repo_name
stringlengths 5
100
| ref
stringlengths 12
67
| path
stringlengths 4
244
| copies
stringlengths 1
8
| content
stringlengths 0
1.05M
⌀ |
|---|---|---|---|---|
pombredanne/pulp
|
refs/heads/master
|
server/test/unit/server/webservices/views/serializers/test_content.py
|
7
|
from datetime import datetime
from unittest import TestCase
from mock import patch
from pulp.common import dateutils
from pulp.server.webservices.views.serializers import content, db
LAST_UPDATED = '_last_updated'
class TestSerialization(TestCase):
@patch('pulp.server.webservices.views.serializers.db.scrub_mongo_fields',
wraps=db.scrub_mongo_fields)
def test_serialization(self, mock):
dt = datetime(2012, 10, 24, 10, 20, tzinfo=dateutils.utc_tz())
last_updated = dateutils.datetime_to_utc_timestamp(dt)
unit = {'_last_updated': last_updated}
serialized = content.content_unit_obj(unit)
mock.assert_called_once_with(unit)
self.assertTrue(LAST_UPDATED in serialized)
self.assertEqual(serialized[LAST_UPDATED], '2012-10-24T10:20:00Z')
def test_serialization_no_last_modified(self):
serialized = content.content_unit_obj({})
self.assertFalse(LAST_UPDATED in serialized)
|
chrislit/abydos
|
refs/heads/master
|
abydos/phonetic/_daitch_mokotoff.py
|
1
|
# Copyright 2014-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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.
#
# Abydos 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 Abydos. If not, see <http://www.gnu.org/licenses/>.
"""abydos.phonetic._daitch_mokotoff.
Daitch-Mokotoff Soundex
"""
from typing import Dict, Tuple, Union, cast
from unicodedata import normalize as unicode_normalize
from ._phonetic import _Phonetic
__all__ = ['DaitchMokotoff']
class DaitchMokotoff(_Phonetic):
"""Daitch-Mokotoff Soundex.
Based on Daitch-Mokotoff Soundex :cite:`Mokotoff:1997`, this returns values
of a word as a set. A collection is necessary since there can be multiple
values for a single word.
.. versionadded:: 0.3.6
"""
_dms_table = {
'STCH': (2, 4, 4),
'DRZ': (4, 4, 4),
'ZH': (4, 4, 4),
'ZHDZH': (2, 4, 4),
'DZH': (4, 4, 4),
'DRS': (4, 4, 4),
'DZS': (4, 4, 4),
'SCHTCH': (2, 4, 4),
'SHTSH': (2, 4, 4),
'SZCZ': (2, 4, 4),
'TZS': (4, 4, 4),
'SZCS': (2, 4, 4),
'STSH': (2, 4, 4),
'SHCH': (2, 4, 4),
'D': (3, 3, 3),
'H': (5, 5, '_'),
'TTSCH': (4, 4, 4),
'THS': (4, 4, 4),
'L': (8, 8, 8),
'P': (7, 7, 7),
'CHS': (5, 54, 54),
'T': (3, 3, 3),
'X': (5, 54, 54),
'OJ': (0, 1, '_'),
'OI': (0, 1, '_'),
'SCHTSH': (2, 4, 4),
'OY': (0, 1, '_'),
'Y': (1, '_', '_'),
'TSH': (4, 4, 4),
'ZDZ': (2, 4, 4),
'TSZ': (4, 4, 4),
'SHT': (2, 43, 43),
'SCHTSCH': (2, 4, 4),
'TTSZ': (4, 4, 4),
'TTZ': (4, 4, 4),
'SCH': (4, 4, 4),
'TTS': (4, 4, 4),
'SZD': (2, 43, 43),
'AI': (0, 1, '_'),
'PF': (7, 7, 7),
'TCH': (4, 4, 4),
'PH': (7, 7, 7),
'TTCH': (4, 4, 4),
'SZT': (2, 43, 43),
'ZDZH': (2, 4, 4),
'EI': (0, 1, '_'),
'G': (5, 5, 5),
'EJ': (0, 1, '_'),
'ZD': (2, 43, 43),
'IU': (1, '_', '_'),
'K': (5, 5, 5),
'O': (0, '_', '_'),
'SHTCH': (2, 4, 4),
'S': (4, 4, 4),
'TRZ': (4, 4, 4),
'SHD': (2, 43, 43),
'DSH': (4, 4, 4),
'CSZ': (4, 4, 4),
'EU': (1, 1, '_'),
'TRS': (4, 4, 4),
'ZS': (4, 4, 4),
'STRZ': (2, 4, 4),
'UY': (0, 1, '_'),
'STRS': (2, 4, 4),
'CZS': (4, 4, 4),
'MN': ('6_6', '6_6', '6_6'),
'UI': (0, 1, '_'),
'UJ': (0, 1, '_'),
'UE': (0, '_', '_'),
'EY': (0, 1, '_'),
'W': (7, 7, 7),
'IA': (1, '_', '_'),
'FB': (7, 7, 7),
'STSCH': (2, 4, 4),
'SCHT': (2, 43, 43),
'NM': ('6_6', '6_6', '6_6'),
'SCHD': (2, 43, 43),
'B': (7, 7, 7),
'DSZ': (4, 4, 4),
'F': (7, 7, 7),
'N': (6, 6, 6),
'CZ': (4, 4, 4),
'R': (9, 9, 9),
'U': (0, '_', '_'),
'V': (7, 7, 7),
'CS': (4, 4, 4),
'Z': (4, 4, 4),
'SZ': (4, 4, 4),
'TSCH': (4, 4, 4),
'KH': (5, 5, 5),
'ST': (2, 43, 43),
'KS': (5, 54, 54),
'SH': (4, 4, 4),
'SC': (2, 4, 4),
'SD': (2, 43, 43),
'DZ': (4, 4, 4),
'ZHD': (2, 43, 43),
'DT': (3, 3, 3),
'ZSH': (4, 4, 4),
'DS': (4, 4, 4),
'TZ': (4, 4, 4),
'TS': (4, 4, 4),
'TH': (3, 3, 3),
'TC': (4, 4, 4),
'A': (0, '_', '_'),
'E': (0, '_', '_'),
'I': (0, '_', '_'),
'AJ': (0, 1, '_'),
'M': (6, 6, 6),
'Q': (5, 5, 5),
'AU': (0, 7, '_'),
'IO': (1, '_', '_'),
'AY': (0, 1, '_'),
'IE': (1, '_', '_'),
'ZSCH': (4, 4, 4),
'CH': ((5, 4), (5, 4), (5, 4)),
'CK': ((5, 45), (5, 45), (5, 45)),
'C': ((5, 4), (5, 4), (5, 4)),
'J': ((1, 4), ('_', 4), ('_', 4)),
'RZ': ((94, 4), (94, 4), (94, 4)),
'RS': ((94, 4), (94, 4), (94, 4)),
}
_dms_order = {
'A': ('AI', 'AJ', 'AU', 'AY', 'A'),
'B': ('B',),
'C': ('CHS', 'CSZ', 'CZS', 'CH', 'CK', 'CS', 'CZ', 'C'),
'D': ('DRS', 'DRZ', 'DSH', 'DSZ', 'DZH', 'DZS', 'DS', 'DT', 'DZ', 'D'),
'E': ('EI', 'EJ', 'EU', 'EY', 'E'),
'F': ('FB', 'F'),
'G': ('G',),
'H': ('H',),
'I': ('IA', 'IE', 'IO', 'IU', 'I'),
'J': ('J',),
'K': ('KH', 'KS', 'K'),
'L': ('L',),
'M': ('MN', 'M'),
'N': ('NM', 'N'),
'O': ('OI', 'OJ', 'OY', 'O'),
'P': ('PF', 'PH', 'P'),
'Q': ('Q',),
'R': ('RS', 'RZ', 'R'),
'S': (
'SCHTSCH',
'SCHTCH',
'SCHTSH',
'SHTCH',
'SHTSH',
'STSCH',
'SCHD',
'SCHT',
'SHCH',
'STCH',
'STRS',
'STRZ',
'STSH',
'SZCS',
'SZCZ',
'SCH',
'SHD',
'SHT',
'SZD',
'SZT',
'SC',
'SD',
'SH',
'ST',
'SZ',
'S',
),
'T': (
'TTSCH',
'TSCH',
'TTCH',
'TTSZ',
'TCH',
'THS',
'TRS',
'TRZ',
'TSH',
'TSZ',
'TTS',
'TTZ',
'TZS',
'TC',
'TH',
'TS',
'TZ',
'T',
),
'U': ('UE', 'UI', 'UJ', 'UY', 'U'),
'V': ('V',),
'W': ('W',),
'X': ('X',),
'Y': ('Y',),
'Z': (
'ZHDZH',
'ZDZH',
'ZSCH',
'ZDZ',
'ZHD',
'ZSH',
'ZD',
'ZH',
'ZS',
'Z',
),
} # type: Dict[str, Tuple[str, ...]]
_uc_v_set = set('AEIJOUY')
_alphabetic = dict(zip((ord(_) for _ in '0123456789'), 'AYstTSKNPLR'))
_alphabetic_non_initials = dict(
zip((ord(_) for _ in '0123456789'), ' A TSKNPLR')
)
def __init__(self, max_length: int = 6, zero_pad: bool = True) -> None:
"""Initialize DaitchMokotoff instance.
Parameters
----------
max_length : int
The length of the code returned (defaults to 6; must be between 6
and 64)
zero_pad : bool
Pad the end of the return value with 0s to achieve a max_length
string
.. versionadded:: 0.4.0
"""
# Require a max_length of at least 6 and not more than 64
if max_length != -1:
self._max_length = min(max(6, max_length), 64)
else:
self._max_length = 64
self._zero_pad = zero_pad
def encode_alpha(self, word: str) -> str:
"""Return the alphabetic Daitch-Mokotoff Soundex code for a word.
Parameters
----------
word : str
The word to transform
Returns
-------
str
The alphabetic Daitch-Mokotoff Soundex value
Examples
--------
>>> pe = DaitchMokotoff()
>>> pe.encode_alpha('Christopher')
'SRSTPR,KRSTPR'
>>> pe.encode_alpha('Niall')
'NL'
>>> pe.encode_alpha('Smith')
'SNT'
>>> pe.encode_alpha('Schmidt')
'SNT'
>>> DaitchMokotoff(max_length=20,
... zero_pad=False).encode_alpha('The quick brown fox')
'TKSKPRPNPKS,TKKPRPNPKS'
.. versionadded:: 0.4.0
.. versionchanged:: 0.6.0
Made return a str only (comma-separated)
"""
alphas = [
code.rstrip('0').translate(self._alphabetic)
for code in self.encode(word).split(',')
]
return ','.join(
code[:1] + code[1:].replace('Y', 'A') for code in alphas
)
def encode(self, word: str) -> str:
"""Return the Daitch-Mokotoff Soundex code for a word.
Parameters
----------
word : str
The word to transform
Returns
-------
str
The Daitch-Mokotoff Soundex value
Examples
--------
>>> pe = DaitchMokotoff()
>>> pe.encode('Christopher')
'494379,594379'
>>> pe.encode('Niall')
'680000'
>>> pe.encode('Smith')
'463000'
>>> pe.encode('Schmidt')
'463000'
>>> DaitchMokotoff(max_length=20,
... zero_pad=False).encode('The quick brown fox')
'35457976754,3557976754'
.. versionadded:: 0.1.0
.. versionchanged:: 0.3.6
Encapsulated in class
.. versionchanged:: 0.6.0
Made return a str only (comma-separated)
"""
dms = [''] # initialize empty code list
# uppercase, normalize, decompose, and filter non-A-Z
word = unicode_normalize('NFKD', word.upper())
word = ''.join(c for c in word if c in self._uc_set)
# Nothing to convert, return base case
if not word:
if self._zero_pad:
return '0' * self._max_length
return '0'
pos = 0
while pos < len(word):
# Iterate through _dms_order, which specifies the possible
# substrings for which codes exist in the Daitch-Mokotoff coding
for sstr in self._dms_order[word[pos]]: # pragma: no branch
if word[pos:].startswith(sstr):
# Having determined a valid substring start, retrieve the
# code
dm_tup = cast(
Tuple[
Union[
int,
str,
Tuple[Union[int, str], Union[int, str]],
],
Union[
int,
str,
Tuple[Union[int, str], Union[int, str]],
],
Union[
int,
str,
Tuple[Union[int, str], Union[int, str]],
],
],
self._dms_table[sstr],
)
# Having retried the code (triple), determine the correct
# positional variant (first, pre-vocalic, elsewhere)
if pos == 0:
dm_val = dm_tup[
0
] # type: Union[int, str, Tuple[Union[int, str], Union[int, str]]] # noqa: E501
elif (
pos + len(sstr) < len(word)
and word[pos + len(sstr)] in self._uc_v_set
):
dm_val = dm_tup[1]
else:
dm_val = dm_tup[2]
# Build the code strings
if isinstance(dm_val, tuple):
dms = [_ + str(dm_val[0]) for _ in dms] + [
_ + str(dm_val[1]) for _ in dms
]
else:
dms = [_ + str(dm_val) for _ in dms]
pos += len(sstr)
break
# Filter out double letters and _ placeholders
dms = [
''.join(c for c in self._delete_consecutive_repeats(_) if c != '_')
for _ in dms
]
# Trim codes and return set
if self._zero_pad:
dms = [
(_ + ('0' * self._max_length))[: self._max_length] for _ in dms
]
else:
dms = [_[: self._max_length] for _ in dms]
return ','.join(sorted(set(dms)))
if __name__ == '__main__':
import doctest
doctest.testmod()
|
krismcfarlin/todo_angular_endpoints
|
refs/heads/master
|
bp_includes/external/requests/packages/chardet/big5prober.py
|
2930
|
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import Big5DistributionAnalysis
from .mbcssm import Big5SMModel
class Big5Prober(MultiByteCharSetProber):
def __init__(self):
MultiByteCharSetProber.__init__(self)
self._mCodingSM = CodingStateMachine(Big5SMModel)
self._mDistributionAnalyzer = Big5DistributionAnalysis()
self.reset()
def get_charset_name(self):
return "Big5"
|
sjuxax/raggregate
|
refs/heads/master
|
raggregate/models/user_preference.py
|
1
|
from raggregate.models import *
from sqlalchemy import Column
from sqlalchemy import UnicodeText
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from raggregate.models.user import User
from raggregate.guid_recipe import GUID
class UserPreference(Base):
__tablename__ = 'user_preferences'
id = Column(GUID, primary_key=True)
user_id = Column(GUID, ForeignKey('users.id'))
preference_list = Column(UnicodeText)
user = relationship('User', backref='preferences')
def __init__(self, user_id, preference_list):
self.user_id = user_id
self.preference_list = preference_list
|
elkingtonmcb/nupic
|
refs/heads/master
|
external/linux32/lib/python2.6/site-packages/matplotlib/units.py
|
70
|
"""
The classes here provide support for using custom classes with
matplotlib, eg those that do not expose the array interface but know
how to converter themselves to arrays. It also supoprts classes with
units and units conversion. Use cases include converters for custom
objects, eg a list of datetime objects, as well as for objects that
are unit aware. We don't assume any particular units implementation,
rather a units implementation must provide a ConversionInterface, and
the register with the Registry converter dictionary. For example,
here is a complete implementation which support plotting with native
datetime objects
import matplotlib.units as units
import matplotlib.dates as dates
import matplotlib.ticker as ticker
import datetime
class DateConverter(units.ConversionInterface):
def convert(value, unit):
'convert value to a scalar or array'
return dates.date2num(value)
convert = staticmethod(convert)
def axisinfo(unit):
'return major and minor tick locators and formatters'
if unit!='date': return None
majloc = dates.AutoDateLocator()
majfmt = dates.AutoDateFormatter(majloc)
return AxisInfo(majloc=majloc,
majfmt=majfmt,
label='date')
axisinfo = staticmethod(axisinfo)
def default_units(x):
'return the default unit for x or None'
return 'date'
default_units = staticmethod(default_units)
# finally we register our object type with a converter
units.registry[datetime.date] = DateConverter()
"""
import numpy as np
from matplotlib.cbook import iterable, is_numlike
class AxisInfo:
'information to support default axis labeling and tick labeling'
def __init__(self, majloc=None, minloc=None,
majfmt=None, minfmt=None, label=None):
"""
majloc and minloc: TickLocators for the major and minor ticks
majfmt and minfmt: TickFormatters for the major and minor ticks
label: the default axis label
If any of the above are None, the axis will simply use the default
"""
self.majloc = majloc
self.minloc = minloc
self.majfmt = majfmt
self.minfmt = minfmt
self.label = label
class ConversionInterface:
"""
The minimal interface for a converter to take custom instances (or
sequences) and convert them to values mpl can use
"""
def axisinfo(unit):
'return an units.AxisInfo instance for unit'
return None
axisinfo = staticmethod(axisinfo)
def default_units(x):
'return the default unit for x or None'
return None
default_units = staticmethod(default_units)
def convert(obj, unit):
"""
convert obj using unit. If obj is a sequence, return the
converted sequence. The ouput must be a sequence of scalars
that can be used by the numpy array layer
"""
return obj
convert = staticmethod(convert)
def is_numlike(x):
"""
The matplotlib datalim, autoscaling, locators etc work with
scalars which are the units converted to floats given the
current unit. The converter may be passed these floats, or
arrays of them, even when units are set. Derived conversion
interfaces may opt to pass plain-ol unitless numbers through
the conversion interface and this is a helper function for
them.
"""
if iterable(x):
for thisx in x:
return is_numlike(thisx)
else:
return is_numlike(x)
is_numlike = staticmethod(is_numlike)
class Registry(dict):
"""
register types with conversion interface
"""
def __init__(self):
dict.__init__(self)
self._cached = {}
def get_converter(self, x):
'get the converter interface instance for x, or None'
if not len(self): return None # nothing registered
#DISABLED idx = id(x)
#DISABLED cached = self._cached.get(idx)
#DISABLED if cached is not None: return cached
converter = None
classx = getattr(x, '__class__', None)
if classx is not None:
converter = self.get(classx)
if converter is None and iterable(x):
# if this is anything but an object array, we'll assume
# there are no custom units
if isinstance(x, np.ndarray) and x.dtype != np.object:
return None
for thisx in x:
converter = self.get_converter( thisx )
return converter
#DISABLED self._cached[idx] = converter
return converter
registry = Registry()
|
hsiaoyi0504/scikit-learn
|
refs/heads/master
|
setup.py
|
143
|
#! /usr/bin/env python
#
# Copyright (C) 2007-2009 Cournapeau David <cournape@gmail.com>
# 2010 Fabian Pedregosa <fabian.pedregosa@inria.fr>
# License: 3-clause BSD
descr = """A set of python modules for machine learning and data mining"""
import sys
import os
import shutil
from distutils.command.clean import clean as Clean
if sys.version_info[0] < 3:
import __builtin__ as builtins
else:
import builtins
# This is a bit (!) hackish: we are setting a global variable so that the main
# sklearn __init__ can detect if it is being loaded by the setup routine, to
# avoid attempting to load components that aren't built yet:
# the numpy distutils extensions that are used by scikit-learn to recursively
# build the compiled extensions in sub-packages is based on the Python import
# machinery.
builtins.__SKLEARN_SETUP__ = True
DISTNAME = 'scikit-learn'
DESCRIPTION = 'A set of python modules for machine learning and data mining'
with open('README.rst') as f:
LONG_DESCRIPTION = f.read()
MAINTAINER = 'Andreas Mueller'
MAINTAINER_EMAIL = 'amueller@ais.uni-bonn.de'
URL = 'http://scikit-learn.org'
LICENSE = 'new BSD'
DOWNLOAD_URL = 'http://sourceforge.net/projects/scikit-learn/files/'
# We can actually import a restricted version of sklearn that
# does not need the compiled code
import sklearn
VERSION = sklearn.__version__
# Optional setuptools features
# We need to import setuptools early, if we want setuptools features,
# as it monkey-patches the 'setup' function
# For some commands, use setuptools
SETUPTOOLS_COMMANDS = set([
'develop', 'release', 'bdist_egg', 'bdist_rpm',
'bdist_wininst', 'install_egg_info', 'build_sphinx',
'egg_info', 'easy_install', 'upload', 'bdist_wheel',
'--single-version-externally-managed',
])
if SETUPTOOLS_COMMANDS.intersection(sys.argv):
import setuptools
extra_setuptools_args = dict(
zip_safe=False, # the package can run out of an .egg file
include_package_data=True,
)
else:
extra_setuptools_args = dict()
# Custom clean command to remove build artifacts
class CleanCommand(Clean):
description = "Remove build artifacts from the source tree"
def run(self):
Clean.run(self)
if os.path.exists('build'):
shutil.rmtree('build')
for dirpath, dirnames, filenames in os.walk('sklearn'):
for filename in filenames:
if (filename.endswith('.so') or filename.endswith('.pyd')
or filename.endswith('.dll')
or filename.endswith('.pyc')):
os.unlink(os.path.join(dirpath, filename))
for dirname in dirnames:
if dirname == '__pycache__':
shutil.rmtree(os.path.join(dirpath, dirname))
cmdclass = {'clean': CleanCommand}
# Optional wheelhouse-uploader features
# To automate release of binary packages for scikit-learn we need a tool
# to download the packages generated by travis and appveyor workers (with
# version number matching the current release) and upload them all at once
# to PyPI at release time.
# The URL of the artifact repositories are configured in the setup.cfg file.
WHEELHOUSE_UPLOADER_COMMANDS = set(['fetch_artifacts', 'upload_all'])
if WHEELHOUSE_UPLOADER_COMMANDS.intersection(sys.argv):
import wheelhouse_uploader.cmd
cmdclass.update(vars(wheelhouse_uploader.cmd))
def configuration(parent_package='', top_path=None):
if os.path.exists('MANIFEST'):
os.remove('MANIFEST')
from numpy.distutils.misc_util import Configuration
config = Configuration(None, parent_package, top_path)
# Avoid non-useful msg:
# "Ignoring attempt to set 'name' (from ... "
config.set_options(ignore_setup_xxx_py=True,
assume_default_configuration=True,
delegate_options_to_subpackages=True,
quiet=True)
config.add_subpackage('sklearn')
return config
def is_scipy_installed():
try:
import scipy
except ImportError:
return False
return True
def is_numpy_installed():
try:
import numpy
except ImportError:
return False
return True
def setup_package():
metadata = dict(name=DISTNAME,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
license=LICENSE,
url=URL,
version=VERSION,
download_url=DOWNLOAD_URL,
long_description=LONG_DESCRIPTION,
classifiers=['Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'License :: OSI Approved',
'Programming Language :: C',
'Programming Language :: Python',
'Topic :: Software Development',
'Topic :: Scientific/Engineering',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: MacOS',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
cmdclass=cmdclass,
**extra_setuptools_args)
if (len(sys.argv) >= 2
and ('--help' in sys.argv[1:] or sys.argv[1]
in ('--help-commands', 'egg_info', '--version', 'clean'))):
# For these actions, NumPy is not required.
#
# They are required to succeed without Numpy for example when
# pip is used to install Scikit-learn when Numpy is not yet present in
# the system.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
metadata['version'] = VERSION
else:
if is_numpy_installed() is False:
raise ImportError("Numerical Python (NumPy) is not installed.\n"
"scikit-learn requires NumPy.\n"
"Installation instructions are available on scikit-learn website: "
"http://scikit-learn.org/stable/install.html\n")
if is_scipy_installed() is False:
raise ImportError("Scientific Python (SciPy) is not installed.\n"
"scikit-learn requires SciPy.\n"
"Installation instructions are available on scikit-learn website: "
"http://scikit-learn.org/stable/install.html\n")
from numpy.distutils.core import setup
metadata['configuration'] = configuration
setup(**metadata)
if __name__ == "__main__":
setup_package()
|
jgillis/casadi
|
refs/heads/develop
|
experimental/greg/ode.py
|
1
|
#
# This file is part of CasADi.
#
# CasADi -- A symbolic framework for dynamic optimization.
# Copyright (C) 2010 by Joel Andersson, Moritz Diehl, K.U.Leuven. All rights reserved.
#
# CasADi is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any later version.
#
# CasADi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with CasADi; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
#
import numpy as np
import casadi as C
class Ode():
def __init__(self, name):
self.name = name
self.locked = False
self.states = []
self.actions = []
self.params = []
def setDxdt(self, dxdt):
if self.locked:
errStr = "Ode "+self.name+" has already been assigned to an Ocp and is in read-only mode"
raise ValueError(errStr)
self.dxdt = dxdt
def addStates(self, states):
if self.locked:
errStr = "Ode "+self.name+" has already been assigned to an Ocp and is in read-only mode"
raise ValueError(errStr)
if not isinstance(states, list):
states = [states]
for x in states:
self._assertUniqueName(x)
self.states += states
def addActions(self, actions):
if self.locked:
errStr = "Ode "+self.name+" has already been assigned to an Ocp and is in read-only mode"
raise ValueError(errStr)
if not isinstance(actions, list):
actions = [actions]
for u in actions:
self._assertUniqueName(u)
self.actions += actions
def addParams(self, params):
if self.locked:
errStr = "Ode "+self.name+" has already been assigned to an Ocp and is in read-only mode"
raise ValueError(errStr)
if not isinstance(params, list):
params = [params]
for p in params:
self._assertUniqueName(p)
self.params += params
def _Nx(self):
return len(self.states)
def _Nu(self):
return len(self.actions)
def _Nxu(self):
return self._Nx() + self._Nu()
def _Np(self):
return len(self.params)
def _stateVecToDict(self, stateVector):
d = {}
for (k,x) in enumerate(self.states):
d[x] = stateVector[k]
return d
def _actionVecToDict(self, actionVector):
d = {}
for (k,u) in enumerate(self.actions):
d[u] = actionVector[k]
return d
def _paramVecToDict(self, paramVector):
d = {}
for (k,p) in enumerate(self.params):
d[p] = paramVector[k]
return d
def _stateDictToVec(self, stateDict):
stateList = [stateDict[s] for s in self.states]
# concatanate and return appropriate type
if isinstance(stateList[0], C.MX): # MX
return C.vertcat(stateList)
elif isinstance(stateList[0], C.SX): # SX
return C.vertcat(stateList)
else: # numpy array
return np.concatenate(stateList, axis=0)
def _dxVector_dt(self, stateVector, actionVector, paramVector, t):
x = self._stateVecToDict(stateVector)
u = self._actionVecToDict(actionVector)
p = self._paramVecToDict(paramVector)
xDot = self.dxdt(x, u, p, t)
return self._stateDictToVec(xDot)
def _assertUniqueName(self, xup):
if xup in self.states+self.actions+self.params:
errStr = "Name "+xup+" is not unique"
raise NameError(errStr)
# inputs all are lists or vectors
def rk4Step(self, x0Vec, u0Vec, u1Vec, pVec, t0, t1):
dt = t1-t0 # time step
k1 = self._dxVector_dt( x0Vec , u0Vec, pVec, t0 )
k2 = self._dxVector_dt( x0Vec + 0.5*dt*k1, 0.5*(u0Vec+u1Vec), pVec, t0 + 0.5*dt )
k3 = self._dxVector_dt( x0Vec + 0.5*dt*k2, 0.5*(u0Vec+u1Vec), pVec, t0 + 0.5*dt )
k4 = self._dxVector_dt( x0Vec + dt*k3, u1Vec, pVec, t0 + dt )
return x0Vec + dt*(k1 + 2*k2 + 2*k3 + k4)/6
# return x0Vec + dt*k1 # euler
# multiple rk4 steps on a single shooting interval
def rk4Steps(self, x0Vec, u0Vec, u1Vec, pVec, t0, t1):
N = 1
x = x0Vec
for k in range(N):
dt = (t1 - t0)/np.double(N)
t0_ = t0+k*dt
t1_ = t0+(k+1)*dt
slider0 = (t0_-t0)/(t1 - t0)
slider1 = (t1_-t0)/(t1 - t0)
u0_ = u0Vec*(1.0 - slider0) + u1Vec*slider0
u1_ = u0Vec*(1.0 - slider1) + u1Vec*slider1
x = self.rk4Step(x, u0_, u1_, pVec, t0_, t1_)
return x
def runSim(self, time, x0, u, p):
N = len(time)
X = np.matrix(np.zeros([self._Nx(), N]))
X[:,0] = x0
for k in range(N-1):
u0 = u[:,k]
u1 = u[:,k+1]
dt = time[k+1] - time[k]
X[:,k+1] = self.rk4Step(X[:,k], u0, u1, p, time[k], time[k+1])
return X
|
chunywang/crosswalk-test-suite
|
refs/heads/master
|
misc/webdriver-w3c-tests/client/webelement.py
|
12
|
"""Element-level WebDriver operations."""
import searchcontext
class WebElement(searchcontext.SearchContext):
"""Corresponds to a DOM element in the current page."""
def __init__(self, driver, id):
self._driver = driver
self._id = id
# Set value of mode used by SearchContext
self.mode = driver.mode
def execute(self, method, path, name, body=None):
"""Execute a command against this WebElement."""
return self._driver.execute(
method, '/element/%s%s' % (self._id, path), name, body)
def is_displayed(self):
"""Is this element displayed?"""
return self.execute('GET', '/displayed', 'isDisplayed')
def is_selected(self):
"""Is this checkbox, radio button, or option selected?"""
return self.execute('GET', '/selected', 'isSelected')
def get_attribute(self, name):
"""Get the value of an element property or attribute."""
return self.execute('GET', '/attribute/%s' %
name, 'getElementAttribute')
def get_text(self):
"""Get the visible text for this element."""
return self.execute('GET', '/text', 'text')
def click(self):
"""Click on this element."""
return self.execute('POST', '/click', 'click')
def clear(self):
"""Clear the contents of the this text input."""
self.execute('POST', '/clear', 'clear')
def send_keys(self, keys):
"""Send keys to this text input or body element."""
if isinstance(keys, str):
keys = [keys]
self.execute('POST', '/value', 'sendKeys', {'value': keys})
def to_json(self):
return {'ELEMENT': self.id}
|
javaos74/neutron
|
refs/heads/master
|
neutron/plugins/ml2/drivers/opendaylight/__init__.py
|
12133432
| |
stacksync/web
|
refs/heads/master
|
webclient/__init__.py
|
12133432
| |
paulrouget/servo
|
refs/heads/master
|
tests/wpt/web-platform-tests/service-workers/service-worker/resources/import-mime-type-worker.py
|
71
|
def main(request, response):
if 'mime' in request.GET:
return (
[('Content-Type', 'application/javascript')],
"importScripts('./mime-type-worker.py?mime={0}');".format(request.GET['mime'])
)
return (
[('Content-Type', 'application/javascript')],
"importScripts('./mime-type-worker.py');"
)
|
xxsergzzxx/python-for-android
|
refs/heads/master
|
python-modules/twisted/twisted/mail/_version.py
|
49
|
# This is an auto-generated file. Do not edit it.
from twisted.python import versions
version = versions.Version('twisted.mail', 10, 2, 0)
|
yesbox/ansible
|
refs/heads/devel
|
test/units/__init__.py
|
267
|
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
|
harmy/kbengine
|
refs/heads/master
|
kbe/res/scripts/common/Lib/test/test_pty.py
|
3
|
from test.support import verbose, run_unittest, import_module, reap_children
#Skip these tests if either fcntl or termios is not available
fcntl = import_module('fcntl')
import_module('termios')
import errno
import pty
import os
import sys
import signal
import unittest
TEST_STRING_1 = b"I wish to buy a fish license.\n"
TEST_STRING_2 = b"For my pet fish, Eric.\n"
if verbose:
def debug(msg):
print(msg)
else:
def debug(msg):
pass
def normalize_output(data):
# Some operating systems do conversions on newline. We could possibly
# fix that by doing the appropriate termios.tcsetattr()s. I couldn't
# figure out the right combo on Tru64 and I don't have an IRIX box.
# So just normalize the output and doc the problem O/Ses by allowing
# certain combinations for some platforms, but avoid allowing other
# differences (like extra whitespace, trailing garbage, etc.)
# This is about the best we can do without getting some feedback
# from someone more knowledgable.
# OSF/1 (Tru64) apparently turns \n into \r\r\n.
if data.endswith(b'\r\r\n'):
return data.replace(b'\r\r\n', b'\n')
# IRIX apparently turns \n into \r\n.
if data.endswith(b'\r\n'):
return data.replace(b'\r\n', b'\n')
return data
# Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
# because pty code is not too portable.
# XXX(nnorwitz): these tests leak fds when there is an error.
class PtyTest(unittest.TestCase):
def setUp(self):
# isatty() and close() can hang on some platforms. Set an alarm
# before running the test to make sure we don't hang forever.
self.old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
signal.alarm(10)
def tearDown(self):
# remove alarm, restore old alarm handler
signal.alarm(0)
signal.signal(signal.SIGALRM, self.old_alarm)
def handle_sig(self, sig, frame):
self.fail("isatty hung")
def test_basic(self):
try:
debug("Calling master_open()")
master_fd, slave_name = pty.master_open()
debug("Got master_fd '%d', slave_name '%s'" %
(master_fd, slave_name))
debug("Calling slave_open(%r)" % (slave_name,))
slave_fd = pty.slave_open(slave_name)
debug("Got slave_fd '%d'" % slave_fd)
except OSError:
# " An optional feature could not be imported " ... ?
raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
# Solaris requires reading the fd before anything is returned.
# My guess is that since we open and close the slave fd
# in master_open(), we need to read the EOF.
# Ensure the fd is non-blocking in case there's nothing to read.
orig_flags = fcntl.fcntl(master_fd, fcntl.F_GETFL)
fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags | os.O_NONBLOCK)
try:
s1 = os.read(master_fd, 1024)
self.assertEqual(b'', s1)
except OSError as e:
if e.errno != errno.EAGAIN:
raise
# Restore the original flags.
fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags)
debug("Writing to slave_fd")
os.write(slave_fd, TEST_STRING_1)
s1 = os.read(master_fd, 1024)
self.assertEqual(b'I wish to buy a fish license.\n',
normalize_output(s1))
debug("Writing chunked output")
os.write(slave_fd, TEST_STRING_2[:5])
os.write(slave_fd, TEST_STRING_2[5:])
s2 = os.read(master_fd, 1024)
self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
os.close(slave_fd)
os.close(master_fd)
def test_fork(self):
debug("calling pty.fork()")
pid, master_fd = pty.fork()
if pid == pty.CHILD:
# stdout should be connected to a tty.
if not os.isatty(1):
debug("Child's fd 1 is not a tty?!")
os._exit(3)
# After pty.fork(), the child should already be a session leader.
# (on those systems that have that concept.)
debug("In child, calling os.setsid()")
try:
os.setsid()
except OSError:
# Good, we already were session leader
debug("Good: OSError was raised.")
pass
except AttributeError:
# Have pty, but not setsid()?
debug("No setsid() available?")
pass
except:
# We don't want this error to propagate, escaping the call to
# os._exit() and causing very peculiar behavior in the calling
# regrtest.py !
# Note: could add traceback printing here.
debug("An unexpected error was raised.")
os._exit(1)
else:
debug("os.setsid() succeeded! (bad!)")
os._exit(2)
os._exit(4)
else:
debug("Waiting for child (%d) to finish." % pid)
# In verbose mode, we have to consume the debug output from the
# child or the child will block, causing this test to hang in the
# parent's waitpid() call. The child blocks after a
# platform-dependent amount of data is written to its fd. On
# Linux 2.6, it's 4000 bytes and the child won't block, but on OS
# X even the small writes in the child above will block it. Also
# on Linux, the read() will throw an OSError (input/output error)
# when it tries to read past the end of the buffer but the child's
# already exited, so catch and discard those exceptions. It's not
# worth checking for EIO.
while True:
try:
data = os.read(master_fd, 80)
except OSError:
break
if not data:
break
sys.stdout.write(str(data.replace(b'\r\n', b'\n'),
encoding='ascii'))
##line = os.read(master_fd, 80)
##lines = line.replace('\r\n', '\n').split('\n')
##if False and lines != ['In child, calling os.setsid()',
## 'Good: OSError was raised.', '']:
## raise TestFailed("Unexpected output from child: %r" % line)
(pid, status) = os.waitpid(pid, 0)
res = status >> 8
debug("Child (%d) exited with status %d (%d)." % (pid, res, status))
if res == 1:
self.fail("Child raised an unexpected exception in os.setsid()")
elif res == 2:
self.fail("pty.fork() failed to make child a session leader.")
elif res == 3:
self.fail("Child spawned by pty.fork() did not have a tty as stdout")
elif res != 4:
self.fail("pty.fork() failed for unknown reasons.")
##debug("Reading from master_fd now that the child has exited")
##try:
## s1 = os.read(master_fd, 1024)
##except os.error:
## pass
##else:
## raise TestFailed("Read from master_fd did not raise exception")
os.close(master_fd)
# pty.fork() passed.
def test_main(verbose=None):
try:
run_unittest(PtyTest)
finally:
reap_children()
if __name__ == "__main__":
test_main()
|
jmwright/cadquery-freecad-module
|
refs/heads/master
|
Libs/requests/hooks.py
|
136
|
# -*- coding: utf-8 -*-
"""
requests.hooks
~~~~~~~~~~~~~~
This module provides the capabilities for the Requests hooks system.
Available hooks:
``response``:
The response generated from a Request.
"""
HOOKS = ['response']
def default_hooks():
return {event: [] for event in HOOKS}
# TODO: response is the only one
def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
return hook_data
|
joariasl/odoo
|
refs/heads/8.0
|
addons/l10n_pe/__openerp__.py
|
260
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 Cubic ERP - Teradata SAC (<http://cubicerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Peru Localization Chart Account',
'version': '1.0',
'description': """
Peruvian accounting chart and tax localization. According the PCGE 2010.
========================================================================
Plan contable peruano e impuestos de acuerdo a disposiciones vigentes de la
SUNAT 2011 (PCGE 2010).
""",
'author': ['Cubic ERP'],
'website': 'http://cubicERP.com',
'category': 'Localization/Account Charts',
'depends': ['account_chart'],
'data':[
'account_tax_code.xml',
'l10n_pe_chart.xml',
'account_tax.xml',
'l10n_pe_wizard.xml',
],
'demo': [],
'active': False,
'installable': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
HandyCodeJob/mikeandzoey-site
|
refs/heads/master
|
src/rsvp/migrations/0015_auto_20150918_1303.py
|
1
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('rsvp', '0014_logistics'),
]
operations = [
migrations.AlterField(
model_name='logistics',
name='name',
field=models.CharField(blank=True, max_length=128, verbose_name='Name of the location', null=True),
),
]
|
jarvys/django-1.7-jdb
|
refs/heads/master
|
django/contrib/formtools/tests/tests.py
|
53
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import os
import unittest
import warnings
from django import http
from django.contrib.formtools import preview, utils
from django.test import TestCase, override_settings
from django.utils._os import upath
from django.contrib.formtools.tests.forms import (
HashTestBlankForm, HashTestForm, TestForm,
)
success_string = "Done was called!"
success_string_encoded = success_string.encode()
class TestFormPreview(preview.FormPreview):
def get_context(self, request, form):
context = super(TestFormPreview, self).get_context(request, form)
context.update({'custom_context': True})
return context
def get_initial(self, request):
return {'field1': 'Works!'}
def done(self, request, cleaned_data):
return http.HttpResponse(success_string)
@override_settings(
TEMPLATE_DIRS=(
os.path.join(os.path.dirname(upath(__file__)), 'templates'),
),
)
class PreviewTests(TestCase):
urls = 'django.contrib.formtools.tests.urls'
def setUp(self):
super(PreviewTests, self).setUp()
# Create a FormPreview instance to share between tests
self.preview = preview.FormPreview(TestForm)
input_template = '<input type="hidden" name="%s" value="%s" />'
self.input = input_template % (self.preview.unused_name('stage'), "%d")
self.test_data = {'field1': 'foo', 'field1_': 'asdf'}
def test_unused_name(self):
"""
Verifies name mangling to get uniue field name.
"""
self.assertEqual(self.preview.unused_name('field1'), 'field1__')
def test_form_get(self):
"""
Test contrib.formtools.preview form retrieval.
Use the client library to see if we can successfully retrieve
the form (mostly testing the setup ROOT_URLCONF
process). Verify that an additional hidden input field
is created to manage the stage.
"""
response = self.client.get('/preview/')
stage = self.input % 1
self.assertContains(response, stage, 1)
self.assertEqual(response.context['custom_context'], True)
self.assertEqual(response.context['form'].initial, {'field1': 'Works!'})
def test_form_preview(self):
"""
Test contrib.formtools.preview form preview rendering.
Use the client library to POST to the form to see if a preview
is returned. If we do get a form back check that the hidden
value is correctly managing the state of the form.
"""
# Pass strings for form submittal and add stage variable to
# show we previously saw first stage of the form.
self.test_data.update({'stage': 1, 'date1': datetime.date(2006, 10, 25)})
response = self.client.post('/preview/', self.test_data)
# Check to confirm stage is set to 2 in output form.
stage = self.input % 2
self.assertContains(response, stage, 1)
def test_form_submit(self):
"""
Test contrib.formtools.preview form submittal.
Use the client library to POST to the form with stage set to 3
to see if our forms done() method is called. Check first
without the security hash, verify failure, retry with security
hash and verify success.
"""
# Pass strings for form submittal and add stage variable to
# show we previously saw first stage of the form.
self.test_data.update({'stage': 2, 'date1': datetime.date(2006, 10, 25)})
response = self.client.post('/preview/', self.test_data)
self.assertNotEqual(response.content, success_string_encoded)
hash = self.preview.security_hash(None, TestForm(self.test_data))
self.test_data.update({'hash': hash})
response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.content, success_string_encoded)
def test_bool_submit(self):
"""
Test contrib.formtools.preview form submittal when form contains:
BooleanField(required=False)
Ticket: #6209 - When an unchecked BooleanField is previewed, the preview
form's hash would be computed with no value for ``bool1``. However, when
the preview form is rendered, the unchecked hidden BooleanField would be
rendered with the string value 'False'. So when the preview form is
resubmitted, the hash would be computed with the value 'False' for
``bool1``. We need to make sure the hashes are the same in both cases.
"""
self.test_data.update({'stage': 2})
hash = self.preview.security_hash(None, TestForm(self.test_data))
self.test_data.update({'hash': hash, 'bool1': 'False'})
with warnings.catch_warnings(record=True):
response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.content, success_string_encoded)
def test_form_submit_good_hash(self):
"""
Test contrib.formtools.preview form submittal, using a correct
hash
"""
# Pass strings for form submittal and add stage variable to
# show we previously saw first stage of the form.
self.test_data.update({'stage': 2})
response = self.client.post('/preview/', self.test_data)
self.assertNotEqual(response.content, success_string_encoded)
hash = utils.form_hmac(TestForm(self.test_data))
self.test_data.update({'hash': hash})
response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.content, success_string_encoded)
def test_form_submit_bad_hash(self):
"""
Test contrib.formtools.preview form submittal does not proceed
if the hash is incorrect.
"""
# Pass strings for form submittal and add stage variable to
# show we previously saw first stage of the form.
self.test_data.update({'stage': 2})
response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.status_code, 200)
self.assertNotEqual(response.content, success_string_encoded)
hash = utils.form_hmac(TestForm(self.test_data)) + "bad"
self.test_data.update({'hash': hash})
response = self.client.post('/previewpreview/', self.test_data)
self.assertNotEqual(response.content, success_string_encoded)
class FormHmacTests(unittest.TestCase):
def test_textfield_hash(self):
"""
Regression test for #10034: the hash generation function should ignore
leading/trailing whitespace so as to be friendly to broken browsers that
submit it (usually in textareas).
"""
f1 = HashTestForm({'name': 'joe', 'bio': 'Speaking español.'})
f2 = HashTestForm({'name': ' joe', 'bio': 'Speaking español. '})
hash1 = utils.form_hmac(f1)
hash2 = utils.form_hmac(f2)
self.assertEqual(hash1, hash2)
def test_empty_permitted(self):
"""
Regression test for #10643: the security hash should allow forms with
empty_permitted = True, or forms where data has not changed.
"""
f1 = HashTestBlankForm({})
f2 = HashTestForm({}, empty_permitted=True)
hash1 = utils.form_hmac(f1)
hash2 = utils.form_hmac(f2)
self.assertEqual(hash1, hash2)
|
webdev1001/ansible
|
refs/heads/devel
|
v2/test/parsing/test_mod_args.py
|
109
|
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.parsing.mod_args import ModuleArgsParser
from ansible.errors import AnsibleParserError
from ansible.compat.tests import unittest
class TestModArgsDwim(unittest.TestCase):
# TODO: add tests that construct ModuleArgsParser with a task reference
# TODO: verify the AnsibleError raised on failure knows the task
# and the task knows the line numbers
def setUp(self):
pass
def _debug(self, mod, args, to):
print("RETURNED module = {0}".format(mod))
print(" args = {0}".format(args))
print(" to = {0}".format(to))
def tearDown(self):
pass
def test_basic_shell(self):
m = ModuleArgsParser(dict(shell='echo hi'))
mod, args, to = m.parse()
self._debug(mod, args, to)
self.assertEqual(mod, 'command')
self.assertEqual(args, dict(
_raw_params = 'echo hi',
_uses_shell = True,
))
self.assertIsNone(to)
def test_basic_command(self):
m = ModuleArgsParser(dict(command='echo hi'))
mod, args, to = m.parse()
self._debug(mod, args, to)
self.assertEqual(mod, 'command')
self.assertEqual(args, dict(
_raw_params = 'echo hi',
))
self.assertIsNone(to)
def test_shell_with_modifiers(self):
m = ModuleArgsParser(dict(shell='/bin/foo creates=/tmp/baz removes=/tmp/bleep'))
mod, args, to = m.parse()
self._debug(mod, args, to)
self.assertEqual(mod, 'command')
self.assertEqual(args, dict(
creates = '/tmp/baz',
removes = '/tmp/bleep',
_raw_params = '/bin/foo',
_uses_shell = True,
))
self.assertIsNone(to)
def test_normal_usage(self):
m = ModuleArgsParser(dict(copy='src=a dest=b'))
mod, args, to = m.parse()
self._debug(mod, args, to)
self.assertEqual(mod, 'copy')
self.assertEqual(args, dict(src='a', dest='b'))
self.assertIsNone(to)
def test_complex_args(self):
m = ModuleArgsParser(dict(copy=dict(src='a', dest='b')))
mod, args, to = m.parse()
self._debug(mod, args, to)
self.assertEqual(mod, 'copy')
self.assertEqual(args, dict(src='a', dest='b'))
self.assertIsNone(to)
def test_action_with_complex(self):
m = ModuleArgsParser(dict(action=dict(module='copy', src='a', dest='b')))
mod, args, to = m.parse()
self._debug(mod, args, to)
self.assertEqual(mod, 'copy')
self.assertEqual(args, dict(src='a', dest='b'))
self.assertIsNone(to)
def test_action_with_complex_and_complex_args(self):
m = ModuleArgsParser(dict(action=dict(module='copy', args=dict(src='a', dest='b'))))
mod, args, to = m.parse()
self._debug(mod, args, to)
self.assertEqual(mod, 'copy')
self.assertEqual(args, dict(src='a', dest='b'))
self.assertIsNone(to)
def test_local_action_string(self):
m = ModuleArgsParser(dict(local_action='copy src=a dest=b'))
mod, args, to = m.parse()
self._debug(mod, args, to)
self.assertEqual(mod, 'copy')
self.assertEqual(args, dict(src='a', dest='b'))
self.assertIs(to, 'localhost')
def test_multiple_actions(self):
m = ModuleArgsParser(dict(action='shell echo hi', local_action='shell echo hi'))
self.assertRaises(AnsibleParserError, m.parse)
m = ModuleArgsParser(dict(action='shell echo hi', shell='echo hi'))
self.assertRaises(AnsibleParserError, m.parse)
m = ModuleArgsParser(dict(local_action='shell echo hi', shell='echo hi'))
self.assertRaises(AnsibleParserError, m.parse)
m = ModuleArgsParser(dict(ping='data=hi', shell='echo hi'))
self.assertRaises(AnsibleParserError, m.parse)
|
jazkarta/edx-platform
|
refs/heads/master
|
openedx/core/djangoapps/content/course_overviews/migrations/0001_initial.py
|
80
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'CourseOverview'
db.create_table('course_overviews_courseoverview', (
('id', self.gf('xmodule_django.models.CourseKeyField')(max_length=255, primary_key=True, db_index=True)),
('_location', self.gf('xmodule_django.models.UsageKeyField')(max_length=255)),
('display_name', self.gf('django.db.models.fields.TextField')(null=True)),
('display_number_with_default', self.gf('django.db.models.fields.TextField')()),
('display_org_with_default', self.gf('django.db.models.fields.TextField')()),
('start', self.gf('django.db.models.fields.DateTimeField')(null=True)),
('end', self.gf('django.db.models.fields.DateTimeField')(null=True)),
('advertised_start', self.gf('django.db.models.fields.TextField')(null=True)),
('course_image_url', self.gf('django.db.models.fields.TextField')()),
('facebook_url', self.gf('django.db.models.fields.TextField')(null=True)),
('social_sharing_url', self.gf('django.db.models.fields.TextField')(null=True)),
('end_of_course_survey_url', self.gf('django.db.models.fields.TextField')(null=True)),
('certificates_display_behavior', self.gf('django.db.models.fields.TextField')(null=True)),
('certificates_show_before_end', self.gf('django.db.models.fields.BooleanField')(default=False)),
('has_any_active_web_certificate', self.gf('django.db.models.fields.BooleanField')(default=False)),
('cert_name_short', self.gf('django.db.models.fields.TextField')()),
('cert_name_long', self.gf('django.db.models.fields.TextField')()),
('lowest_passing_grade', self.gf('django.db.models.fields.DecimalField')(max_digits=5, decimal_places=2)),
('mobile_available', self.gf('django.db.models.fields.BooleanField')(default=False)),
('visible_to_staff_only', self.gf('django.db.models.fields.BooleanField')(default=False)),
('_pre_requisite_courses_json', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal('course_overviews', ['CourseOverview'])
def backwards(self, orm):
# Deleting model 'CourseOverview'
db.delete_table('course_overviews_courseoverview')
models = {
'course_overviews.courseoverview': {
'Meta': {'object_name': 'CourseOverview'},
'_location': ('xmodule_django.models.UsageKeyField', [], {'max_length': '255'}),
'_pre_requisite_courses_json': ('django.db.models.fields.TextField', [], {}),
'advertised_start': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'cert_name_long': ('django.db.models.fields.TextField', [], {}),
'cert_name_short': ('django.db.models.fields.TextField', [], {}),
'certificates_display_behavior': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'certificates_show_before_end': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'course_image_url': ('django.db.models.fields.TextField', [], {}),
'display_name': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'display_number_with_default': ('django.db.models.fields.TextField', [], {}),
'display_org_with_default': ('django.db.models.fields.TextField', [], {}),
'end': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'end_of_course_survey_url': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'facebook_url': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'has_any_active_web_certificate': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'primary_key': 'True', 'db_index': 'True'}),
'lowest_passing_grade': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'}),
'mobile_available': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'social_sharing_url': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'start': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'visible_to_staff_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
}
}
complete_apps = ['course_overviews']
|
wilkeraziz/grasp
|
refs/heads/master
|
grasp/cfg/info.py
|
1
|
"""
Reports information about grammars.
:Authors: - Wilker Aziz
"""
import argparse
import logging
from grasp.cfg.reader import load_grammar
from tabulate import tabulate
from grasp.formal.hg import cfg_to_hg
from grasp.formal.topsort import LazyTopSortTable
def report(args):
general_header = ['path', 'type', 'terminals', 'nonterminals', 'rules']
general_info = []
# Load main grammars
logging.info('Loading main grammar...')
cfg = load_grammar(args.grammar, args.grammarfmt, args.log)
logging.info('Main grammar: terminals=%d nonterminals=%d productions=%d',
cfg.n_terminals(),
cfg.n_nonterminals(),
len(cfg))
general_info.append([args.grammar, 'main', cfg.n_terminals(), cfg.n_nonterminals(), len(cfg)])
# Load additional grammars
main_grammars = [cfg]
if args.extra_grammar:
for grammar_path in args.extra_grammar:
logging.info('Loading additional grammar: %s', grammar_path)
grammar = load_grammar(grammar_path, args.grammarfmt, args.log)
logging.info('Additional grammar: terminals=%d nonterminals=%d productions=%d',
grammar.n_terminals(),
grammar.n_nonterminals(),
len(grammar))
main_grammars.append(grammar)
general_info.append([grammar_path, 'extra', grammar.n_terminals(), grammar.n_nonterminals(), len(grammar)])
# Load glue grammars
glue_grammars = []
if args.glue_grammar:
for glue_path in args.glue_grammar:
logging.info('Loading glue grammar: %s', glue_path)
glue = load_grammar(glue_path, args.grammarfmt, args.log)
logging.info('Glue grammar: terminals=%d nonterminals=%d productions=%d', glue.n_terminals(),
glue.n_nonterminals(), len(glue))
glue_grammars.append(glue)
general_info.append([glue_path, 'glue', glue.n_terminals(), glue.n_nonterminals(), len(glue)])
print(tabulate(general_info, general_header))
hg = cfg_to_hg(main_grammars, glue_grammars)
tsorter = LazyTopSortTable(hg, acyclic=False)
if args.tsort:
tsort = tsorter.do()
with open('{0}.tsort'.format(args.output), 'w') as fo:
print(tsort.pp(), file=fo)
def argparser():
parser = argparse.ArgumentParser(prog='grasp.cfg.info',
usage='python -m %(prog)s [options]',
description="Output information about a (collection of) grammar(s)",
epilog="")
parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter
parser.add_argument('grammar',
type=str,
help='grammar file (or prefix to grammar files)')
parser.add_argument('output',
type=str,
help='output prefix')
parser.add_argument('--log',
action='store_true',
help='apply the log transform to the grammar (by default we assume this has already been done)')
parser.add_argument('--grammarfmt',
type=str, default='bar', metavar='FMT',
choices=['bar', 'discodop', 'cdec'],
help="grammar format: bar, discodop, cdec")
parser.add_argument('--extra-grammar',
action='append', default=[], metavar='PATH',
help="path to an additional grammar (multiple allowed)")
parser.add_argument('--glue-grammar',
action='append', default=[], metavar='PATH',
help="glue rules are only applied to initial states (multiple allowed)")
parser.add_argument('--tsort',
action='store_true',
help='topsort the grammar and report the partial ordering of its symbols')
parser.add_argument('--verbose', '-v',
action='count', default=0,
help='increase the verbosity level')
return parser
def configure():
"""
Parse command line arguments, configures the main logger.
:returns: command line arguments
"""
args = argparser().parse_args()
if args.verbose == 1:
logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(levelname)s %(message)s')
elif args.verbose > 1:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
return args
def main():
"""
Configures the parser by parsing command line arguments and calling the core code.
It might also profile the run if the user chose to do so.
"""
args = configure()
# Prepare output directories
logging.info('Writing files to: %s.*', args.output)
report(args)
if __name__ == '__main__':
main()
|
perryjrandall/arsenalsuite
|
refs/heads/master
|
python/blur/examples/timesheet_reports.py
|
11
|
#!/usr/bin/python
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from blur.Stone import *
from blur.Classes import *
import sys
import blur.reports
# First Create a Qt Application
app = QApplication(sys.argv)
# Load database config
if sys.platform=='win32':
initConfig("c:\\blur\\resin\\resin.ini")
else:
initConfig("/etc/db.ini")
report_dict = {}
for report in blur.reports.ReportList:
if report:
report_dict[report.Name] = report
def usage():
print 'timesheet_reports.py SQL_WHERE REPORT_NAME OUTPUT_FILE'
print 'REPORT_NAME can be ' + ', '.join(report_dict.keys())
print 'example:'
print """timesheet_reports.py "datetime >= now() - '7 days'::interval" dump test.xls"""
if len(sys.argv) != 4:
usage()
sys.exit(1)
if sys.argv[2].lower() not in report_dict:
print "Invalid REPORT_NAME"
usage()
sys.exit(1)
tsl = TimeSheet.select( sys.argv[1] )
minDate, maxDate = None, None
for ts in tsl:
if not minDate or ts.dateTime() < minDate:
minDate = ts.dateTime()
if not maxDate or ts.dateTime() > maxDate:
maxDate = ts.dateTime()
report_dict[sys.argv[2].lower()].Function( minDate.date(), maxDate.date(), tsl, recipients=[], filename = sys.argv[3] )
|
Matt-Deacalion/django
|
refs/heads/master
|
django/db/migrations/operations/base.py
|
356
|
from __future__ import unicode_literals
from django.db import router
class Operation(object):
"""
Base class for migration operations.
It's responsible for both mutating the in-memory model state
(see db/migrations/state.py) to represent what it performs, as well
as actually performing it against a live database.
Note that some operations won't modify memory state at all (e.g. data
copying operations), and some will need their modifications to be
optionally specified by the user (e.g. custom Python code snippets)
Due to the way this class deals with deconstruction, it should be
considered immutable.
"""
# If this migration can be run in reverse.
# Some operations are impossible to reverse, like deleting data.
reversible = True
# Can this migration be represented as SQL? (things like RunPython cannot)
reduces_to_sql = True
# Should this operation be forced as atomic even on backends with no
# DDL transaction support (i.e., does it have no DDL, like RunPython)
atomic = False
serialization_expand_args = []
def __new__(cls, *args, **kwargs):
# We capture the arguments to make returning them trivial
self = object.__new__(cls)
self._constructor_args = (args, kwargs)
return self
def deconstruct(self):
"""
Returns a 3-tuple of class import path (or just name if it lives
under django.db.migrations), positional arguments, and keyword
arguments.
"""
return (
self.__class__.__name__,
self._constructor_args[0],
self._constructor_args[1],
)
def state_forwards(self, app_label, state):
"""
Takes the state from the previous migration, and mutates it
so that it matches what this migration would perform.
"""
raise NotImplementedError('subclasses of Operation must provide a state_forwards() method')
def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""
Performs the mutation on the database schema in the normal
(forwards) direction.
"""
raise NotImplementedError('subclasses of Operation must provide a database_forwards() method')
def database_backwards(self, app_label, schema_editor, from_state, to_state):
"""
Performs the mutation on the database schema in the reverse
direction - e.g. if this were CreateModel, it would in fact
drop the model's table.
"""
raise NotImplementedError('subclasses of Operation must provide a database_backwards() method')
def describe(self):
"""
Outputs a brief summary of what the action does.
"""
return "%s: %s" % (self.__class__.__name__, self._constructor_args)
def references_model(self, name, app_label=None):
"""
Returns True if there is a chance this operation references the given
model name (as a string), with an optional app label for accuracy.
Used for optimization. If in doubt, return True;
returning a false positive will merely make the optimizer a little
less efficient, while returning a false negative may result in an
unusable optimized migration.
"""
return True
def references_field(self, model_name, name, app_label=None):
"""
Returns True if there is a chance this operation references the given
field name, with an optional app label for accuracy.
Used for optimization. If in doubt, return True.
"""
return self.references_model(model_name, app_label)
def allow_migrate_model(self, connection_alias, model):
"""
Returns if we're allowed to migrate the model.
This is a thin wrapper around router.allow_migrate_model() that
preemptively rejects any proxy, swapped out, or unmanaged model.
"""
if not model._meta.can_migrate(connection_alias):
return False
return router.allow_migrate_model(connection_alias, model)
def __repr__(self):
return "<%s %s%s>" % (
self.__class__.__name__,
", ".join(map(repr, self._constructor_args[0])),
",".join(" %s=%r" % x for x in self._constructor_args[1].items()),
)
|
bis12/spdyathome
|
refs/heads/master
|
spdyathome/servers.py
|
2
|
"""
Start the basic thor servers for each case of connection.
Use the standard request responders in BaseServer.
"""
import urilib
import os
import sys
import argparse
from . import conf
from . import util
from thor.loop import run
from thor import HttpServer
from thor import SpdyServer
from serverbase import BaseServer
from multiprocessing import Process
from thor.events import on
def get_args():
parser = argparse.ArgumentParser(
description='Run SPDY and HTTP servers to act as endpoint of test.',
epilog='This can be run directly or using `scripts/run-servers`.')
return parser.parse_args()
def http_main(conf):
print 'Loading configuration into http base server!'
base = BaseServer(conf)
print 'creating HTTP server on port %d' % (conf.http_port,)
def http_handler(x):
@on(x, 'request_start')
def go(*args):
print 'HTTP: start %s' % (str(args[1]),)
base.paths.get(util.make_ident(x.method, x.uri), base.fourohfour)(x)
@on(x, 'request_body')
def body(chunk):
#print 'body: %s' % chunk
pass
@on(x, 'request_done')
def done(trailers):
#print 'done: %s' % str(trailers)
pass
http_serve = HttpServer(host='', port=conf.http_port)
http_serve.on('exchange', http_handler)
def spdy_main(conf):
print 'Loading configuration into spdy base server!'
base = BaseServer(conf)
print 'creating SPDY server on port %d' % (conf.spdy_port,)
def spdy_handler(x):
@on(x, 'request_start')
def go(*args):
path = urilib.URI(x.uri).path # Take into account SPDY's uri
print 'SPDY: start %s' % (path,)
base.paths.get(util.make_ident(x.method, path), base.fourohfour)(x)
@on(x, 'request_body')
def body(chunk):
#print 'body: %s' % chunk
pass
@on(x, 'request_done')
def done(trailers):
#print 'done: %s' % str(trailers)
pass
spdy_serve = SpdyServer('', conf.spdy_port)
spdy_serve.on('exchange', spdy_handler)
def capture_main(conf):
print 'creating capture server on port %d' % (conf.capture_port,)
def capture_handler(x):
up = {'inp': '', 'final': {}}
@on(x, 'request_start')
def go(*args):
print 'capture: start %s' % (str(args[1]),)
@on(x, 'request_body')
def body(chunk):
up['inp'] += chunk
@on(x, 'request_done')
def done(trailers):
with open(os.path.join(conf.outdir, conf.outfile), 'a') as f:
f.write(up['inp'])
f.write('\n')
f.close()
print 'finished capture'
x.response_start(200, 'OK', [])
x.response_done([])
capture_serve = HttpServer(host='', port=conf.capture_port)
capture_serve.on('exchange', capture_handler)
if __name__ == '__main__':
args = get_args()
sys.setrecursionlimit(2000) # I'm so sorry...
try:
os.mkdir(conf.outdir)
except OSError:
pass
capture_main(conf)
spdy_main(conf)
http_main(conf)
run()
|
OpenSlides/OpenSlides
|
refs/heads/master
|
server/openslides/assignments/migrations/0021_assignmentvote_user_token_3.py
|
5
|
# Generated by jsangmeister on 2021-03-25 10:41
from django.db import migrations, models
import openslides.poll.models
class Migration(migrations.Migration):
dependencies = [
("assignments", "0020_assignmentvote_user_token_2"),
]
operations = [
migrations.AlterField(
model_name="assignmentvote",
name="user_token",
field=models.CharField(
null=False,
default=openslides.poll.models.generate_user_token,
max_length=16,
),
),
]
|
classrank/ClassRank
|
refs/heads/master
|
classrank/handlers/suggestion.py
|
1
|
from tornado.web import authenticated
from classrank.database.wrapper import Query
from . import BaseHandler
from classrank.filters.collabfilter import CollaborativeFilter
class SuggestionHandler(BaseHandler):
@authenticated
def get(self):
page_data = {"error": False, "data":{}}
user = self.decoded_username()
data = dict()
try:
filters = self.add_filters()
with Query(self.db) as q:
student = q.query(self.db.account).filter_by(username=user).one().student
courses = set(c[0] for c in q.query(self.db.course.name).all()) - set([c.name for c in student.courses])
student_id = student.uid
ratings = filters['rating'].getRecommendation({student_id: courses})[student_id]
page_data['data']['rating'] = sorted([(k, v) for k, v in ratings.items()], key=lambda x: x[1] or 0)[::-1]
self.render('suggestion.html', **page_data)
except Exception as e:
print(e)
page_data['error'] = True
self.render("suggestion.html", **page_data)
def add_filters(self):
# attrs = set(x for x in dir(self.db.rating) if not x.startswith("_"))
# attrs -= set(["metadata", "section_id", "student", "section", "student_id"])
# return {attr: CollaborativeFilter(db=self.db, metric=attr) for attr in attrs}
with Query(self.db)as q:
num = max(1, int(q.query(self.db.student).count() / 5))
return {'rating': CollaborativeFilter(db=self.db, metric='rating', numRecommendations=num)}
|
dakcarto/suite-qgis-plugin
|
refs/heads/name_fixes
|
src/opengeo/gui/dialogs/styledialog.py
|
1
|
from PyQt4 import QtGui, QtCore
from opengeo.qgis import layers
class StyleFromLayerDialog(QtGui.QDialog):
def __init__(self, parent = None):
super(StyleFromLayerDialog, self).__init__(parent)
self.layer = None
self.name = None
self.initGui()
def initGui(self):
verticalLayout = QtGui.QVBoxLayout()
buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Close)
self.setWindowTitle('Create style from layer')
horizontalLayout = QtGui.QHBoxLayout()
horizontalLayout.setSpacing(30)
horizontalLayout.setMargin(0)
layerLabel = QtGui.QLabel('Layer')
layerLabel.setMinimumWidth(150)
self.layerBox = QtGui.QComboBox()
self.alllayers = [layer.name() for layer in layers.getAllLayers()]
self.layerBox.addItems(self.alllayers)
self.layerBox.setMinimumWidth(250)
horizontalLayout.addWidget(layerLabel)
horizontalLayout.addWidget(self.layerBox)
verticalLayout.addLayout(horizontalLayout)
horizontalLayout = QtGui.QHBoxLayout()
horizontalLayout.setSpacing(30)
horizontalLayout.setMargin(0)
nameLabel = QtGui.QLabel('Name')
nameLabel.setMinimumWidth(150)
self.nameBox = QtGui.QLineEdit()
self.nameBox.setText('')
self.nameBox.setPlaceholderText("[Use layer name]")
self.nameBox.setMinimumWidth(250)
horizontalLayout.addWidget(nameLabel)
horizontalLayout.addWidget(self.nameBox)
verticalLayout.addLayout(horizontalLayout)
self.groupBox = QtGui.QGroupBox()
self.groupBox.setTitle("")
self.groupBox.setLayout(verticalLayout)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.groupBox)
layout.addWidget(buttonBox)
self.setLayout(layout)
buttonBox.accepted.connect(self.okPressed)
buttonBox.rejected.connect(self.cancelPressed)
self.resize(400,150)
def okPressed(self):
self.layer = self.layerBox.currentText()
self.name = unicode(self.nameBox.text())
self.name = self.name if not self.name.strip() == "" else self.layer
self.close()
def cancelPressed(self):
self.layer = None
self.name = None
self.close()
class AddStyleToLayerDialog(QtGui.QDialog):
def __init__(self, catalog, parent = None):
super(AddStyleToLayerDialog, self).__init__(parent)
self.catalog = catalog
self.style = None
self.default = None
self.initGui()
def initGui(self):
layout = QtGui.QVBoxLayout()
buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Close)
self.setWindowTitle('Add style to layer')
horizontalLayout = QtGui.QHBoxLayout()
horizontalLayout.setSpacing(30)
horizontalLayout.setMargin(0)
styleLabel = QtGui.QLabel('Style')
self.styleBox = QtGui.QComboBox()
styles = [style.name for style in self.catalog.get_styles()]
self.styleBox.addItems(styles)
horizontalLayout.addWidget(styleLabel)
horizontalLayout.addWidget(self.styleBox)
layout.addLayout(horizontalLayout)
horizontalLayout = QtGui.QHBoxLayout()
horizontalLayout.setSpacing(30)
horizontalLayout.setMargin(0)
self.checkBox = QtGui.QCheckBox("Add as default style")
horizontalLayout.addWidget(self.checkBox)
layout.addLayout(horizontalLayout)
layout.addWidget(buttonBox)
self.setLayout(layout)
buttonBox.accepted.connect(self.okPressed)
buttonBox.rejected.connect(self.cancelPressed)
self.resize(400,200)
def okPressed(self):
self.style = self.catalog.get_style(self.styleBox.currentText())
self.default = self.checkBox.isChecked()
self.close()
def cancelPressed(self):
self.style = None
self.default = None
self.close()
class PublishStyleDialog(QtGui.QDialog):
def __init__(self, catalogs, parent = None):
super(PublishStyleDialog, self).__init__(parent)
self.catalogs = catalogs
self.catalog = None
self.name = None
self.initGui()
def initGui(self):
verticalLayout = QtGui.QVBoxLayout()
buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Close)
self.setWindowTitle('Publish style')
horizontalLayout = QtGui.QHBoxLayout()
horizontalLayout.setSpacing(30)
horizontalLayout.setMargin(0)
catalogLabel = QtGui.QLabel('Catalog')
self.catalogBox = QtGui.QComboBox()
self.catalogBox.addItems(self.catalogs)
horizontalLayout.addWidget(catalogLabel)
horizontalLayout.addWidget(self.catalogBox)
verticalLayout.addLayout(horizontalLayout)
horizontalLayout = QtGui.QHBoxLayout()
horizontalLayout.setSpacing(30)
horizontalLayout.setMargin(0)
nameLabel = QtGui.QLabel('Name')
self.nameBox = QtGui.QLineEdit()
self.nameBox.setText('')
self.nameBox.setPlaceholderText("[Use layer name]")
horizontalLayout.addWidget(nameLabel)
horizontalLayout.addWidget(self.nameBox)
verticalLayout.addLayout(horizontalLayout)
self.groupBox = QtGui.QGroupBox()
self.groupBox.setTitle("")
self.groupBox.setLayout(verticalLayout)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.groupBox)
layout.addWidget(buttonBox)
self.setLayout(layout)
buttonBox.accepted.connect(self.okPressed)
buttonBox.rejected.connect(self.cancelPressed)
self.resize(400,200)
def okPressed(self):
self.name = unicode(self.nameBox.text())
self.name = self.name if not self.name.strip() == "" else None
self.catalog = self.catalogs[self.catalogBox.currentIndex()]
self.close()
def cancelPressed(self):
self.catalog = None
self.name = None
self.close()
|
pipermerriam/django
|
refs/heads/master
|
tests/schema/fields.py
|
203
|
from django.db import models
from django.db.models.fields.related import (
RECURSIVE_RELATIONSHIP_CONSTANT, ManyRelatedObjectsDescriptor,
ManyToManyField, ManyToManyRel, RelatedField,
create_many_to_many_intermediary_model,
)
from django.utils.functional import curry
class CustomManyToManyField(RelatedField):
"""
Ticket #24104 - Need to have a custom ManyToManyField,
which is not an inheritor of ManyToManyField.
"""
many_to_many = True
def __init__(self, to, db_constraint=True, swappable=True, **kwargs):
try:
to._meta
except AttributeError:
to = str(to)
kwargs['rel'] = ManyToManyRel(
self, to,
related_name=kwargs.pop('related_name', None),
related_query_name=kwargs.pop('related_query_name', None),
limit_choices_to=kwargs.pop('limit_choices_to', None),
symmetrical=kwargs.pop('symmetrical', to == RECURSIVE_RELATIONSHIP_CONSTANT),
through=kwargs.pop('through', None),
through_fields=kwargs.pop('through_fields', None),
db_constraint=db_constraint,
)
self.swappable = swappable
self.db_table = kwargs.pop('db_table', None)
if kwargs['rel'].through is not None:
assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used."
super(CustomManyToManyField, self).__init__(**kwargs)
def contribute_to_class(self, cls, name, **kwargs):
if self.remote_field.symmetrical and (
self.remote_field.model == "self" or self.remote_field.model == cls._meta.object_name):
self.remote_field.related_name = "%s_rel_+" % name
super(CustomManyToManyField, self).contribute_to_class(cls, name, **kwargs)
if not self.remote_field.through and not cls._meta.abstract and not cls._meta.swapped:
self.remote_field.through = create_many_to_many_intermediary_model(self, cls)
setattr(cls, self.name, ManyRelatedObjectsDescriptor(self.remote_field))
self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta)
def get_internal_type(self):
return 'ManyToManyField'
# Copy those methods from ManyToManyField because they don't call super() internally
contribute_to_related_class = ManyToManyField.__dict__['contribute_to_related_class']
_get_m2m_attr = ManyToManyField.__dict__['_get_m2m_attr']
_get_m2m_reverse_attr = ManyToManyField.__dict__['_get_m2m_reverse_attr']
_get_m2m_db_table = ManyToManyField.__dict__['_get_m2m_db_table']
class InheritedManyToManyField(ManyToManyField):
pass
class MediumBlobField(models.BinaryField):
"""
A MySQL BinaryField that uses a different blob size.
"""
def db_type(self, connection):
return 'MEDIUMBLOB'
|
willwray/dash
|
refs/heads/v0.12.2.x
|
contrib/seeds/makeseeds.py
|
34
|
#!/usr/bin/env python
#
# Generate seeds.txt from Pieter's DNS seeder
#
NSEEDS=512
MAX_SEEDS_PER_ASN=2
MIN_BLOCKS = 400000
# These are hosts that have been observed to be behaving strangely (e.g.
# aggressively connecting to every node).
SUSPICIOUS_HOSTS = set([
"130.211.129.106", "178.63.107.226",
"83.81.130.26", "88.198.17.7", "148.251.238.178", "176.9.46.6",
"54.173.72.127", "54.174.10.182", "54.183.64.54", "54.194.231.211",
"54.66.214.167", "54.66.220.137", "54.67.33.14", "54.77.251.214",
"54.94.195.96", "54.94.200.247"
])
import re
import sys
import dns.resolver
import collections
PATTERN_IPV4 = re.compile(r"^((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})):(\d+)$")
PATTERN_IPV6 = re.compile(r"^\[([0-9a-z:]+)\]:(\d+)$")
PATTERN_ONION = re.compile(r"^([abcdefghijklmnopqrstuvwxyz234567]{16}\.onion):(\d+)$")
PATTERN_AGENT = re.compile(r"^(\/Satoshi:0\.8\.6\/|\/Satoshi:0\.9\.(2|3|4|5)\/|\/Core:0.1(0|1|2).\d{1,2}.\d{1,2}\/)$")
def parseline(line):
sline = line.split()
if len(sline) < 11:
return None
m = PATTERN_IPV4.match(sline[0])
sortkey = None
ip = None
if m is None:
m = PATTERN_IPV6.match(sline[0])
if m is None:
m = PATTERN_ONION.match(sline[0])
if m is None:
return None
else:
net = 'onion'
ipstr = sortkey = m.group(1)
port = int(m.group(2))
else:
net = 'ipv6'
if m.group(1) in ['::']: # Not interested in localhost
return None
ipstr = m.group(1)
sortkey = ipstr # XXX parse IPv6 into number, could use name_to_ipv6 from generate-seeds
port = int(m.group(2))
else:
# Do IPv4 sanity check
ip = 0
for i in range(0,4):
if int(m.group(i+2)) < 0 or int(m.group(i+2)) > 255:
return None
ip = ip + (int(m.group(i+2)) << (8*(3-i)))
if ip == 0:
return None
net = 'ipv4'
sortkey = ip
ipstr = m.group(1)
port = int(m.group(6))
# Skip bad results.
if sline[1] == 0:
return None
# Extract uptime %.
uptime30 = float(sline[7][:-1])
# Extract Unix timestamp of last success.
lastsuccess = int(sline[2])
# Extract protocol version.
version = int(sline[10])
# Extract user agent.
agent = sline[11][1:-1]
# Extract service flags.
service = int(sline[9], 16)
# Extract blocks.
blocks = int(sline[8])
# Construct result.
return {
'net': net,
'ip': ipstr,
'port': port,
'ipnum': ip,
'uptime': uptime30,
'lastsuccess': lastsuccess,
'version': version,
'agent': agent,
'service': service,
'blocks': blocks,
'sortkey': sortkey,
}
def filtermultiport(ips):
'''Filter out hosts with more nodes per IP'''
hist = collections.defaultdict(list)
for ip in ips:
hist[ip['sortkey']].append(ip)
return [value[0] for (key,value) in hist.items() if len(value)==1]
# Based on Greg Maxwell's seed_filter.py
def filterbyasn(ips, max_per_asn, max_total):
# Sift out ips by type
ips_ipv4 = [ip for ip in ips if ip['net'] == 'ipv4']
ips_ipv6 = [ip for ip in ips if ip['net'] == 'ipv6']
ips_onion = [ip for ip in ips if ip['net'] == 'onion']
# Filter IPv4 by ASN
result = []
asn_count = {}
for ip in ips_ipv4:
if len(result) == max_total:
break
try:
asn = int([x.to_text() for x in dns.resolver.query('.'.join(reversed(ip['ip'].split('.'))) + '.origin.asn.cymru.com', 'TXT').response.answer][0].split('\"')[1].split(' ')[0])
if asn not in asn_count:
asn_count[asn] = 0
if asn_count[asn] == max_per_asn:
continue
asn_count[asn] += 1
result.append(ip)
except:
sys.stderr.write('ERR: Could not resolve ASN for "' + ip['ip'] + '"\n')
# TODO: filter IPv6 by ASN
# Add back non-IPv4
result.extend(ips_ipv6)
result.extend(ips_onion)
return result
def main():
lines = sys.stdin.readlines()
ips = [parseline(line) for line in lines]
# Skip entries with valid address.
ips = [ip for ip in ips if ip is not None]
# Skip entries from suspicious hosts.
ips = [ip for ip in ips if ip['ip'] not in SUSPICIOUS_HOSTS]
# Enforce minimal number of blocks.
ips = [ip for ip in ips if ip['blocks'] >= MIN_BLOCKS]
# Require service bit 1.
ips = [ip for ip in ips if (ip['service'] & 1) == 1]
# Require at least 50% 30-day uptime.
ips = [ip for ip in ips if ip['uptime'] > 50]
# Require a known and recent user agent.
ips = [ip for ip in ips if PATTERN_AGENT.match(ip['agent'])]
# Sort by availability (and use last success as tie breaker)
ips.sort(key=lambda x: (x['uptime'], x['lastsuccess'], x['ip']), reverse=True)
# Filter out hosts with multiple ports, these are likely abusive
ips = filtermultiport(ips)
# Look up ASNs and limit results, both per ASN and globally.
ips = filterbyasn(ips, MAX_SEEDS_PER_ASN, NSEEDS)
# Sort the results by IP address (for deterministic output).
ips.sort(key=lambda x: (x['net'], x['sortkey']))
for ip in ips:
if ip['net'] == 'ipv6':
print '[%s]:%i' % (ip['ip'], ip['port'])
else:
print '%s:%i' % (ip['ip'], ip['port'])
if __name__ == '__main__':
main()
|
nagyistoce/edx-platform
|
refs/heads/master
|
common/djangoapps/auth_exchange/tests/test_forms.py
|
113
|
# pylint: disable=no-member
"""
Tests for OAuth token exchange forms
"""
import unittest
from django.conf import settings
from django.contrib.sessions.middleware import SessionMiddleware
from django.test import TestCase
from django.test.client import RequestFactory
import httpretty
from provider import scope
import social.apps.django_app.utils as social_utils
from auth_exchange.forms import AccessTokenExchangeForm
from auth_exchange.tests.utils import AccessTokenExchangeTestMixin
from third_party_auth.tests.utils import ThirdPartyOAuthTestMixinFacebook, ThirdPartyOAuthTestMixinGoogle
class AccessTokenExchangeFormTest(AccessTokenExchangeTestMixin):
"""
Mixin that defines test cases for AccessTokenExchangeForm
"""
def setUp(self):
super(AccessTokenExchangeFormTest, self).setUp()
self.request = RequestFactory().post("dummy_url")
redirect_uri = 'dummy_redirect_url'
SessionMiddleware().process_request(self.request)
self.request.social_strategy = social_utils.load_strategy(self.request)
# pylint: disable=no-member
self.request.backend = social_utils.load_backend(self.request.social_strategy, self.BACKEND, redirect_uri)
def _assert_error(self, data, expected_error, expected_error_description):
form = AccessTokenExchangeForm(request=self.request, data=data)
self.assertEqual(
form.errors,
{"error": expected_error, "error_description": expected_error_description}
)
self.assertNotIn("partial_pipeline", self.request.session)
def _assert_success(self, data, expected_scopes):
form = AccessTokenExchangeForm(request=self.request, data=data)
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["user"], self.user)
self.assertEqual(form.cleaned_data["client"], self.oauth_client)
self.assertEqual(scope.to_names(form.cleaned_data["scope"]), expected_scopes)
# This is necessary because cms does not implement third party auth
@unittest.skipUnless(settings.FEATURES.get("ENABLE_THIRD_PARTY_AUTH"), "third party auth not enabled")
@httpretty.activate
class AccessTokenExchangeFormTestFacebook(
AccessTokenExchangeFormTest,
ThirdPartyOAuthTestMixinFacebook,
TestCase
):
"""
Tests for AccessTokenExchangeForm used with Facebook
"""
pass
# This is necessary because cms does not implement third party auth
@unittest.skipUnless(settings.FEATURES.get("ENABLE_THIRD_PARTY_AUTH"), "third party auth not enabled")
@httpretty.activate
class AccessTokenExchangeFormTestGoogle(
AccessTokenExchangeFormTest,
ThirdPartyOAuthTestMixinGoogle,
TestCase
):
"""
Tests for AccessTokenExchangeForm used with Google
"""
pass
|
vladryk/horizon
|
refs/heads/master
|
openstack_dashboard/dashboards/admin/volumes/volume_types/extras/urls.py
|
66
|
# 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 django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.dashboards.admin.volumes.volume_types.extras \
import views
urlpatterns = patterns(
'',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^create/$', views.CreateView.as_view(), name='create'),
url(r'^(?P<key>[^/]+)/edit/$', views.EditView.as_view(), name='edit')
)
|
hughperkins/pycltorch
|
refs/heads/master
|
test_cltorch.py
|
1
|
from __future__ import print_function
import PyClTorch
from PyTorchAug import nn
# PyClTorch.newfunction(123)
import PyTorch
from PyTorchAug import *
def myeval(expr):
print(expr, ':', eval(expr))
if __name__ == '__main__':
# a = PyTorch.foo(3,2)
# print('a', a)
# print(PyTorch.FloatTensor(3,2))
a = PyTorch.FloatTensor(4, 3).uniform()
print('a', a)
a = a.cl()
print(type(a))
print('a.dims()', a.dims())
print('a.size()', a.size())
print('a', a)
print('sum:', a.sum())
myeval('a + 1')
b = PyClTorch.ClTensor()
print('got b')
myeval('b')
b.resizeAs(a)
myeval('b')
print('run uniform')
b.uniform()
myeval('b')
print('create new b')
b = PyClTorch.ClTensor()
print('b.dims()', b.dims())
print('b.size()', b.size())
print('b', b)
c = PyTorch.FloatTensor().cl()
print('c.dims()', c.dims())
print('c.size()', c.size())
print('c', c)
print('creating Linear...')
linear = nn.Linear(3, 5)
print('created linear')
print('linear:', linear)
myeval('linear.output')
myeval('linear.output.dims()')
myeval('linear.output.size()')
myeval('linear.output.nElement()')
linear = linear.cl()
myeval('type(linear)')
myeval('type(linear.output)')
myeval('linear.output.dims()')
myeval('linear.output.size()')
myeval('linear.output')
# print('linearCl.output', linear.output)
output = linear.forward(a)
print('output.dims()', output.dims())
print('output.size()', output.size())
outputFloat = output.float()
print('outputFloat', outputFloat)
print('output', output)
mlp = nn.Sequential()
mlp.add(nn.SpatialConvolutionMM(1, 16, 5, 5, 1, 1, 2, 2))
mlp.add(nn.ReLU())
mlp.add(nn.SpatialMaxPooling(3, 3, 3, 3))
mlp.add(nn.SpatialConvolutionMM(16, 32, 5, 5, 1, 1, 2, 2))
mlp.add(nn.ReLU())
mlp.add(nn.SpatialMaxPooling(2, 2, 2, 2))
mlp.add(nn.Reshape(32 * 4 * 4))
mlp.add(nn.Linear(32 * 4 * 4, 150))
mlp.add(nn.Tanh())
mlp.add(nn.Linear(150, 10))
mlp.add(nn.LogSoftMax())
mlp.cl()
print('mlp', mlp)
myeval('mlp.output')
input = PyTorch.FloatTensor(128, 1, 28, 28).uniform().cl()
myeval('input[0]')
output = mlp.forward(input)
myeval('output[0]')
|
jleclanche/django-push-notifications
|
refs/heads/master
|
push_notifications/gcm.py
|
3
|
"""
Firebase Cloud Messaging
Previously known as GCM / C2DM
Documentation is available on the Firebase Developer website:
https://firebase.google.com/docs/cloud-messaging/
"""
import json
from django.core.exceptions import ImproperlyConfigured
from .compat import Request, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .models import GCMDevice
# Valid keys for FCM messages. Reference:
# https://firebase.google.com/docs/cloud-messaging/http-server-ref
FCM_TARGETS_KEYS = [
"to", "condition", "notification_key"
]
FCM_OPTIONS_KEYS = [
"collapse_key", "priority", "content_available", "delay_while_idle", "time_to_live",
"restricted_package_name", "dry_run", "mutable_content"
]
FCM_NOTIFICATIONS_PAYLOAD_KEYS = [
"title", "body", "icon", "sound", "badge", "color", "tag", "click_action",
"body_loc_key", "body_loc_args", "title_loc_key", "title_loc_args", "android_channel_id"
]
class GCMError(NotificationError):
pass
def _chunks(l, n):
"""
Yield successive chunks from list \a l with a minimum size \a n
"""
for i in range(0, len(l), n):
yield l[i:i + n]
def _gcm_send(data, content_type, application_id):
key = get_manager().get_gcm_api_key(application_id)
headers = {
"Content-Type": content_type,
"Authorization": "key=%s" % (key),
"Content-Length": str(len(data)),
}
request = Request(get_manager().get_post_url("GCM", application_id), data, headers)
return urlopen(
request, timeout=get_manager().get_error_timeout("GCM", application_id)
).read().decode("utf-8")
def _fcm_send(data, content_type, application_id):
key = get_manager().get_fcm_api_key(application_id)
headers = {
"Content-Type": content_type,
"Authorization": "key=%s" % (key),
"Content-Length": str(len(data)),
}
request = Request(get_manager().get_post_url("FCM", application_id), data, headers)
return urlopen(
request, timeout=get_manager().get_error_timeout("FCM", application_id)
).read().decode("utf-8")
def _cm_handle_response(registration_ids, response_data, cloud_type, application_id=None):
response = response_data
if response.get("failure") or response.get("canonical_ids"):
ids_to_remove, old_new_ids = [], []
throw_error = False
for index, result in enumerate(response["results"]):
error = result.get("error")
if error:
# https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes
# If error is NotRegistered or InvalidRegistration, then we will deactivate devices
# because this registration ID is no more valid and can't be used to send messages,
# otherwise raise error
if error in ("NotRegistered", "InvalidRegistration"):
ids_to_remove.append(registration_ids[index])
else:
throw_error = True
result["original_registration_id"] = registration_ids[index]
# If registration_id is set, replace the original ID with the new value (canonical ID)
# in your server database. Note that the original ID is not part of the result, you need
# to obtain it from the list of registration_ids in the request (using the same index).
new_id = result.get("registration_id")
if new_id:
old_new_ids.append((registration_ids[index], new_id))
if ids_to_remove:
removed = GCMDevice.objects.filter(
registration_id__in=ids_to_remove, cloud_message_type=cloud_type
)
removed.update(active=False)
for old_id, new_id in old_new_ids:
_cm_handle_canonical_id(new_id, old_id, cloud_type)
if throw_error:
raise GCMError(response)
return response
def _cm_send_request(
registration_ids, data, cloud_type="GCM", application_id=None,
use_fcm_notifications=True, **kwargs
):
"""
Sends a FCM or GCM notification to one or more registration_ids as json data.
The registration_ids needs to be a list.
"""
payload = {"registration_ids": registration_ids} if registration_ids else {}
data = data.copy()
# If using FCM, optionally autodiscovers notification related keys
# https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
if cloud_type == "FCM" and use_fcm_notifications:
notification_payload = {}
if "message" in data:
notification_payload["body"] = data.pop("message", None)
for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS:
value_from_extra = data.pop(key, None)
if value_from_extra:
notification_payload[key] = value_from_extra
value_from_kwargs = kwargs.pop(key, None)
if value_from_kwargs:
notification_payload[key] = value_from_kwargs
if notification_payload:
payload["notification"] = notification_payload
if data:
payload["data"] = data
# Attach any additional non falsy keyword args (targets, options)
# See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
payload.update({
k: v for k, v in kwargs.items() if v and (k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS)
})
# Sort the keys for deterministic output (useful for tests)
json_payload = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
# Sends requests and handles the response
if cloud_type == "GCM":
response = json.loads(_gcm_send(
json_payload, "application/json", application_id=application_id
))
elif cloud_type == "FCM":
response = json.loads(_fcm_send(
json_payload, "application/json", application_id=application_id
))
else:
raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
return _cm_handle_response(registration_ids, response, cloud_type, application_id)
def _cm_handle_canonical_id(canonical_id, current_id, cloud_type):
"""
Handle situation when FCM server response contains canonical ID
"""
devices = GCMDevice.objects.filter(cloud_message_type=cloud_type)
if devices.filter(registration_id=canonical_id, active=True).exists():
devices.filter(registration_id=current_id).update(active=False)
else:
devices.filter(registration_id=current_id).update(registration_id=canonical_id)
def send_message(registration_ids, data, cloud_type, application_id=None, **kwargs):
"""
Sends a FCM (or GCM) notification to one or more registration_ids. The registration_ids
can be a list or a single string. This will send the notification as json data.
A reference of extra keyword arguments sent to the server is available here:
https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
"""
if cloud_type in ("FCM", "GCM"):
max_recipients = get_manager().get_max_recipients(cloud_type, application_id)
else:
raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
# Checks for valid recipient
if registration_ids is None and "/topics/" not in kwargs.get("to", ""):
return
# Bundles the registration_ids in an list if only one is sent
if not isinstance(registration_ids, list):
registration_ids = [registration_ids] if registration_ids else None
# FCM only allows up to 1000 reg ids per bulk message
# https://firebase.google.com/docs/cloud-messaging/server#http-request
if registration_ids:
ret = []
for chunk in _chunks(registration_ids, max_recipients):
ret.append(_cm_send_request(
chunk, data, cloud_type=cloud_type, application_id=application_id, **kwargs
))
return ret[0] if len(ret) == 1 else ret
else:
return _cm_send_request(None, data, cloud_type=cloud_type, **kwargs)
send_bulk_message = send_message
|
jia-kai/pynojo
|
refs/heads/master
|
experiments/serialize-set.py
|
3
|
# -*- coding: utf-8 -*-
# $File: serialize-set.py
# $Date: Sun Mar 04 18:48:58 2012 +0800
# $Author: jiakai <jia.kai66@gmail.com>
from clock import clock
import pickle, cPickle, json, cjson, marshal
data = set(range(10))
def test(lib, enc, dec, niter = 100000):
with clock(lib + ' encode:'):
for i in range(niter):
s = enc(data)
print lib, 'encode len:', len(s)
with clock(lib + ' decode:'):
for i in range(niter):
d = dec(s)
assert d == data
def myload(s):
return set([int(i) for i in s.split('|')])
def mydump(s):
return '|'.join([str(i) for i in s])
test('my', mydump, myload)
test('json', lambda s: json.dumps(list(s)), lambda s: set(json.loads(s)))
test('cjson', lambda s: cjson.encode(list(s)), lambda s: set(cjson.decode(s)))
test('pickle',
lambda s: pickle.dumps(s, pickle.HIGHEST_PROTOCOL),
lambda s: pickle.loads(s))
test('cPickle',
lambda s: cPickle.dumps(s, cPickle.HIGHEST_PROTOCOL),
lambda s: cPickle.loads(s))
test('marshal', marshal.dumps, marshal.loads)
|
stephane-martin/salt-debian-packaging
|
refs/heads/master
|
salt-2016.3.2/tests/unit/modules/glusterfs_test.py
|
2
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
:codeauthor: :email:`Joe Julian <me@joejulian.name>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import (
MagicMock,
patch,
NO_MOCK,
NO_MOCK_REASON
)
# Import Salt Libs
from salt.modules import glusterfs
import salt.utils.cloud as suc
from salt.exceptions import CommandExecutionError, SaltInvocationError
# Globals
glusterfs.__salt__ = {}
class GlusterResults(object):
''' This class holds the xml results from gluster cli transactions '''
class v34(object):
''' This is for version 3.4 results '''
class list_peers(object):
''' results from "peer status" '''
pass
class peer_probe(object):
fail_cant_connect = fail_bad_hostname = '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
'<cliOutput>',
' <opRet>-1</opRet>',
' <opErrno>107</opErrno>',
' <opErrstr>Probe returned with unknown errno 107</opErrstr>',
'</cliOutput>',
''])
success_self = '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>1</opErrno>',
' <opErrstr>(null)</opErrstr>',
' <output>success: on localhost not needed</output>',
'</cliOutput>',
''])
success_other = '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>0</opErrno>',
' <opErrstr>(null)</opErrstr>',
' <output>success</output>',
'</cliOutput>',
''])
success_hostname_after_ip = success_other
success_ip_after_hostname = success_other
success_already_peer = {
'ip': '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>2</opErrno>',
' <opErrstr>(null)</opErrstr>',
' <output>success: host 10.0.0.2 port 24007 already in peer list</output>',
'</cliOutput>',
'']),
'hostname': '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>2</opErrno>',
' <opErrstr>(null)</opErrstr>',
' <output>success: host server2 port 24007 already in peer list</output>',
'</cliOutput>',
''])}
success_reverse_already_peer = {
'ip': '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>2</opErrno>',
' <opErrstr>(null)</opErrstr>',
' <output>success: host 10.0.0.1 port 24007 already in peer list</output>',
'</cliOutput>',
'']),
'hostname': '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>2</opErrno>',
' <opErrstr>(null)</opErrstr>',
' <output>success: host server1 port 24007 already in peer list</output>',
'</cliOutput>',
''])}
success_first_hostname_from_second_first_time = success_other
success_first_hostname_from_second_second_time = success_reverse_already_peer[
'hostname']
success_first_ip_from_second_first_time = success_reverse_already_peer[
'ip']
class v37(object):
class peer_probe(object):
fail_cant_connect = fail_bad_hostname = '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
'<cliOutput>',
' <opRet>-1</opRet>',
' <opErrno>107</opErrno>',
' <opErrstr>Probe returned with Transport endpoint is not connected</opErrstr>',
'</cliOutput>',
''])
success_self = '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>1</opErrno>',
' <opErrstr/>',
' <output>Probe on localhost not needed</output>',
'</cliOutput>',
''])
success_other = '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>0</opErrno>',
' <opErrstr/>',
' <output/>',
'</cliOutput>',
''])
success_hostname_after_ip = success_other
success_ip_after_hostname = success_other
success_already_peer = {
'ip': '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>2</opErrno>',
' <opErrstr/>',
' <output>Host 10.0.0.2 port 24007 already in peer list</output>',
'</cliOutput>',
'']),
'hostname': '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>2</opErrno>',
' <opErrstr/>',
' <output>Host server2 port 24007 already in peer list</output>',
'</cliOutput>',
''])}
success_reverse_already_peer = {
'ip': '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>2</opErrno>',
' <opErrstr/>',
' <output>Host 10.0.0.1 port 24007 already in peer list</output>',
'</cliOutput>',
'']),
'hostname': '\n'.join([
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
' <cliOutput>',
' <opRet>0</opRet>',
' <opErrno>2</opErrno>',
' <opErrstr/>',
' <output>Host server1 port 24007 already in peer list</output>',
'</cliOutput>',
''])}
success_first_hostname_from_second_first_time = success_reverse_already_peer[
'hostname']
success_first_ip_from_second_first_time = success_other
success_first_ip_from_second_second_time = success_reverse_already_peer[
'ip']
xml_peer_present = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cliOutput>
<opRet>0</opRet>
<peer>
<hostname>node02</hostname>
<hostnames>
<hostname>node02.domain.dom</hostname>
<hostname>10.0.0.2</hostname>
</hostnames>
</peer>
</cliOutput>
"""
xml_volume_present = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cliOutput>
<opRet>0</opRet>
<volList>
<volume>Newvolume1</volume>
<volume>Newvolume2</volume>
</volList>
</cliOutput>
"""
xml_volume_absent = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cliOutput>
<opRet>0</opRet>
<volList>
<count>0</count>
</volList>
</cliOutput>
"""
xml_volume_status = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cliOutput>
<opRet>0</opRet>
<volStatus>
<volumes>
<volume>
<volName>myvol1</volName>
<nodeCount>3</nodeCount>
<node>
<hostname>node01</hostname>
<path>/tmp/foo</path>
<peerid>830700d7-0684-497c-a12c-c02e365fb90b</peerid>
<status>1</status>
<port>49155</port>
<ports>
<tcp>49155</tcp>
<rdma>N/A</rdma>
</ports>
<pid>2470</pid>
</node>
<node>
<hostname>NFS Server</hostname>
<path>localhost</path>
<peerid>830700d7-0684-497c-a12c-c02e365fb90b</peerid>
<status>0</status>
<port>N/A</port>
<ports>
<tcp>N/A</tcp>
<rdma>N/A</rdma>
</ports>
<pid>-1</pid>
</node>
<tasks/>
</volume>
</volumes>
</volStatus>
</cliOutput>
"""
xml_volume_info_running = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cliOutput>
<opRet>0</opRet>
<volInfo>
<volumes>
<volume>
<name>myvol1</name>
<id>f03c2180-cf55-4f77-ae0b-3650f57c82a1</id>
<status>1</status>
<statusStr>Started</statusStr>
<brickCount>1</brickCount>
<distCount>1</distCount>
<stripeCount>1</stripeCount>
<replicaCount>1</replicaCount>
<disperseCount>0</disperseCount>
<redundancyCount>0</redundancyCount>
<type>0</type>
<typeStr>Distribute</typeStr>
<transport>0</transport>
<bricks>
<brick uuid="830700d7-0684-497c-a12c-c02e365fb90b">node01:/tmp/foo<name>node01:/tmp/foo</name><hostUuid>830700d7-0684-497c-a12c-c02e365fb90b</hostUuid></brick>
</bricks>
<optCount>1</optCount>
<options>
<option>
<name>performance.readdir-ahead</name>
<value>on</value>
</option>
</options>
</volume>
<count>1</count>
</volumes>
</volInfo>
</cliOutput>
"""
xml_volume_info_stopped = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cliOutput>
<opRet>0</opRet>
<volInfo>
<volumes>
<volume>
<name>myvol1</name>
<status>1</status>
</volume>
</volumes>
</volInfo>
</cliOutput>
"""
xml_command_success = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cliOutput>
<opRet>0</opRet>
</cliOutput>
"""
xml_command_fail = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cliOutput>
<opRet>-1</opRet>
<opErrno>0</opErrno>
<opErrstr>Command Failed</opErrstr>
</cliOutput>
"""
@skipIf(NO_MOCK, NO_MOCK_REASON)
class GlusterfsTestCase(TestCase):
'''
Test cases for salt.modules.glusterfs
'''
# 'list_peers' function tests: 1
maxDiff = None
def test_list_peers(self):
'''
Test if it return a list of gluster peers
'''
mock = MagicMock(return_value=xml_peer_present)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertDictEqual(glusterfs.list_peers(), {
'node02': ['node02.domain.dom', '10.0.0.2']})
mock = MagicMock(return_value=xml_command_success)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertIsNone(glusterfs.list_peers())
# 'peer' function tests: 1
def test_peer(self):
'''
Test if it adds another node into the peer list.
'''
# invalid characters
mock = MagicMock(return_value=True)
with patch.object(suc, 'check_name', mock):
self.assertRaises(SaltInvocationError, glusterfs.peer, 'a')
# version 3.4
# by hostname
# peer failed unknown hostname
# peer failed can't connect
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.fail_cant_connect)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(CommandExecutionError, glusterfs.peer, 'server2')
# peer self
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_self)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('server1'),
{'exitval': '1', 'output': 'success: on localhost not needed'})
# peer added
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_other)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('server2'),
{'exitval': '0', 'output': 'success'})
# peer already member
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_already_peer['hostname'])
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('server2'),
{'exitval': '2', 'output': 'success: host server2 port 24007 already in peer list'})
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_already_peer['ip'])
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.2'),
{'exitval': '2', 'output': 'success: host 10.0.0.2 port 24007 already in peer list'})
# peer in reverse (probe server1 from server2)
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_first_hostname_from_second_first_time)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('server1'),
{'exitval': '0', 'output': 'success'})
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_first_hostname_from_second_second_time)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('server1'),
{'exitval': '2', 'output': 'success: host server1 port 24007 already in peer list'})
# peer in reverse using ip address instead of hostname
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_reverse_already_peer['ip'])
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.1'),
{'exitval': '2', 'output': 'success: host 10.0.0.1 port 24007 already in peer list'})
# by ip address
# peer self
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_self)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.1'),
{'exitval': '1', 'output': 'success: on localhost not needed'})
# peer added
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_other)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.2'),
{'exitval': '0', 'output': 'success'})
# peer already member
mock = MagicMock(
return_value=GlusterResults.v34.peer_probe.success_already_peer['ip'])
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.2'),
{'exitval': '2', 'output': 'success: host 10.0.0.2 port 24007 already in peer list'})
# version 3.7
# peer failed unknown hostname
# peer failed can't connect
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.fail_cant_connect)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(CommandExecutionError, glusterfs.peer, 'server2')
# peer self
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.success_self)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('server1'),
{'exitval': '1', 'output': 'Probe on localhost not needed'})
# peer added
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.success_other)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('server2'),
{'exitval': '0', 'output': None})
# peer already member
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.success_already_peer['hostname'])
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('server2'),
{'exitval': '2', 'output': 'Host server2 port 24007 already in peer list'})
# peer in reverse
# by ip address
# peer added
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.success_other)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.2'),
{'exitval': '0', 'output': None})
# peer already member
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.success_already_peer['ip'])
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.2'),
{'exitval': '2', 'output': 'Host 10.0.0.2 port 24007 already in peer list'})
# peer self
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.success_self)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.1'),
{'exitval': '1', 'output': 'Probe on localhost not needed'})
# peer in reverse (probe server1 from server2)
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.success_first_hostname_from_second_first_time)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('server1'),
{'exitval': '2', 'output': 'Host server1 port 24007 already in peer list'})
# peer in reverse using ip address instead of hostname first time
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.success_first_ip_from_second_first_time)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.1'),
{'exitval': '0', 'output': None})
mock = MagicMock(
return_value=GlusterResults.v37.peer_probe.success_first_ip_from_second_second_time)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.peer('10.0.0.1'),
{'exitval': '2', 'output': 'Host 10.0.0.1 port 24007 already in peer list'})
# 'create' function tests: 1
def test_create(self):
'''
Test if it create a glusterfs volume.
'''
mock = MagicMock(return_value='')
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(
SaltInvocationError,
glusterfs.create,
'newvolume',
'host1:brick')
mock = MagicMock(return_value='')
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(
SaltInvocationError,
glusterfs.create,
'newvolume',
'host1/brick')
mock = MagicMock(return_value=xml_command_fail)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(
CommandExecutionError,
glusterfs.create,
'newvolume',
'host1:/brick',
True,
True,
True,
'tcp',
True)
mock = MagicMock(return_value=xml_command_success)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.create('newvolume', 'host1:/brick',
True, True, True, 'tcp', True),
'Volume newvolume created and started')
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.create('newvolume', 'host1:/brick'),
'Volume newvolume created. Start volume to use')
# 'list_volumes' function tests: 1
def test_list_volumes(self):
'''
Test if it list configured volumes
'''
mock = MagicMock(return_value=xml_volume_absent)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertListEqual(glusterfs.list_volumes(), [])
mock = MagicMock(return_value=xml_volume_present)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertListEqual(glusterfs.list_volumes(),
['Newvolume1', 'Newvolume2'])
# 'status' function tests: 1
def test_status(self):
'''
Test if it check the status of a gluster volume.
'''
mock = MagicMock(return_value=xml_command_fail)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(
CommandExecutionError, glusterfs.status, 'myvol1')
res = {'bricks': {
'node01:/tmp/foo': {
'host': 'node01',
'hostname': 'node01',
'online': True,
'path': '/tmp/foo',
'peerid': '830700d7-0684-497c-a12c-c02e365fb90b',
'pid': '2470',
'port': '49155',
'ports': {
'rdma': 'N/A',
'tcp': '49155'},
'status': '1'}},
'healers': {},
'nfs': {
'node01': {
'host': 'NFS Server',
'hostname': 'NFS Server',
'online': False,
'path': 'localhost',
'peerid': '830700d7-0684-497c-a12c-c02e365fb90b',
'pid': '-1',
'port': 'N/A',
'ports': {
'rdma': 'N/A',
'tcp': 'N/A'},
'status': '0'}}}
mock = MagicMock(return_value=xml_volume_status)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertDictEqual(glusterfs.status('myvol1'), res)
# 'start_volume' function tests: 1
def test_volume_info(self):
'''
Test if it returns the volume info.
'''
res = {'myvol1': {
'brickCount': '1',
'bricks': {
'brick1': {
'hostUuid': '830700d7-0684-497c-a12c-c02e365fb90b',
'path': 'node01:/tmp/foo',
'uuid': '830700d7-0684-497c-a12c-c02e365fb90b'}},
'disperseCount': '0',
'distCount': '1',
'id': 'f03c2180-cf55-4f77-ae0b-3650f57c82a1',
'name': 'myvol1',
'optCount': '1',
'options': {
'performance.readdir-ahead': 'on'},
'redundancyCount': '0',
'replicaCount': '1',
'status': '1',
'statusStr': 'Started',
'stripeCount': '1',
'transport': '0',
'type': '0',
'typeStr': 'Distribute'}}
mock = MagicMock(return_value=xml_volume_info_running)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertDictEqual(glusterfs.info('myvol1'), res)
def test_start_volume(self):
'''
Test if it start a gluster volume.
'''
mock_list = MagicMock(return_value=['Newvolume1', 'Newvolume2'])
with patch.object(glusterfs, 'list_volumes', mock_list):
mock_status = MagicMock(return_value={'status': '1'})
with patch.object(glusterfs, 'info', mock_status):
mock = MagicMock(return_value=xml_command_success)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.start_volume('Newvolume1'),
'Volume already started')
mock_status = MagicMock(return_value={'status': '0'})
with patch.object(glusterfs, 'info', mock_status):
mock_run = MagicMock(return_value=xml_command_success)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock_run}):
self.assertEqual(glusterfs.start_volume('Newvolume1'),
'Volume Newvolume1 started')
mock = MagicMock(return_value=xml_command_fail)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(
CommandExecutionError, glusterfs.start_volume, 'Newvolume1')
# 'stop_volume' function tests: 1
def test_stop_volume(self):
'''
Test if it stop a gluster volume.
'''
mock = MagicMock(return_value={})
with patch.object(glusterfs, 'status', mock):
mock = MagicMock(return_value=xml_command_success)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.stop_volume('Newvolume1'),
'Volume Newvolume1 stopped')
mock = MagicMock(return_value=xml_command_fail)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(
CommandExecutionError, glusterfs.stop_volume, 'Newvolume1')
mock = MagicMock(return_value=xml_command_fail)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(
CommandExecutionError, glusterfs.stop_volume, 'Newvolume1')
# 'delete' function tests: 1
def test_delete(self):
'''
Test if it deletes a gluster volume.
'''
mock = MagicMock(return_value=['Newvolume1', 'Newvolume2'])
with patch.object(glusterfs, 'list_volumes', mock):
# volume doesn't exist
self.assertRaises(
SaltInvocationError, glusterfs.delete, 'Newvolume3')
mock = MagicMock(return_value={'status': '1'})
with patch.object(glusterfs, 'info', mock):
mock = MagicMock(return_value=xml_command_success)
# volume exists, should not be stopped, and is started
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(
SaltInvocationError,
glusterfs.delete,
'Newvolume1',
False)
# volume exists, should be stopped, and is started
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.delete('Newvolume1'),
'Volume Newvolume1 stopped and deleted')
# volume exists and isn't started
mock = MagicMock(return_value={'status': '0'})
with patch.object(glusterfs, 'info', mock):
mock = MagicMock(return_value=xml_command_success)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.delete('Newvolume1'),
'Volume Newvolume1 deleted')
# 'add_volume_bricks' function tests: 1
def test_add_volume_bricks(self):
'''
Test if it add brick(s) to an existing volume
'''
# volume does not exist
mock = MagicMock(return_value=xml_command_fail)
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertRaises(
CommandExecutionError,
glusterfs.add_volume_bricks,
'Newvolume1',
['bricks'])
ret = '1 bricks successfully added to the volume Newvolume1'
# volume does exist
mock = MagicMock(return_value={'Newvolume1': {'bricks': {}}})
with patch.object(glusterfs, 'info', mock):
mock = MagicMock(return_value=xml_command_success)
# ... and the added brick does not exist
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
self.assertEqual(glusterfs.add_volume_bricks('Newvolume1',
['bricks']), ret)
mock = MagicMock(
return_value={'Newvolume1': {'bricks': {'brick1': {'path': 'bricks'}}}})
with patch.object(glusterfs, 'info', mock):
# ... and the added brick does exist
with patch.dict(glusterfs.__salt__, {'cmd.run': mock}):
# As a list
self.assertEqual(
glusterfs.add_volume_bricks(
'Newvolume1',
['bricks']),
'Bricks already in volume Newvolume1')
# As a string
self.assertEqual(
glusterfs.add_volume_bricks(
'Newvolume1',
'bricks'),
'Bricks already in volume Newvolume1')
# And empty list
self.assertEqual(glusterfs.add_volume_bricks('Newvolume1', []),
'Bricks already in volume Newvolume1')
if __name__ == '__main__':
from integration import run_tests
run_tests(GlusterfsTestCase, needs_daemon=False)
|
skoslowski/gnuradio
|
refs/heads/master
|
grc/core/cache.py
|
1
|
# Copyright 2017 Free Software Foundation, Inc.
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
from __future__ import absolute_import, print_function, unicode_literals
from io import open
import json
import logging
import os
import six
from .io import yaml
logger = logging.getLogger(__name__)
class Cache(object):
def __init__(self, filename):
self.cache_file = filename
self.cache = {}
self.need_cache_write = True
self._accessed_items = set()
try:
os.makedirs(os.path.dirname(filename))
except OSError:
pass
try:
self._converter_mtime = os.path.getmtime(filename)
except OSError:
self._converter_mtime = -1
def load(self):
try:
logger.debug("Loading block cache from: {}".format(self.cache_file))
with open(self.cache_file, encoding="utf-8") as cache_file:
self.cache = json.load(cache_file)
self.need_cache_write = False
except (IOError, ValueError):
self.need_cache_write = True
def get_or_load(self, filename):
self._accessed_items.add(filename)
if os.path.getmtime(filename) <= self._converter_mtime:
try:
return self.cache[filename]
except KeyError:
pass
with open(filename, encoding="utf-8") as fp:
data = yaml.safe_load(fp)
self.cache[filename] = data
self.need_cache_write = True
return data
def save(self):
if not self.need_cache_write:
return
logger.debug("Saving %d entries to json cache", len(self.cache))
# Dumping to binary file is only supported for Python3 >= 3.6
with open(self.cache_file, "w", encoding="utf8") as cache_file:
cache_file.write(json.dumps(self.cache, ensure_ascii=False))
def prune(self):
for filename in set(self.cache) - self._accessed_items:
del self.cache[filename]
def __enter__(self):
self.load()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.save()
def byteify(data):
if isinstance(data, dict):
return {byteify(key): byteify(value) for key, value in six.iteritems(data)}
elif isinstance(data, list):
return [byteify(element) for element in data]
elif isinstance(data, six.text_type) and six.PY2:
return data.encode("utf-8")
else:
return data
|
hanleilei/note
|
refs/heads/master
|
python/vir_manager/backstage/view/home_views.py
|
1
|
import datetime
from django.db.models import Q
from django.shortcuts import render
from django.forms.models import model_to_dict
from backstage.base import logger
from backstage.models import IdcRoom
from backstage.models import Colony
from backstage.models import Host
from backstage.models import Virtual
from backstage.models import Images
from utils.detection import query_params
from utils.detection import return_json_api
from utils.common import get_page_info
from utils.common import get_page_params
from utils.common import change_model_to_dict
from utils.common import to_dict
@return_json_api()
def test(request):
"""
* desc test
* input None
* output 统计入库
"""
return ''
@return_json_api()
def count_hosts(request):
"""
* desc 统计所有宿主机信息 cpu 内存 磁盘
* input None
* output 统计入库
"""
return ''
@return_json_api()
def count_idcs(request):
"""
* desc 统计所有机房信息 机房 总数 每个机房的宿主机数量 cpu 内存 磁盘
* input None
* output 统计入库
"""
return ''
@return_json_api()
def count_colony(request):
"""
* desc 统计所有集群信息 集群的 宿主机数量 虚拟机数量 cpu 内存 磁盘
* input None
* output 统计入库
"""
return ''
@return_json_api()
def count_virtual(request):
"""
* desc 统计所有虚拟机信息 数量 cpu 内存 磁盘
* input None
* output 统计入库
"""
return ''
@return_json_api()
def count_images(request):
"""
* desc 统计所有镜像信息 数量 每个机房的数量 以及占比 操作系统总数以及占比
* input None
* output 统计入库
"""
return ''
@return_json_api()
def index(request):
"""
机房
- 集群数量
- 产线数量
- 宿主机数量
- 虚拟机数量
- cpu总量 / 已用量 / 保留量
- 内存总量 / 已用量 / 保留量
- 磁盘总量 / 已用量 / 保留量
集群
- 宿主机数量
- 产线数量
- 虚拟机数量
- cpu总量 / 已用量 / 保留量
- 内存总量 / 已用量 / 保留量
- 磁盘总量 / 已用量 / 保留量
镜像
- 机房 镜像数分布
- 操作系统分布
- 根据状态进行统计
"""
image_info = get_image_count()
return {'image_info': image_info}
def get_colony_count(idc_name=None):
"""
* desc 获取集群的统计信息
* input None
* output 集群统计信息
"""
colony_info = {
'colony_num': 0,
'product_line_num': 0,
'host_num': 0,
'vir_num': 0,
'total_cpu': 0,
'total_memory': 0,
'total_disk': 0,
'used_cpu': 0,
'used_memory': 0,
'used_disk': 0,
'keep_cpu': 0,
'keep_memory': 0,
'keep_disk': 0,
'status': {
'available': 0,
'unavailable': 0
}
}
if idc_name:
query_set = Colony.objects.filter(idc__name=idc_name)
else:
query_set = Colony.objects.all()
def get_image_count():
"""
* desc 获取镜像的统计信息
* input None
* output 镜像统计信息
"""
image_info = {
'idc': {
'num': 0,
'name': {}
},
'os': {
'num': 0,
'os_name': {}
},
'status': {
'available': 0,
'unavailable': 0
}
}
image_dict = {}
image_db = Images.objects.all()
for line in image_db:
os_name = line.os_name
idc_name = line.idc_name
status = line.status
if status == 1:
image_info['status']['available'] += 1
else:
image_info['status']['unavailable'] += 1
if idc_name not in image_info['idc']['name']:
image_info['idc']['name'][idc_name] = 1
else:
image_info['idc']['name'][idc_name] += 1
image_info['idc']['num'] += 1
if os_name not in image_info['os']['os_name']:
image_info['os']['os_name'][os_name] = 1
else:
image_info['os']['os_name'][os_name] += 1
image_info['os']['num'] += 1
return image_info
|
dkubiak789/odoo
|
refs/heads/8.0
|
addons/portal_sale/res_config.py
|
445
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class sale_portal_config_settings(osv.TransientModel):
_inherit = 'account.config.settings'
_columns = {
'group_payment_options': fields.boolean('Show payment buttons to employees too',
implied_group='portal_sale.group_payment_options',
help="Show online payment options on Sale Orders and Customer Invoices to employees. "
"If not checked, these options are only visible to portal users."),
}
|
dims/glance
|
refs/heads/master
|
glance/db/sqlalchemy/api.py
|
1
|
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2010-2011 OpenStack Foundation
# Copyright 2012 Justin Santa Barbara
# Copyright 2013 IBM Corp.
# Copyright 2015 Mirantis, 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.
"""Defines interface for DB access."""
import datetime
import threading
from oslo_config import cfg
from oslo_db import exception as db_exception
from oslo_db.sqlalchemy import session
from oslo_log import log as logging
import osprofiler.sqlalchemy
from retrying import retry
import six
# NOTE(jokke): simplified transition to py3, behaves like py2 xrange
from six.moves import range
import sqlalchemy
from sqlalchemy import MetaData, Table, select
import sqlalchemy.orm as sa_orm
import sqlalchemy.sql as sa_sql
from glance.common import exception
from glance.common import timeutils
from glance.common import utils
from glance.db.sqlalchemy import glare
from glance.db.sqlalchemy.metadef_api import (resource_type
as metadef_resource_type_api)
from glance.db.sqlalchemy.metadef_api import (resource_type_association
as metadef_association_api)
from glance.db.sqlalchemy.metadef_api import namespace as metadef_namespace_api
from glance.db.sqlalchemy.metadef_api import object as metadef_object_api
from glance.db.sqlalchemy.metadef_api import property as metadef_property_api
from glance.db.sqlalchemy.metadef_api import tag as metadef_tag_api
from glance.db.sqlalchemy import models
from glance import glare as ga
from glance.i18n import _, _LW, _LE, _LI
BASE = models.BASE
sa_logger = None
LOG = logging.getLogger(__name__)
STATUSES = ['active', 'saving', 'queued', 'killed', 'pending_delete',
'deleted', 'deactivated']
CONF = cfg.CONF
CONF.import_group("profiler", "glance.common.wsgi")
_FACADE = None
_LOCK = threading.Lock()
def _retry_on_deadlock(exc):
"""Decorator to retry a DB API call if Deadlock was received."""
if isinstance(exc, db_exception.DBDeadlock):
LOG.warn(_LW("Deadlock detected. Retrying..."))
return True
return False
def _create_facade_lazily():
global _LOCK, _FACADE
if _FACADE is None:
with _LOCK:
if _FACADE is None:
_FACADE = session.EngineFacade.from_config(CONF)
if CONF.profiler.enabled and CONF.profiler.trace_sqlalchemy:
osprofiler.sqlalchemy.add_tracing(sqlalchemy,
_FACADE.get_engine(),
"db")
return _FACADE
def get_engine():
facade = _create_facade_lazily()
return facade.get_engine()
def get_session(autocommit=True, expire_on_commit=False):
facade = _create_facade_lazily()
return facade.get_session(autocommit=autocommit,
expire_on_commit=expire_on_commit)
def clear_db_env():
"""
Unset global configuration variables for database.
"""
global _FACADE
_FACADE = None
def _check_mutate_authorization(context, image_ref):
if not is_image_mutable(context, image_ref):
LOG.warn(_LW("Attempted to modify image user did not own."))
msg = _("You do not own this image")
if image_ref.is_public:
exc_class = exception.ForbiddenPublicImage
else:
exc_class = exception.Forbidden
raise exc_class(msg)
def image_create(context, values):
"""Create an image from the values dictionary."""
return _image_update(context, values, None, purge_props=False)
def image_update(context, image_id, values, purge_props=False,
from_state=None):
"""
Set the given properties on an image and update it.
:raises: ImageNotFound if image does not exist.
"""
return _image_update(context, values, image_id, purge_props,
from_state=from_state)
@retry(retry_on_exception=_retry_on_deadlock, wait_fixed=500,
stop_max_attempt_number=50)
def image_destroy(context, image_id):
"""Destroy the image or raise if it does not exist."""
session = get_session()
with session.begin():
image_ref = _image_get(context, image_id, session=session)
# Perform authorization check
_check_mutate_authorization(context, image_ref)
image_ref.delete(session=session)
delete_time = image_ref.deleted_at
_image_locations_delete_all(context, image_id, delete_time, session)
_image_property_delete_all(context, image_id, delete_time, session)
_image_member_delete_all(context, image_id, delete_time, session)
_image_tag_delete_all(context, image_id, delete_time, session)
return _normalize_locations(context, image_ref)
def _normalize_locations(context, image, force_show_deleted=False):
"""
Generate suitable dictionary list for locations field of image.
We don't need to set other data fields of location record which return
from image query.
"""
if image['status'] == 'deactivated' and not context.is_admin:
# Locations are not returned for a deactivated image for non-admin user
image['locations'] = []
return image
if force_show_deleted:
locations = image['locations']
else:
locations = filter(lambda x: not x.deleted, image['locations'])
image['locations'] = [{'id': loc['id'],
'url': loc['value'],
'metadata': loc['meta_data'],
'status': loc['status']}
for loc in locations]
return image
def _normalize_tags(image):
undeleted_tags = filter(lambda x: not x.deleted, image['tags'])
image['tags'] = [tag['value'] for tag in undeleted_tags]
return image
def image_get(context, image_id, session=None, force_show_deleted=False):
image = _image_get(context, image_id, session=session,
force_show_deleted=force_show_deleted)
image = _normalize_locations(context, image.to_dict(),
force_show_deleted=force_show_deleted)
return image
def _check_image_id(image_id):
"""
check if the given image id is valid before executing operations. For
now, we only check its length. The original purpose of this method is
wrapping the different behaviors between MySql and DB2 when the image id
length is longer than the defined length in database model.
:param image_id: The id of the image we want to check
:returns: Raise NoFound exception if given image id is invalid
"""
if (image_id and
len(image_id) > models.Image.id.property.columns[0].type.length):
raise exception.ImageNotFound()
def _image_get(context, image_id, session=None, force_show_deleted=False):
"""Get an image or raise if it does not exist."""
_check_image_id(image_id)
session = session or get_session()
try:
query = session.query(models.Image).options(
sa_orm.joinedload(models.Image.properties)).options(
sa_orm.joinedload(
models.Image.locations)).filter_by(id=image_id)
# filter out deleted images if context disallows it
if not force_show_deleted and not context.can_see_deleted:
query = query.filter_by(deleted=False)
image = query.one()
except sa_orm.exc.NoResultFound:
msg = "No image found with ID %s" % image_id
LOG.debug(msg)
raise exception.ImageNotFound(msg)
# Make sure they can look at it
if not is_image_visible(context, image):
msg = "Forbidding request, image %s not visible" % image_id
LOG.debug(msg)
raise exception.Forbidden(msg)
return image
def is_image_mutable(context, image):
"""Return True if the image is mutable in this context."""
# Is admin == image mutable
if context.is_admin:
return True
# No owner == image not mutable
if image['owner'] is None or context.owner is None:
return False
# Image only mutable by its owner
return image['owner'] == context.owner
def is_image_visible(context, image, status=None):
"""Return True if the image is visible in this context."""
# Is admin == image visible
if context.is_admin:
return True
# No owner == image visible
if image['owner'] is None:
return True
# Image is_public == image visible
if image['is_public']:
return True
# Perform tests based on whether we have an owner
if context.owner is not None:
if context.owner == image['owner']:
return True
# Figure out if this image is shared with that tenant
members = image_member_find(context,
image_id=image['id'],
member=context.owner,
status=status)
if members:
return True
# Private image
return False
def _get_default_column_value(column_type):
"""Return the default value of the columns from DB table
In postgreDB case, if no right default values are being set, an
psycopg2.DataError will be thrown.
"""
type_schema = {
'datetime': None,
'big_integer': 0,
'integer': 0,
'string': ''
}
if isinstance(column_type, sa_sql.type_api.Variant):
return _get_default_column_value(column_type.impl)
return type_schema[column_type.__visit_name__]
def _paginate_query(query, model, limit, sort_keys, marker=None,
sort_dir=None, sort_dirs=None):
"""Returns a query with sorting / pagination criteria added.
Pagination works by requiring a unique sort_key, specified by sort_keys.
(If sort_keys is not unique, then we risk looping through values.)
We use the last row in the previous page as the 'marker' for pagination.
So we must return values that follow the passed marker in the order.
With a single-valued sort_key, this would be easy: sort_key > X.
With a compound-values sort_key, (k1, k2, k3) we must do this to repeat
the lexicographical ordering:
(k1 > X1) or (k1 == X1 && k2 > X2) or (k1 == X1 && k2 == X2 && k3 > X3)
We also have to cope with different sort_directions.
Typically, the id of the last row is used as the client-facing pagination
marker, then the actual marker object must be fetched from the db and
passed in to us as marker.
:param query: the query object to which we should add paging/sorting
:param model: the ORM model class
:param limit: maximum number of items to return
:param sort_keys: array of attributes by which results should be sorted
:param marker: the last item of the previous page; we returns the next
results after this value.
:param sort_dir: direction in which results should be sorted (asc, desc)
:param sort_dirs: per-column array of sort_dirs, corresponding to sort_keys
:rtype: sqlalchemy.orm.query.Query
:returns: The query with sorting/pagination added.
"""
if 'id' not in sort_keys:
# TODO(justinsb): If this ever gives a false-positive, check
# the actual primary key, rather than assuming its id
LOG.warn(_LW('Id not in sort_keys; is sort_keys unique?'))
assert(not (sort_dir and sort_dirs)) # nosec
# nosec: This function runs safely if the assertion fails.
# Default the sort direction to ascending
if sort_dir is None:
sort_dir = 'asc'
# Ensure a per-column sort direction
if sort_dirs is None:
sort_dirs = [sort_dir] * len(sort_keys)
assert(len(sort_dirs) == len(sort_keys)) # nosec
# nosec: This function runs safely if the assertion fails.
if len(sort_dirs) < len(sort_keys):
sort_dirs += [sort_dir] * (len(sort_keys) - len(sort_dirs))
# Add sorting
for current_sort_key, current_sort_dir in zip(sort_keys, sort_dirs):
sort_dir_func = {
'asc': sqlalchemy.asc,
'desc': sqlalchemy.desc,
}[current_sort_dir]
try:
sort_key_attr = getattr(model, current_sort_key)
except AttributeError:
raise exception.InvalidSortKey()
query = query.order_by(sort_dir_func(sort_key_attr))
default = '' # Default to an empty string if NULL
# Add pagination
if marker is not None:
marker_values = []
for sort_key in sort_keys:
v = getattr(marker, sort_key)
if v is None:
v = default
marker_values.append(v)
# Build up an array of sort criteria as in the docstring
criteria_list = []
for i in range(len(sort_keys)):
crit_attrs = []
for j in range(i):
model_attr = getattr(model, sort_keys[j])
default = _get_default_column_value(
model_attr.property.columns[0].type)
attr = sa_sql.expression.case([(model_attr != None,
model_attr), ],
else_=default)
crit_attrs.append((attr == marker_values[j]))
model_attr = getattr(model, sort_keys[i])
default = _get_default_column_value(
model_attr.property.columns[0].type)
attr = sa_sql.expression.case([(model_attr != None,
model_attr), ],
else_=default)
if sort_dirs[i] == 'desc':
crit_attrs.append((attr < marker_values[i]))
elif sort_dirs[i] == 'asc':
crit_attrs.append((attr > marker_values[i]))
else:
raise ValueError(_("Unknown sort direction, "
"must be 'desc' or 'asc'"))
criteria = sa_sql.and_(*crit_attrs)
criteria_list.append(criteria)
f = sa_sql.or_(*criteria_list)
query = query.filter(f)
if limit is not None:
query = query.limit(limit)
return query
def _make_conditions_from_filters(filters, is_public=None):
# NOTE(venkatesh) make copy of the filters are to be altered in this
# method.
filters = filters.copy()
image_conditions = []
prop_conditions = []
tag_conditions = []
if is_public is not None:
image_conditions.append(models.Image.is_public == is_public)
if 'checksum' in filters:
checksum = filters.pop('checksum')
image_conditions.append(models.Image.checksum == checksum)
if 'is_public' in filters:
key = 'is_public'
value = filters.pop('is_public')
prop_filters = _make_image_property_condition(key=key, value=value)
prop_conditions.append(prop_filters)
for (k, v) in filters.pop('properties', {}).items():
prop_filters = _make_image_property_condition(key=k, value=v)
prop_conditions.append(prop_filters)
if 'changes-since' in filters:
# normalize timestamp to UTC, as sqlalchemy doesn't appear to
# respect timezone offsets
changes_since = timeutils.normalize_time(filters.pop('changes-since'))
image_conditions.append(models.Image.updated_at > changes_since)
if 'deleted' in filters:
deleted_filter = filters.pop('deleted')
image_conditions.append(models.Image.deleted == deleted_filter)
# TODO(bcwaldon): handle this logic in registry server
if not deleted_filter:
image_statuses = [s for s in STATUSES if s != 'killed']
image_conditions.append(models.Image.status.in_(image_statuses))
if 'tags' in filters:
tags = filters.pop('tags')
for tag in tags:
tag_filters = [models.ImageTag.deleted == False]
tag_filters.extend([models.ImageTag.value == tag])
tag_conditions.append(tag_filters)
filters = {k: v for k, v in filters.items() if v is not None}
# need to copy items because filters is modified in the loop body
# (filters.pop(k))
keys = list(filters.keys())
for k in keys:
key = k
if k.endswith('_min') or k.endswith('_max'):
key = key[0:-4]
try:
v = int(filters.pop(k))
except ValueError:
msg = _("Unable to filter on a range "
"with a non-numeric value.")
raise exception.InvalidFilterRangeValue(msg)
if k.endswith('_min'):
image_conditions.append(getattr(models.Image, key) >= v)
if k.endswith('_max'):
image_conditions.append(getattr(models.Image, key) <= v)
elif k in ['created_at', 'updated_at']:
attr_value = getattr(models.Image, key)
operator, isotime = utils.split_filter_op(filters.pop(k))
try:
parsed_time = timeutils.parse_isotime(isotime)
threshold = timeutils.normalize_time(parsed_time)
except ValueError:
msg = (_("Bad \"%s\" query filter format. "
"Use ISO 8601 DateTime notation.") % k)
raise exception.InvalidParameterValue(msg)
comparison = utils.evaluate_filter_op(attr_value, operator,
threshold)
image_conditions.append(comparison)
for (k, value) in filters.items():
if hasattr(models.Image, k):
image_conditions.append(getattr(models.Image, k) == value)
else:
prop_filters = _make_image_property_condition(key=k, value=value)
prop_conditions.append(prop_filters)
return image_conditions, prop_conditions, tag_conditions
def _make_image_property_condition(key, value):
prop_filters = [models.ImageProperty.deleted == False]
prop_filters.extend([models.ImageProperty.name == key])
prop_filters.extend([models.ImageProperty.value == value])
return prop_filters
def _select_images_query(context, image_conditions, admin_as_user,
member_status, visibility):
session = get_session()
img_conditional_clause = sa_sql.and_(*image_conditions)
regular_user = (not context.is_admin) or admin_as_user
query_member = session.query(models.Image).join(
models.Image.members).filter(img_conditional_clause)
if regular_user:
member_filters = [models.ImageMember.deleted == False]
if context.owner is not None:
member_filters.extend([models.ImageMember.member == context.owner])
if member_status != 'all':
member_filters.extend([
models.ImageMember.status == member_status])
query_member = query_member.filter(sa_sql.and_(*member_filters))
# NOTE(venkatesh) if the 'visibility' is set to 'shared', we just
# query the image members table. No union is required.
if visibility is not None and visibility == 'shared':
return query_member
query_image = session.query(models.Image).filter(img_conditional_clause)
if regular_user:
query_image = query_image.filter(models.Image.is_public == True)
query_image_owner = None
if context.owner is not None:
query_image_owner = session.query(models.Image).filter(
models.Image.owner == context.owner).filter(
img_conditional_clause)
if query_image_owner is not None:
query = query_image.union(query_image_owner, query_member)
else:
query = query_image.union(query_member)
return query
else:
# Admin user
return query_image
def image_get_all(context, filters=None, marker=None, limit=None,
sort_key=None, sort_dir=None,
member_status='accepted', is_public=None,
admin_as_user=False, return_tag=False):
"""
Get all images that match zero or more filters.
:param filters: dict of filter keys and values. If a 'properties'
key is present, it is treated as a dict of key/value
filters on the image properties attribute
:param marker: image id after which to start page
:param limit: maximum number of images to return
:param sort_key: list of image attributes by which results should be sorted
:param sort_dir: directions in which results should be sorted (asc, desc)
:param member_status: only return shared images that have this membership
status
:param is_public: If true, return only public images. If false, return
only private and shared images.
:param admin_as_user: For backwards compatibility. If true, then return to
an admin the equivalent set of images which it would see
if it was a regular user
:param return_tag: To indicates whether image entry in result includes it
relevant tag entries. This could improve upper-layer
query performance, to prevent using separated calls
"""
sort_key = ['created_at'] if not sort_key else sort_key
default_sort_dir = 'desc'
if not sort_dir:
sort_dir = [default_sort_dir] * len(sort_key)
elif len(sort_dir) == 1:
default_sort_dir = sort_dir[0]
sort_dir *= len(sort_key)
filters = filters or {}
visibility = filters.pop('visibility', None)
showing_deleted = 'changes-since' in filters or filters.get('deleted',
False)
img_cond, prop_cond, tag_cond = _make_conditions_from_filters(
filters, is_public)
query = _select_images_query(context,
img_cond,
admin_as_user,
member_status,
visibility)
if visibility is not None:
if visibility == 'public':
query = query.filter(models.Image.is_public == True)
elif visibility == 'private':
query = query.filter(models.Image.is_public == False)
if prop_cond:
for prop_condition in prop_cond:
query = query.join(models.ImageProperty, aliased=True).filter(
sa_sql.and_(*prop_condition))
if tag_cond:
for tag_condition in tag_cond:
query = query.join(models.ImageTag, aliased=True).filter(
sa_sql.and_(*tag_condition))
marker_image = None
if marker is not None:
marker_image = _image_get(context,
marker,
force_show_deleted=showing_deleted)
for key in ['created_at', 'id']:
if key not in sort_key:
sort_key.append(key)
sort_dir.append(default_sort_dir)
query = _paginate_query(query, models.Image, limit,
sort_key,
marker=marker_image,
sort_dir=None,
sort_dirs=sort_dir)
query = query.options(sa_orm.joinedload(
models.Image.properties)).options(
sa_orm.joinedload(models.Image.locations))
if return_tag:
query = query.options(sa_orm.joinedload(models.Image.tags))
images = []
for image in query.all():
image_dict = image.to_dict()
image_dict = _normalize_locations(context, image_dict,
force_show_deleted=showing_deleted)
if return_tag:
image_dict = _normalize_tags(image_dict)
images.append(image_dict)
return images
def _drop_protected_attrs(model_class, values):
"""
Removed protected attributes from values dictionary using the models
__protected_attributes__ field.
"""
for attr in model_class.__protected_attributes__:
if attr in values:
del values[attr]
def _image_get_disk_usage_by_owner(owner, session, image_id=None):
query = session.query(models.Image)
query = query.filter(models.Image.owner == owner)
if image_id is not None:
query = query.filter(models.Image.id != image_id)
query = query.filter(models.Image.size > 0)
query = query.filter(~models.Image.status.in_(['killed', 'deleted']))
images = query.all()
total = 0
for i in images:
locations = [l for l in i.locations if l['status'] != 'deleted']
total += (i.size * len(locations))
return total
def _validate_image(values, mandatory_status=True):
"""
Validates the incoming data and raises a Invalid exception
if anything is out of order.
:param values: Mapping of image metadata to check
:param mandatory_status: Whether to validate status from values
"""
if mandatory_status:
status = values.get('status')
if not status:
msg = "Image status is required."
raise exception.Invalid(msg)
if status not in STATUSES:
msg = "Invalid image status '%s' for image." % status
raise exception.Invalid(msg)
# validate integer values to eliminate DBError on save
utils.validate_mysql_int(min_disk=values.get('min_disk'),
min_ram=values.get('min_ram'))
return values
def _update_values(image_ref, values):
for k in values:
if getattr(image_ref, k) != values[k]:
setattr(image_ref, k, values[k])
@retry(retry_on_exception=_retry_on_deadlock, wait_fixed=500,
stop_max_attempt_number=50)
@utils.no_4byte_params
def _image_update(context, values, image_id, purge_props=False,
from_state=None):
"""
Used internally by image_create and image_update
:param context: Request context
:param values: A dict of attributes to set
:param image_id: If None, create the image, otherwise, find and update it
"""
# NOTE(jbresnah) values is altered in this so a copy is needed
values = values.copy()
session = get_session()
with session.begin():
# Remove the properties passed in the values mapping. We
# handle properties separately from base image attributes,
# and leaving properties in the values mapping will cause
# a SQLAlchemy model error because SQLAlchemy expects the
# properties attribute of an Image model to be a list and
# not a dict.
properties = values.pop('properties', {})
location_data = values.pop('locations', None)
new_status = values.get('status', None)
if image_id:
image_ref = _image_get(context, image_id, session=session)
current = image_ref.status
# Perform authorization check
_check_mutate_authorization(context, image_ref)
else:
if values.get('size') is not None:
values['size'] = int(values['size'])
if 'min_ram' in values:
values['min_ram'] = int(values['min_ram'] or 0)
if 'min_disk' in values:
values['min_disk'] = int(values['min_disk'] or 0)
values['is_public'] = bool(values.get('is_public', False))
values['protected'] = bool(values.get('protected', False))
image_ref = models.Image()
# Need to canonicalize ownership
if 'owner' in values and not values['owner']:
values['owner'] = None
if image_id:
# Don't drop created_at if we're passing it in...
_drop_protected_attrs(models.Image, values)
# NOTE(iccha-sethi): updated_at must be explicitly set in case
# only ImageProperty table was modifited
values['updated_at'] = timeutils.utcnow()
if image_id:
query = session.query(models.Image).filter_by(id=image_id)
if from_state:
query = query.filter_by(status=from_state)
mandatory_status = True if new_status else False
_validate_image(values, mandatory_status=mandatory_status)
# Validate fields for Images table. This is similar to what is done
# for the query result update except that we need to do it prior
# in this case.
values = {key: values[key] for key in values
if key in image_ref.to_dict()}
updated = query.update(values, synchronize_session='fetch')
if not updated:
msg = (_('cannot transition from %(current)s to '
'%(next)s in update (wanted '
'from_state=%(from)s)') %
{'current': current, 'next': new_status,
'from': from_state})
raise exception.Conflict(msg)
image_ref = _image_get(context, image_id, session=session)
else:
image_ref.update(values)
# Validate the attributes before we go any further. From my
# investigation, the @validates decorator does not validate
# on new records, only on existing records, which is, well,
# idiotic.
values = _validate_image(image_ref.to_dict())
_update_values(image_ref, values)
try:
image_ref.save(session=session)
except db_exception.DBDuplicateEntry:
raise exception.Duplicate("Image ID %s already exists!"
% values['id'])
_set_properties_for_image(context, image_ref, properties, purge_props,
session)
if location_data:
_image_locations_set(context, image_ref.id, location_data,
session=session)
return image_get(context, image_ref.id)
@utils.no_4byte_params
def image_location_add(context, image_id, location, session=None):
deleted = location['status'] in ('deleted', 'pending_delete')
delete_time = timeutils.utcnow() if deleted else None
location_ref = models.ImageLocation(image_id=image_id,
value=location['url'],
meta_data=location['metadata'],
status=location['status'],
deleted=deleted,
deleted_at=delete_time)
session = session or get_session()
location_ref.save(session=session)
@utils.no_4byte_params
def image_location_update(context, image_id, location, session=None):
loc_id = location.get('id')
if loc_id is None:
msg = _("The location data has an invalid ID: %d") % loc_id
raise exception.Invalid(msg)
try:
session = session or get_session()
location_ref = session.query(models.ImageLocation).filter_by(
id=loc_id).filter_by(image_id=image_id).one()
deleted = location['status'] in ('deleted', 'pending_delete')
updated_time = timeutils.utcnow()
delete_time = updated_time if deleted else None
location_ref.update({"value": location['url'],
"meta_data": location['metadata'],
"status": location['status'],
"deleted": deleted,
"updated_at": updated_time,
"deleted_at": delete_time})
location_ref.save(session=session)
except sa_orm.exc.NoResultFound:
msg = (_("No location found with ID %(loc)s from image %(img)s") %
dict(loc=loc_id, img=image_id))
LOG.warn(msg)
raise exception.NotFound(msg)
def image_location_delete(context, image_id, location_id, status,
delete_time=None, session=None):
if status not in ('deleted', 'pending_delete'):
msg = _("The status of deleted image location can only be set to "
"'pending_delete' or 'deleted'")
raise exception.Invalid(msg)
try:
session = session or get_session()
location_ref = session.query(models.ImageLocation).filter_by(
id=location_id).filter_by(image_id=image_id).one()
delete_time = delete_time or timeutils.utcnow()
location_ref.update({"deleted": True,
"status": status,
"updated_at": delete_time,
"deleted_at": delete_time})
location_ref.save(session=session)
except sa_orm.exc.NoResultFound:
msg = (_("No location found with ID %(loc)s from image %(img)s") %
dict(loc=location_id, img=image_id))
LOG.warn(msg)
raise exception.NotFound(msg)
def _image_locations_set(context, image_id, locations, session=None):
# NOTE(zhiyan): 1. Remove records from DB for deleted locations
session = session or get_session()
query = session.query(models.ImageLocation).filter_by(
image_id=image_id).filter_by(deleted=False)
loc_ids = [loc['id'] for loc in locations if loc.get('id')]
if loc_ids:
query = query.filter(~models.ImageLocation.id.in_(loc_ids))
for loc_id in [loc_ref.id for loc_ref in query.all()]:
image_location_delete(context, image_id, loc_id, 'deleted',
session=session)
# NOTE(zhiyan): 2. Adding or update locations
for loc in locations:
if loc.get('id') is None:
image_location_add(context, image_id, loc, session=session)
else:
image_location_update(context, image_id, loc, session=session)
def _image_locations_delete_all(context, image_id,
delete_time=None, session=None):
"""Delete all image locations for given image"""
session = session or get_session()
location_refs = session.query(models.ImageLocation).filter_by(
image_id=image_id).filter_by(deleted=False).all()
for loc_id in [loc_ref.id for loc_ref in location_refs]:
image_location_delete(context, image_id, loc_id, 'deleted',
delete_time=delete_time, session=session)
@utils.no_4byte_params
def _set_properties_for_image(context, image_ref, properties,
purge_props=False, session=None):
"""
Create or update a set of image_properties for a given image
:param context: Request context
:param image_ref: An Image object
:param properties: A dict of properties to set
:param session: A SQLAlchemy session to use (if present)
"""
orig_properties = {}
for prop_ref in image_ref.properties:
orig_properties[prop_ref.name] = prop_ref
for name, value in six.iteritems(properties):
prop_values = {'image_id': image_ref.id,
'name': name,
'value': value}
if name in orig_properties:
prop_ref = orig_properties[name]
_image_property_update(context, prop_ref, prop_values,
session=session)
else:
image_property_create(context, prop_values, session=session)
if purge_props:
for key in orig_properties.keys():
if key not in properties:
prop_ref = orig_properties[key]
image_property_delete(context, prop_ref.name,
image_ref.id, session=session)
def _image_child_entry_delete_all(child_model_cls, image_id, delete_time=None,
session=None):
"""Deletes all the child entries for the given image id.
Deletes all the child entries of the given child entry ORM model class
using the parent image's id.
The child entry ORM model class can be one of the following:
model.ImageLocation, model.ImageProperty, model.ImageMember and
model.ImageTag.
:param child_model_cls: the ORM model class.
:param image_id: id of the image whose child entries are to be deleted.
:param delete_time: datetime of deletion to be set.
If None, uses current datetime.
:param session: A SQLAlchemy session to use (if present)
:rtype: int
:returns: The number of child entries got soft-deleted.
"""
session = session or get_session()
query = session.query(child_model_cls).filter_by(
image_id=image_id).filter_by(deleted=False)
delete_time = delete_time or timeutils.utcnow()
count = query.update({"deleted": True, "deleted_at": delete_time})
return count
def image_property_create(context, values, session=None):
"""Create an ImageProperty object."""
prop_ref = models.ImageProperty()
prop = _image_property_update(context, prop_ref, values, session=session)
return prop.to_dict()
def _image_property_update(context, prop_ref, values, session=None):
"""
Used internally by image_property_create and image_property_update.
"""
_drop_protected_attrs(models.ImageProperty, values)
values["deleted"] = False
prop_ref.update(values)
prop_ref.save(session=session)
return prop_ref
def image_property_delete(context, prop_ref, image_ref, session=None):
"""
Used internally by image_property_create and image_property_update.
"""
session = session or get_session()
prop = session.query(models.ImageProperty).filter_by(image_id=image_ref,
name=prop_ref).one()
prop.delete(session=session)
return prop
def _image_property_delete_all(context, image_id, delete_time=None,
session=None):
"""Delete all image properties for given image"""
props_updated_count = _image_child_entry_delete_all(models.ImageProperty,
image_id,
delete_time,
session)
return props_updated_count
def image_member_create(context, values, session=None):
"""Create an ImageMember object."""
memb_ref = models.ImageMember()
_image_member_update(context, memb_ref, values, session=session)
return _image_member_format(memb_ref)
def _image_member_format(member_ref):
"""Format a member ref for consumption outside of this module."""
return {
'id': member_ref['id'],
'image_id': member_ref['image_id'],
'member': member_ref['member'],
'can_share': member_ref['can_share'],
'status': member_ref['status'],
'created_at': member_ref['created_at'],
'updated_at': member_ref['updated_at'],
'deleted': member_ref['deleted']
}
def image_member_update(context, memb_id, values):
"""Update an ImageMember object."""
session = get_session()
memb_ref = _image_member_get(context, memb_id, session)
_image_member_update(context, memb_ref, values, session)
return _image_member_format(memb_ref)
def _image_member_update(context, memb_ref, values, session=None):
"""Apply supplied dictionary of values to a Member object."""
_drop_protected_attrs(models.ImageMember, values)
values["deleted"] = False
values.setdefault('can_share', False)
memb_ref.update(values)
memb_ref.save(session=session)
return memb_ref
def image_member_delete(context, memb_id, session=None):
"""Delete an ImageMember object."""
session = session or get_session()
member_ref = _image_member_get(context, memb_id, session)
_image_member_delete(context, member_ref, session)
def _image_member_delete(context, memb_ref, session):
memb_ref.delete(session=session)
def _image_member_delete_all(context, image_id, delete_time=None,
session=None):
"""Delete all image members for given image"""
members_updated_count = _image_child_entry_delete_all(models.ImageMember,
image_id,
delete_time,
session)
return members_updated_count
def _image_member_get(context, memb_id, session):
"""Fetch an ImageMember entity by id."""
query = session.query(models.ImageMember)
query = query.filter_by(id=memb_id)
return query.one()
def image_member_find(context, image_id=None, member=None,
status=None, include_deleted=False):
"""Find all members that meet the given criteria.
Note, currently include_deleted should be true only when create a new
image membership, as there may be a deleted image membership between
the same image and tenant, the membership will be reused in this case.
It should be false in other cases.
:param image_id: identifier of image entity
:param member: tenant to which membership has been granted
:include_deleted: A boolean indicating whether the result should include
the deleted record of image member
"""
session = get_session()
members = _image_member_find(context, session, image_id,
member, status, include_deleted)
return [_image_member_format(m) for m in members]
def _image_member_find(context, session, image_id=None,
member=None, status=None, include_deleted=False):
query = session.query(models.ImageMember)
if not include_deleted:
query = query.filter_by(deleted=False)
if not context.is_admin:
query = query.join(models.Image)
filters = [
models.Image.owner == context.owner,
models.ImageMember.member == context.owner,
]
query = query.filter(sa_sql.or_(*filters))
if image_id is not None:
query = query.filter(models.ImageMember.image_id == image_id)
if member is not None:
query = query.filter(models.ImageMember.member == member)
if status is not None:
query = query.filter(models.ImageMember.status == status)
return query.all()
def image_member_count(context, image_id):
"""Return the number of image members for this image
:param image_id: identifier of image entity
"""
session = get_session()
if not image_id:
msg = _("Image id is required.")
raise exception.Invalid(msg)
query = session.query(models.ImageMember)
query = query.filter_by(deleted=False)
query = query.filter(models.ImageMember.image_id == str(image_id))
return query.count()
def image_tag_set_all(context, image_id, tags):
# NOTE(kragniz): tag ordering should match exactly what was provided, so a
# subsequent call to image_tag_get_all returns them in the correct order
session = get_session()
existing_tags = image_tag_get_all(context, image_id, session)
tags_created = []
for tag in tags:
if tag not in tags_created and tag not in existing_tags:
tags_created.append(tag)
image_tag_create(context, image_id, tag, session)
for tag in existing_tags:
if tag not in tags:
image_tag_delete(context, image_id, tag, session)
@utils.no_4byte_params
def image_tag_create(context, image_id, value, session=None):
"""Create an image tag."""
session = session or get_session()
tag_ref = models.ImageTag(image_id=image_id, value=value)
tag_ref.save(session=session)
return tag_ref['value']
def image_tag_delete(context, image_id, value, session=None):
"""Delete an image tag."""
_check_image_id(image_id)
session = session or get_session()
query = session.query(models.ImageTag).filter_by(
image_id=image_id).filter_by(
value=value).filter_by(deleted=False)
try:
tag_ref = query.one()
except sa_orm.exc.NoResultFound:
raise exception.NotFound()
tag_ref.delete(session=session)
def _image_tag_delete_all(context, image_id, delete_time=None, session=None):
"""Delete all image tags for given image"""
tags_updated_count = _image_child_entry_delete_all(models.ImageTag,
image_id,
delete_time,
session)
return tags_updated_count
def image_tag_get_all(context, image_id, session=None):
"""Get a list of tags for a specific image."""
_check_image_id(image_id)
session = session or get_session()
tags = session.query(models.ImageTag.value).filter_by(
image_id=image_id).filter_by(deleted=False).all()
return [tag[0] for tag in tags]
def purge_deleted_rows(context, age_in_days, max_rows, session=None):
"""Purges soft deleted rows
Deletes rows of table images, table tasks and all dependent tables
according to given age for relevant models.
"""
try:
age_in_days = int(age_in_days)
except ValueError:
LOG.exception(_LE('Invalid value for age, %(age)d'),
{'age': age_in_days})
raise exception.InvalidParameterValue(value=age_in_days,
param='age_in_days')
try:
max_rows = int(max_rows)
except ValueError:
LOG.exception(_LE('Invalid value for max_rows, %(max_rows)d'),
{'max_rows': max_rows})
raise exception.InvalidParameterValue(value=max_rows,
param='max_rows')
session = session or get_session()
metadata = MetaData(get_engine())
deleted_age = timeutils.utcnow() - datetime.timedelta(days=age_in_days)
tables = []
for model_class in models.__dict__.values():
if not hasattr(model_class, '__tablename__'):
continue
if hasattr(model_class, 'deleted'):
tables.append(model_class.__tablename__)
# get rid of FX constraints
for tbl in ('images', 'tasks'):
try:
tables.remove(tbl)
except ValueError:
LOG.warning(_LW('Expected table %(tbl)s was not found in DB.'),
**locals())
else:
tables.append(tbl)
for tbl in tables:
tab = Table(tbl, metadata, autoload=True)
LOG.info(
_LI('Purging deleted rows older than %(age_in_days)d day(s) '
'from table %(tbl)s'),
**locals()
)
with session.begin():
result = session.execute(
tab.delete().where(
tab.columns.id.in_(
select([tab.columns.id]).where(
tab.columns.deleted_at < deleted_age
).limit(max_rows)
)
)
)
rows = result.rowcount
LOG.info(_LI('Deleted %(rows)d row(s) from table %(tbl)s'),
**locals())
def user_get_storage_usage(context, owner_id, image_id=None, session=None):
_check_image_id(image_id)
session = session or get_session()
total_size = _image_get_disk_usage_by_owner(
owner_id, session, image_id=image_id)
return total_size
def _task_info_format(task_info_ref):
"""Format a task info ref for consumption outside of this module"""
if task_info_ref is None:
return {}
return {
'task_id': task_info_ref['task_id'],
'input': task_info_ref['input'],
'result': task_info_ref['result'],
'message': task_info_ref['message'],
}
def _task_info_create(context, task_id, values, session=None):
"""Create an TaskInfo object"""
session = session or get_session()
task_info_ref = models.TaskInfo()
task_info_ref.task_id = task_id
task_info_ref.update(values)
task_info_ref.save(session=session)
return _task_info_format(task_info_ref)
def _task_info_update(context, task_id, values, session=None):
"""Update an TaskInfo object"""
session = session or get_session()
task_info_ref = _task_info_get(context, task_id, session=session)
if task_info_ref:
task_info_ref.update(values)
task_info_ref.save(session=session)
return _task_info_format(task_info_ref)
def _task_info_get(context, task_id, session=None):
"""Fetch an TaskInfo entity by task_id"""
session = session or get_session()
query = session.query(models.TaskInfo)
query = query.filter_by(task_id=task_id)
try:
task_info_ref = query.one()
except sa_orm.exc.NoResultFound:
LOG.debug("TaskInfo was not found for task with id %(task_id)s",
{'task_id': task_id})
task_info_ref = None
return task_info_ref
def task_create(context, values, session=None):
"""Create a task object"""
values = values.copy()
session = session or get_session()
with session.begin():
task_info_values = _pop_task_info_values(values)
task_ref = models.Task()
_task_update(context, task_ref, values, session=session)
_task_info_create(context,
task_ref.id,
task_info_values,
session=session)
return task_get(context, task_ref.id, session)
def _pop_task_info_values(values):
task_info_values = {}
for k, v in values.items():
if k in ['input', 'result', 'message']:
values.pop(k)
task_info_values[k] = v
return task_info_values
def task_update(context, task_id, values, session=None):
"""Update a task object"""
session = session or get_session()
with session.begin():
task_info_values = _pop_task_info_values(values)
task_ref = _task_get(context, task_id, session)
_drop_protected_attrs(models.Task, values)
values['updated_at'] = timeutils.utcnow()
_task_update(context, task_ref, values, session)
if task_info_values:
_task_info_update(context,
task_id,
task_info_values,
session)
return task_get(context, task_id, session)
def task_get(context, task_id, session=None, force_show_deleted=False):
"""Fetch a task entity by id"""
task_ref = _task_get(context, task_id, session=session,
force_show_deleted=force_show_deleted)
return _task_format(task_ref, task_ref.info)
def task_delete(context, task_id, session=None):
"""Delete a task"""
session = session or get_session()
task_ref = _task_get(context, task_id, session=session)
task_ref.delete(session=session)
return _task_format(task_ref, task_ref.info)
def task_get_all(context, filters=None, marker=None, limit=None,
sort_key='created_at', sort_dir='desc', admin_as_user=False):
"""
Get all tasks that match zero or more filters.
:param filters: dict of filter keys and values.
:param marker: task id after which to start page
:param limit: maximum number of tasks to return
:param sort_key: task attribute by which results should be sorted
:param sort_dir: direction in which results should be sorted (asc, desc)
:param admin_as_user: For backwards compatibility. If true, then return to
an admin the equivalent set of tasks which it would see
if it were a regular user
:returns: tasks set
"""
filters = filters or {}
session = get_session()
query = session.query(models.Task)
if not (context.is_admin or admin_as_user) and context.owner is not None:
query = query.filter(models.Task.owner == context.owner)
showing_deleted = False
if 'deleted' in filters:
deleted_filter = filters.pop('deleted')
query = query.filter_by(deleted=deleted_filter)
showing_deleted = deleted_filter
for (k, v) in filters.items():
if v is not None:
key = k
if hasattr(models.Task, key):
query = query.filter(getattr(models.Task, key) == v)
marker_task = None
if marker is not None:
marker_task = _task_get(context, marker,
force_show_deleted=showing_deleted)
sort_keys = ['created_at', 'id']
if sort_key not in sort_keys:
sort_keys.insert(0, sort_key)
query = _paginate_query(query, models.Task, limit,
sort_keys,
marker=marker_task,
sort_dir=sort_dir)
task_refs = query.all()
tasks = []
for task_ref in task_refs:
tasks.append(_task_format(task_ref, task_info_ref=None))
return tasks
def _is_task_visible(context, task):
"""Return True if the task is visible in this context."""
# Is admin == task visible
if context.is_admin:
return True
# No owner == task visible
if task['owner'] is None:
return True
# Perform tests based on whether we have an owner
if context.owner is not None:
if context.owner == task['owner']:
return True
return False
def _task_get(context, task_id, session=None, force_show_deleted=False):
"""Fetch a task entity by id"""
session = session or get_session()
query = session.query(models.Task).options(
sa_orm.joinedload(models.Task.info)
).filter_by(id=task_id)
if not force_show_deleted and not context.can_see_deleted:
query = query.filter_by(deleted=False)
try:
task_ref = query.one()
except sa_orm.exc.NoResultFound:
LOG.debug("No task found with ID %s", task_id)
raise exception.TaskNotFound(task_id=task_id)
# Make sure the task is visible
if not _is_task_visible(context, task_ref):
msg = "Forbidding request, task %s is not visible" % task_id
LOG.debug(msg)
raise exception.Forbidden(msg)
return task_ref
def _task_update(context, task_ref, values, session=None):
"""Apply supplied dictionary of values to a task object."""
if 'deleted' not in values:
values["deleted"] = False
task_ref.update(values)
task_ref.save(session=session)
return task_ref
def _task_format(task_ref, task_info_ref=None):
"""Format a task ref for consumption outside of this module"""
task_dict = {
'id': task_ref['id'],
'type': task_ref['type'],
'status': task_ref['status'],
'owner': task_ref['owner'],
'expires_at': task_ref['expires_at'],
'created_at': task_ref['created_at'],
'updated_at': task_ref['updated_at'],
'deleted_at': task_ref['deleted_at'],
'deleted': task_ref['deleted']
}
if task_info_ref:
task_info_dict = {
'input': task_info_ref['input'],
'result': task_info_ref['result'],
'message': task_info_ref['message'],
}
task_dict.update(task_info_dict)
return task_dict
def metadef_namespace_get_all(context, marker=None, limit=None, sort_key=None,
sort_dir=None, filters=None, session=None):
"""List all available namespaces."""
session = session or get_session()
namespaces = metadef_namespace_api.get_all(
context, session, marker, limit, sort_key, sort_dir, filters)
return namespaces
def metadef_namespace_get(context, namespace_name, session=None):
"""Get a namespace or raise if it does not exist or is not visible."""
session = session or get_session()
return metadef_namespace_api.get(
context, namespace_name, session)
def metadef_namespace_create(context, values, session=None):
"""Create a namespace or raise if it already exists."""
session = session or get_session()
return metadef_namespace_api.create(context, values, session)
def metadef_namespace_update(context, namespace_id, namespace_dict,
session=None):
"""Update a namespace or raise if it does not exist or not visible"""
session = session or get_session()
return metadef_namespace_api.update(
context, namespace_id, namespace_dict, session)
def metadef_namespace_delete(context, namespace_name, session=None):
"""Delete the namespace and all foreign references"""
session = session or get_session()
return metadef_namespace_api.delete_cascade(
context, namespace_name, session)
def metadef_object_get_all(context, namespace_name, session=None):
"""Get a metadata-schema object or raise if it does not exist."""
session = session or get_session()
return metadef_object_api.get_all(
context, namespace_name, session)
def metadef_object_get(context, namespace_name, object_name, session=None):
"""Get a metadata-schema object or raise if it does not exist."""
session = session or get_session()
return metadef_object_api.get(
context, namespace_name, object_name, session)
def metadef_object_create(context, namespace_name, object_dict,
session=None):
"""Create a metadata-schema object or raise if it already exists."""
session = session or get_session()
return metadef_object_api.create(
context, namespace_name, object_dict, session)
def metadef_object_update(context, namespace_name, object_id, object_dict,
session=None):
"""Update an object or raise if it does not exist or not visible."""
session = session or get_session()
return metadef_object_api.update(
context, namespace_name, object_id, object_dict, session)
def metadef_object_delete(context, namespace_name, object_name,
session=None):
"""Delete an object or raise if namespace or object doesn't exist."""
session = session or get_session()
return metadef_object_api.delete(
context, namespace_name, object_name, session)
def metadef_object_delete_namespace_content(
context, namespace_name, session=None):
"""Delete an object or raise if namespace or object doesn't exist."""
session = session or get_session()
return metadef_object_api.delete_by_namespace_name(
context, namespace_name, session)
def metadef_object_count(context, namespace_name, session=None):
"""Get count of properties for a namespace, raise if ns doesn't exist."""
session = session or get_session()
return metadef_object_api.count(context, namespace_name, session)
def metadef_property_get_all(context, namespace_name, session=None):
"""Get a metadef property or raise if it does not exist."""
session = session or get_session()
return metadef_property_api.get_all(context, namespace_name, session)
def metadef_property_get(context, namespace_name,
property_name, session=None):
"""Get a metadef property or raise if it does not exist."""
session = session or get_session()
return metadef_property_api.get(
context, namespace_name, property_name, session)
def metadef_property_create(context, namespace_name, property_dict,
session=None):
"""Create a metadef property or raise if it already exists."""
session = session or get_session()
return metadef_property_api.create(
context, namespace_name, property_dict, session)
def metadef_property_update(context, namespace_name, property_id,
property_dict, session=None):
"""Update an object or raise if it does not exist or not visible."""
session = session or get_session()
return metadef_property_api.update(
context, namespace_name, property_id, property_dict, session)
def metadef_property_delete(context, namespace_name, property_name,
session=None):
"""Delete a property or raise if it or namespace doesn't exist."""
session = session or get_session()
return metadef_property_api.delete(
context, namespace_name, property_name, session)
def metadef_property_delete_namespace_content(
context, namespace_name, session=None):
"""Delete a property or raise if it or namespace doesn't exist."""
session = session or get_session()
return metadef_property_api.delete_by_namespace_name(
context, namespace_name, session)
def metadef_property_count(context, namespace_name, session=None):
"""Get count of properties for a namespace, raise if ns doesn't exist."""
session = session or get_session()
return metadef_property_api.count(context, namespace_name, session)
def metadef_resource_type_create(context, values, session=None):
"""Create a resource_type"""
session = session or get_session()
return metadef_resource_type_api.create(
context, values, session)
def metadef_resource_type_get(context, resource_type_name, session=None):
"""Get a resource_type"""
session = session or get_session()
return metadef_resource_type_api.get(
context, resource_type_name, session)
def metadef_resource_type_get_all(context, session=None):
"""list all resource_types"""
session = session or get_session()
return metadef_resource_type_api.get_all(context, session)
def metadef_resource_type_delete(context, resource_type_name, session=None):
"""Get a resource_type"""
session = session or get_session()
return metadef_resource_type_api.delete(
context, resource_type_name, session)
def metadef_resource_type_association_get(
context, namespace_name, resource_type_name, session=None):
session = session or get_session()
return metadef_association_api.get(
context, namespace_name, resource_type_name, session)
def metadef_resource_type_association_create(
context, namespace_name, values, session=None):
session = session or get_session()
return metadef_association_api.create(
context, namespace_name, values, session)
def metadef_resource_type_association_delete(
context, namespace_name, resource_type_name, session=None):
session = session or get_session()
return metadef_association_api.delete(
context, namespace_name, resource_type_name, session)
def metadef_resource_type_association_get_all_by_namespace(
context, namespace_name, session=None):
session = session or get_session()
return metadef_association_api.get_all_by_namespace(
context, namespace_name, session)
def metadef_tag_get_all(
context, namespace_name, filters=None, marker=None, limit=None,
sort_key=None, sort_dir=None, session=None):
"""Get metadata-schema tags or raise if none exist."""
session = session or get_session()
return metadef_tag_api.get_all(
context, namespace_name, session,
filters, marker, limit, sort_key, sort_dir)
def metadef_tag_get(context, namespace_name, name, session=None):
"""Get a metadata-schema tag or raise if it does not exist."""
session = session or get_session()
return metadef_tag_api.get(
context, namespace_name, name, session)
def metadef_tag_create(context, namespace_name, tag_dict,
session=None):
"""Create a metadata-schema tag or raise if it already exists."""
session = session or get_session()
return metadef_tag_api.create(
context, namespace_name, tag_dict, session)
def metadef_tag_create_tags(context, namespace_name, tag_list,
session=None):
"""Create a metadata-schema tag or raise if it already exists."""
session = get_session()
return metadef_tag_api.create_tags(
context, namespace_name, tag_list, session)
def metadef_tag_update(context, namespace_name, id, tag_dict,
session=None):
"""Update an tag or raise if it does not exist or not visible."""
session = session or get_session()
return metadef_tag_api.update(
context, namespace_name, id, tag_dict, session)
def metadef_tag_delete(context, namespace_name, name,
session=None):
"""Delete an tag or raise if namespace or tag doesn't exist."""
session = session or get_session()
return metadef_tag_api.delete(
context, namespace_name, name, session)
def metadef_tag_delete_namespace_content(
context, namespace_name, session=None):
"""Delete an tag or raise if namespace or tag doesn't exist."""
session = session or get_session()
return metadef_tag_api.delete_by_namespace_name(
context, namespace_name, session)
def metadef_tag_count(context, namespace_name, session=None):
"""Get count of tags for a namespace, raise if ns doesn't exist."""
session = session or get_session()
return metadef_tag_api.count(context, namespace_name, session)
def artifact_create(context, values, type_name,
type_version=None, session=None):
session = session or get_session()
artifact = glare.create(context, values, session, type_name,
type_version)
return artifact
def artifact_delete(context, artifact_id, type_name,
type_version=None, session=None):
session = session or get_session()
artifact = glare.delete(context, artifact_id, session, type_name,
type_version)
return artifact
def artifact_update(context, values, artifact_id, type_name,
type_version=None, session=None):
session = session or get_session()
artifact = glare.update(context, values, artifact_id, session,
type_name, type_version)
return artifact
def artifact_get(context, artifact_id,
type_name=None,
type_version=None,
show_level=ga.Showlevel.BASIC,
session=None):
session = session or get_session()
return glare.get(context, artifact_id, session, type_name,
type_version, show_level)
def artifact_publish(context,
artifact_id,
type_name,
type_version=None,
session=None):
session = session or get_session()
return glare.publish(context,
artifact_id,
session,
type_name,
type_version)
def artifact_get_all(context, marker=None, limit=None, sort_keys=None,
sort_dirs=None, filters=None,
show_level=ga.Showlevel.NONE, session=None):
session = session or get_session()
return glare.get_all(context, session, marker, limit, sort_keys,
sort_dirs, filters, show_level)
|
Jorge-Rodriguez/ansible
|
refs/heads/devel
|
lib/ansible/plugins/doc_fragments/default_callback.py
|
9
|
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
DOCUMENTATION = """
options:
display_skipped_hosts:
name: Show skipped hosts
description: "Toggle to control displaying skipped task/host results in a task"
default: True
env:
- name: DISPLAY_SKIPPED_HOSTS
ini:
- key: display_skipped_hosts
section: defaults
type: boolean
display_ok_hosts:
name: Show 'ok' hosts
description: "Toggle to control displaying 'ok' task/host results in a task"
default: True
env:
- name: ANSIBLE_DISPLAY_OK_HOSTS
ini:
- key: display_ok_hosts
section: defaults
type: boolean
version_added: '2.7'
display_failed_stderr:
name: Use STDERR for failed and unreachable tasks
description: "Toggle to control whether failed and unreachable tasks are displayed to STDERR (vs. STDOUT)"
default: False
env:
- name: ANSIBLE_DISPLAY_FAILED_STDERR
ini:
- key: display_failed_stderr
section: defaults
type: boolean
version_added: '2.7'
show_custom_stats:
name: Show custom stats
description: 'This adds the custom stats set via the set_stats plugin to the play recap'
default: False
env:
- name: ANSIBLE_SHOW_CUSTOM_STATS
ini:
- key: show_custom_stats
section: defaults
type: bool
"""
|
Petr-Kovalev/nupic-win32
|
refs/heads/master
|
py/nupic/frameworks/opf/exp_generator/opfExperimentControlTemplate.py
|
3
|
control = {
# The environment that the current model is being run in
"environment": $ENVIRONMENT,
# [optional] A sequence of one or more tasks that describe what to do with the
# model. Each task consists of a task label, an input spec., iteration count,
# and a task-control spec per opfTaskSchema.json
#
# NOTE: The tasks are intended for OPF clients that make use of OPFTaskDriver.
# Clients that interact with OPF Model directly do not make use of
# the tasks specification.
#
"tasks":[
{
# Task label; this label string may be used for diagnostic logging and for
# constructing filenames or directory pathnames for task-specific files, etc.
'taskLabel' : "OnlineLearning",
# Input stream specification per py/nupic/frameworks/opf/jsonschema/stream_def.json.
#
'dataset' : $DATASET_SPEC,
# Iteration count: maximum number of iterations. Each iteration corresponds
# to one record from the (possibly aggregated) dataset. The task is
# terminated when either number of iterations reaches iterationCount or
# all records in the (possibly aggregated) database have been processed,
# whichever occurs first.
#
# iterationCount of -1 = iterate over the entire dataset
'iterationCount' : $ITERATION_COUNT,
# Task Control parameters for OPFTaskDriver (per opfTaskControlSchema.json)
'taskControl' : {
# Iteration cycle list consisting of opftaskdriver.IterationPhaseSpecXXXXX
# instances.
'iterationCycle' : [
#IterationPhaseSpecLearnOnly(1000),
IterationPhaseSpecLearnAndInfer(1000),
#IterationPhaseSpecInferOnly(10),
],
# Metrics: A list of MetricSpecs that instantiate the metrics that are
# computed for this experiment
'metrics':[
$METRICS
],
# Logged Metrics: A sequence of regular expressions that specify which of
# the metrics from the Inference Specifications section MUST be logged for
# every prediction. The regex's correspond to the automatically generated
# metric labels. This is similar to the way the optimization metric is
# specified in permutations.py.
'loggedMetrics': $LOGGED_METRICS,
# Callbacks for experimentation/research (optional)
'callbacks' : {
# Callbacks to be called at the beginning of a task, before model iterations.
# Signature: callback(<reference to OPF Model>); returns nothing
'setup' : [],
# Callbacks to be called after every learning/inference iteration
# Signature: callback(<reference to OPF Model>); returns nothing
'postIter' : [],
# Callbacks to be called when the experiment task is finished
# Signature: callback(<reference to OPF Model>); returns nothing
'finish' : []
}
} # End of taskControl
}, # End of task
]
}
|
jtakayama/ics691-setupbooster
|
refs/heads/master
|
makahiki/apps/managers/player_mgr/migrations/0002_auto__add_dailystatus.py
|
7
|
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'DailyStatus'
db.create_table('player_mgr_dailystatus', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('daily_visitors', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)),
('date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal('player_mgr', ['DailyStatus'])
def backwards(self, orm):
# Deleting model 'DailyStatus'
db.delete_table('player_mgr_dailystatus')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 6, 25, 17, 12, 43, 14393)'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 6, 25, 17, 12, 43, 14256)'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'player_mgr.dailystatus': {
'Meta': {'object_name': 'DailyStatus'},
'daily_visitors': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'player_mgr.profile': {
'Meta': {'object_name': 'Profile'},
'completion_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'contact_carrier': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'contact_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'contact_text': ('django.contrib.localflavor.us.models.PhoneNumberField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
'daily_visit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'last_visit_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}),
'referrer_awarded': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'referring_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'referred_profiles'", 'null': 'True', 'to': "orm['auth.User']"}),
'setup_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'setup_profile': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'team': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['team_mgr.Team']", 'null': 'True', 'blank': 'True'}),
'theme': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"})
},
'team_mgr.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True', 'db_index': 'True'})
},
'team_mgr.team': {
'Meta': {'object_name': 'Team'},
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['team_mgr.Group']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '1024', 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True', 'db_index': 'True'})
}
}
complete_apps = ['player_mgr']
|
zer0yu/ZEROScan
|
refs/heads/master
|
thirdparty/colorama/win32.py
|
6
|
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
# from winbase.h
STDOUT = -11
STDERR = -12
try:
import ctypes
from ctypes import LibraryLoader
windll = LibraryLoader(ctypes.WinDLL)
from ctypes import wintypes
except (AttributeError, ImportError):
windll = None
SetConsoleTextAttribute = lambda *_: None
winapi_test = lambda *_: None
else:
from ctypes import byref, Structure, c_char, POINTER
COORD = wintypes._COORD
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
"""struct in wincon.h."""
_fields_ = [
("dwSize", COORD),
("dwCursorPosition", COORD),
("wAttributes", wintypes.WORD),
("srWindow", wintypes.SMALL_RECT),
("dwMaximumWindowSize", COORD),
]
def __str__(self):
return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (
self.dwSize.Y, self.dwSize.X
, self.dwCursorPosition.Y, self.dwCursorPosition.X
, self.wAttributes
, self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right
, self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X
)
_GetStdHandle = windll.kernel32.GetStdHandle
_GetStdHandle.argtypes = [
wintypes.DWORD,
]
_GetStdHandle.restype = wintypes.HANDLE
_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
_GetConsoleScreenBufferInfo.argtypes = [
wintypes.HANDLE,
POINTER(CONSOLE_SCREEN_BUFFER_INFO),
]
_GetConsoleScreenBufferInfo.restype = wintypes.BOOL
_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
_SetConsoleTextAttribute.argtypes = [
wintypes.HANDLE,
wintypes.WORD,
]
_SetConsoleTextAttribute.restype = wintypes.BOOL
_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition
_SetConsoleCursorPosition.argtypes = [
wintypes.HANDLE,
COORD,
]
_SetConsoleCursorPosition.restype = wintypes.BOOL
_FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA
_FillConsoleOutputCharacterA.argtypes = [
wintypes.HANDLE,
c_char,
wintypes.DWORD,
COORD,
POINTER(wintypes.DWORD),
]
_FillConsoleOutputCharacterA.restype = wintypes.BOOL
_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
_FillConsoleOutputAttribute.argtypes = [
wintypes.HANDLE,
wintypes.WORD,
wintypes.DWORD,
COORD,
POINTER(wintypes.DWORD),
]
_FillConsoleOutputAttribute.restype = wintypes.BOOL
_SetConsoleTitleW = windll.kernel32.SetConsoleTitleW
_SetConsoleTitleW.argtypes = [
wintypes.LPCWSTR
]
_SetConsoleTitleW.restype = wintypes.BOOL
handles = {
STDOUT: _GetStdHandle(STDOUT),
STDERR: _GetStdHandle(STDERR),
}
def _winapi_test(handle):
csbi = CONSOLE_SCREEN_BUFFER_INFO()
success = _GetConsoleScreenBufferInfo(
handle, byref(csbi))
return bool(success)
def winapi_test():
return any(_winapi_test(h) for h in handles.values())
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
handle = handles[stream_id]
csbi = CONSOLE_SCREEN_BUFFER_INFO()
success = _GetConsoleScreenBufferInfo(
handle, byref(csbi))
return csbi
def SetConsoleTextAttribute(stream_id, attrs):
handle = handles[stream_id]
return _SetConsoleTextAttribute(handle, attrs)
def SetConsoleCursorPosition(stream_id, position, adjust=True):
position = COORD(*position)
# If the position is out of range, do nothing.
if position.Y <= 0 or position.X <= 0:
return
# Adjust for Windows' SetConsoleCursorPosition:
# 1. being 0-based, while ANSI is 1-based.
# 2. expecting (x,y), while ANSI uses (y,x).
adjusted_position = COORD(position.Y - 1, position.X - 1)
if adjust:
# Adjust for viewport's scroll position
sr = GetConsoleScreenBufferInfo(STDOUT).srWindow
adjusted_position.Y += sr.Top
adjusted_position.X += sr.Left
# Resume normal processing
handle = handles[stream_id]
return _SetConsoleCursorPosition(handle, adjusted_position)
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char.encode())
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
def FillConsoleOutputAttribute(stream_id, attr, length, start):
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
handle = handles[stream_id]
attribute = wintypes.WORD(attr)
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
return _FillConsoleOutputAttribute(
handle, attribute, length, start, byref(num_written))
def SetConsoleTitle(title):
return _SetConsoleTitleW(title)
|
zubair-arbi/edx-platform
|
refs/heads/master
|
openedx/core/djangoapps/content/course_overviews/migrations/0003_add_cert_html_view_enabled.py
|
66
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'CourseOverview.cert_html_view_enabled'
# The default value for the cert_html_view_eanbled column is False.
# However, for courses in the table for which cert_html_view_enabled
# should be True, this would be invalid. So, we must clear the
# table before adding the new column.
db.clear_table('course_overviews_courseoverview')
db.add_column('course_overviews_courseoverview', 'cert_html_view_enabled',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Deleting field 'CourseOverview.cert_html_view_enabled'
db.delete_column('course_overviews_courseoverview', 'cert_html_view_enabled')
models = {
'course_overviews.courseoverview': {
'Meta': {'object_name': 'CourseOverview'},
'_location': ('xmodule_django.models.UsageKeyField', [], {'max_length': '255'}),
'_pre_requisite_courses_json': ('django.db.models.fields.TextField', [], {}),
'advertised_start': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'cert_html_view_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'cert_name_long': ('django.db.models.fields.TextField', [], {}),
'cert_name_short': ('django.db.models.fields.TextField', [], {}),
'certificates_display_behavior': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'certificates_show_before_end': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'course_image_url': ('django.db.models.fields.TextField', [], {}),
'days_early_for_beta': ('django.db.models.fields.FloatField', [], {'null': 'True'}),
'display_name': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'display_number_with_default': ('django.db.models.fields.TextField', [], {}),
'display_org_with_default': ('django.db.models.fields.TextField', [], {}),
'end': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'end_of_course_survey_url': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'facebook_url': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'has_any_active_web_certificate': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'primary_key': 'True', 'db_index': 'True'}),
'lowest_passing_grade': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'}),
'mobile_available': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'social_sharing_url': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'start': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'visible_to_staff_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
}
}
complete_apps = ['course_overviews']
|
mrquim/mrquimrepo
|
refs/heads/master
|
repo/script.skin.helper.service/resources/lib/plugin_content.py
|
4
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
script.skin.helper.service
Helper service and scripts for Kodi skins
plugin_content.py
Hidden plugin entry point providing some helper features
'''
import xbmc
import xbmcplugin
import xbmcgui
import xbmcaddon
from simplecache import SimpleCache
from utils import log_msg, KODI_VERSION, log_exception, urlencode
from metadatautils import KodiDb, Tmdb, get_clean_image, process_method_on_list
import urlparse
import sys
import os
class PluginContent:
'''Hidden plugin entry point providing some helper features'''
params = {}
win = None
def __init__(self):
self.cache = SimpleCache()
self.kodi_db = KodiDb()
self.win = xbmcgui.Window(10000)
try:
self.params = dict(urlparse.parse_qsl(sys.argv[2].replace('?', '').lower().decode("utf-8")))
log_msg("plugin called with parameters: %s" % self.params)
self.main()
except Exception as exc:
log_exception(__name__, exc)
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
# cleanup when done processing
self.close()
def close(self):
'''Cleanup Kodi Cpython instances'''
self.cache.close()
del self.win
def main(self):
'''main action, load correct function'''
action = self.params.get("action", "")
if self.win.getProperty("SkinHelperShutdownRequested"):
# do not proceed if kodi wants to exit
log_msg("%s --> Not forfilling request: Kodi is exiting" % __name__, xbmc.LOGWARNING)
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
else:
try:
if hasattr(self.__class__, action):
# launch module for action provided by this plugin
getattr(self, action)()
else:
# legacy (widget) path called !!!
self.load_widget()
except Exception as exc:
log_exception(__name__, exc)
def load_widget(self):
'''legacy entrypoint called (widgets are moved to seperate addon), start redirect...'''
action = self.params.get("action", "")
newaddon = "script.skin.helper.widgets"
log_msg("Deprecated method: %s. Please reassign your widgets to get rid of this message. -"
"This automatic redirect will be removed in the future" % (action), xbmc.LOGWARNING)
paramstring = ""
for key, value in self.params.iteritems():
paramstring += ",%s=%s" % (key, value)
if xbmc.getCondVisibility("System.HasAddon(%s)" % newaddon):
# TEMP !!! for backwards compatability reasons only - to be removed in the near future!!
import imp
addon = xbmcaddon.Addon(newaddon)
addon_path = addon.getAddonInfo('path').decode("utf-8")
imp.load_source('plugin', os.path.join(addon_path, "plugin.py"))
from plugin import main
main.Main()
del addon
else:
# trigger install of the addon
if KODI_VERSION > 16:
xbmc.executebuiltin("InstallAddon(%s)" % newaddon)
else:
xbmc.executebuiltin("RunPlugin(plugin://%s)" % newaddon)
def playchannel(self):
'''play channel from widget helper'''
params = {"item": {"channelid": int(self.params["channelid"])}}
self.kodi_db.set_json("Player.Open", params)
def playrecording(self):
'''retrieve the recording and play to get resume working'''
recording = self.kodi_db.recording(self.params["recordingid"])
params = {"item": {"recordingid": recording["recordingid"]}}
self.kodi_db.set_json("Player.Open", params)
# manually seek because passing resume to the player json cmd doesn't seem to work
if recording["resume"].get("position"):
for i in range(50):
if xbmc.getCondVisibility("Player.HasVideo"):
break
xbmc.sleep(50)
xbmc.Player().seekTime(recording["resume"].get("position"))
def launch(self):
'''launch any builtin action using a plugin listitem'''
if "runscript" in self.params["path"]:
self.params["path"] = self.params["path"].replace("?", ",")
xbmc.executebuiltin(self.params["path"])
def playalbum(self):
'''helper to play an entire album'''
xbmc.executeJSONRPC(
'{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "albumid": %d } }, "id": 1 }' %
int(self.params["albumid"]))
def smartshortcuts(self):
'''called from skinshortcuts to retrieve listing of all smart shortcuts'''
import skinshortcuts
skinshortcuts.get_smartshortcuts(self.params.get("path", ""))
@staticmethod
def backgrounds():
'''called from skinshortcuts to retrieve listing of all backgrounds'''
import skinshortcuts
skinshortcuts.get_backgrounds()
def widgets(self):
'''called from skinshortcuts to retrieve listing of all widgetss'''
import skinshortcuts
skinshortcuts.get_widgets(self.params.get("path", ""), self.params.get("sublevel", ""))
def resourceimages(self):
'''retrieve listing of specific resource addon images'''
from resourceaddons import get_resourceimages
addontype = self.params.get("addontype", "")
for item in get_resourceimages(addontype, True):
listitem = xbmcgui.ListItem(item[0], label2=item[2], path=item[1], iconImage=item[3])
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
url=item[1], listitem=listitem, isFolder=False)
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
def extrafanart(self):
'''helper to display extrafanart in multiimage control in the skin'''
fanarts = eval(self.params["fanarts"])
# process extrafanarts
for item in fanarts:
listitem = xbmcgui.ListItem(item, path=item)
listitem.setProperty('mimetype', 'image/jpeg')
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=item, listitem=listitem)
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
def genrebackground(self):
'''helper to display images for a specific genre in multiimage control in the skin'''
genre = self.params.get("genre").split(".")[0]
arttype = self.params.get("arttype", "fanart")
randomize = self.params.get("random", "false") == "true"
mediatype = self.params.get("mediatype", "movies")
if genre and genre != "..":
filters = [{"operator": "is", "field": "genre", "value": genre}]
if randomize:
sort = {"method": "random", "order": "descending"}
else:
sort = {"method": "sorttitle", "order": "ascending"}
items = getattr(self.kodi_db, mediatype)(
sort=sort,
filters=filters, limits=(0, 50))
for item in items:
image = get_clean_image(item["art"].get(arttype, ""))
if image:
image = get_clean_image(item["art"][arttype])
listitem = xbmcgui.ListItem(image, path=image)
listitem.setProperty('mimetype', 'image/jpeg')
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=image, listitem=listitem)
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
def getcastmedia(self):
'''helper to display get all media for a specific actor'''
name = self.params.get("name")
if name:
all_items = self.kodi_db.castmedia(name)
all_items = process_method_on_list(self.kodi_db.prepare_listitem, all_items)
all_items = process_method_on_list(self.kodi_db.create_listitem, all_items)
xbmcplugin.addDirectoryItems(int(sys.argv[1]), all_items, len(all_items))
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
def getcast(self):
'''helper to get all cast for a given media item'''
db_id = None
all_cast = []
all_cast_names = list()
cache_str = ""
download_thumbs = self.params.get("downloadthumbs", "") == "true"
extended_cast_action = self.params.get("castaction", "") == "extendedinfo"
tmdb = Tmdb()
movie = self.params.get("movie")
tvshow = self.params.get("tvshow")
episode = self.params.get("episode")
movieset = self.params.get("movieset")
try: # try to parse db_id
if movieset:
cache_str = "movieset.castcache-%s-%s" % (self.params["movieset"], download_thumbs)
db_id = int(movieset)
elif tvshow:
cache_str = "tvshow.castcache-%s-%s" % (self.params["tvshow"], download_thumbs)
db_id = int(tvshow)
elif movie:
cache_str = "movie.castcache-%s-%s" % (self.params["movie"], download_thumbs)
db_id = int(movie)
elif episode:
cache_str = "episode.castcache-%s-%s" % (self.params["episode"], download_thumbs)
db_id = int(episode)
except Exception:
pass
cachedata = self.cache.get(cache_str)
if cachedata:
# get data from cache
all_cast = cachedata
else:
# retrieve data from json api...
if movie and db_id:
all_cast = self.kodi_db.movie(db_id)["cast"]
elif movie and not db_id:
filters = [{"operator": "is", "field": "title", "value": movie}]
result = self.kodi_db.movies(filters=filters)
all_cast = result[0]["cast"] if result else []
elif tvshow and db_id:
all_cast = self.kodi_db.tvshow(db_id)["cast"]
elif tvshow and not db_id:
filters = [{"operator": "is", "field": "title", "value": tvshow}]
result = self.kodi_db.tvshows(filters=filters)
all_cast = result[0]["cast"] if result else []
elif episode and db_id:
all_cast = self.kodi_db.episode(db_id)["cast"]
elif episode and not db_id:
filters = [{"operator": "is", "field": "title", "value": episode}]
result = self.kodi_db.episodes(filters=filters)
all_cast = result[0]["cast"] if result else []
elif movieset:
if not db_id:
for item in self.kodi_db.moviesets():
if item["title"].lower() == movieset.lower():
db_id = item["setid"]
if db_id:
json_result = self.kodi_db.movieset(db_id, include_set_movies_fields=["cast"])
if "movies" in json_result:
for movie in json_result['movies']:
all_cast += movie['cast']
# optional: download missing actor thumbs
if all_cast and download_thumbs:
for cast in all_cast:
if cast.get("thumbnail"):
cast["thumbnail"] = get_clean_image(cast.get("thumbnail"))
if not cast.get("thumbnail"):
artwork = tmdb.get_actor(cast["name"])
cast["thumbnail"] = artwork.get("thumb", "")
# lookup tmdb if item is requested that is not in local db
if not all_cast:
tmdbdetails = {}
if movie and not db_id:
tmdbdetails = tmdb.search_movie(movie)
elif tvshow and not db_id:
tmdbdetails = tmdb.search_tvshow(tvshow)
if tmdbdetails.get("cast"):
all_cast = tmdbdetails["cast"]
# save to cache
self.cache.set(cache_str, all_cast)
# process listing with the results...
for cast in all_cast:
if cast.get("name") not in all_cast_names:
liz = xbmcgui.ListItem(label=cast.get("name"), label2=cast.get("role"),
iconImage=cast.get("thumbnail"))
if extended_cast_action:
url = "RunScript(script.extendedinfo,info=extendedactorinfo,name=%s)" % cast.get("name")
url = "plugin://script.skin.helper.service/?action=launch&path=%s" % url
is_folder = False
else:
url = "RunScript(script.skin.helper.service,action=getcastmedia,name=%s)" % cast.get("name")
url = "plugin://script.skin.helper.service/?action=launch&path=%s" % urlencode(url)
is_folder = False
all_cast_names.append(cast.get("name"))
liz.setThumbnailImage(cast.get("thumbnail"))
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=liz, isFolder=is_folder)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@staticmethod
def alphabet():
'''display an alphabet scrollbar in listings'''
all_letters = []
if xbmc.getInfoLabel("Container.NumItems"):
for i in range(int(xbmc.getInfoLabel("Container.NumItems"))):
all_letters.append(xbmc.getInfoLabel("Listitem(%s).SortLetter" % i).upper())
start_number = ""
for number in ["2", "3", "4", "5", "6", "7", "8", "9"]:
if number in all_letters:
start_number = number
break
for letter in [start_number, "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]:
if letter == start_number:
label = "#"
else:
label = letter
listitem = xbmcgui.ListItem(label=label)
if letter not in all_letters:
lipath = "noop"
listitem.setProperty("NotAvailable", "true")
else:
lipath = "plugin://script.skin.helper.service/?action=alphabetletter&letter=%s" % letter
xbmcplugin.addDirectoryItem(int(sys.argv[1]), lipath, listitem, isFolder=False)
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
def alphabetletter(self):
'''used with the alphabet scrollbar to jump to a letter'''
if KODI_VERSION > 16:
xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=False, listitem=xbmcgui.ListItem())
letter = self.params.get("letter", "").upper()
jumpcmd = ""
if letter in ["A", "B", "C", "2"]:
jumpcmd = "2"
elif letter in ["D", "E", "F", "3"]:
jumpcmd = "3"
elif letter in ["G", "H", "I", "4"]:
jumpcmd = "4"
elif letter in ["J", "K", "L", "5"]:
jumpcmd = "5"
elif letter in ["M", "N", "O", "6"]:
jumpcmd = "6"
elif letter in ["P", "Q", "R", "S", "7"]:
jumpcmd = "7"
elif letter in ["T", "U", "V", "8"]:
jumpcmd = "8"
elif letter in ["W", "X", "Y", "Z", "9"]:
jumpcmd = "9"
if jumpcmd:
xbmc.executebuiltin("SetFocus(50)")
for i in range(40):
xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Input.ExecuteAction",\
"params": { "action": "jumpsms%s" }, "id": 1 }' % (jumpcmd))
xbmc.sleep(50)
if xbmc.getInfoLabel("ListItem.Sortletter").upper() == letter:
break
|
Distrotech/scons
|
refs/heads/distrotech-scons
|
test/spaces.py
|
4
|
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import TestSCons
import sys
import os
test = TestSCons.TestSCons()
if sys.platform == 'win32':
test.write('duplicate a file.bat', 'copy foo.in foo.out\n')
copy = test.workpath('duplicate a file.bat')
else:
test.write('duplicate a file.sh', 'cp foo.in foo.out\n')
copy = test.workpath('duplicate a file.sh')
os.chmod(test.workpath('duplicate a file.sh'), 0777)
test.write('SConstruct', r'''
env=Environment()
env.Command("foo.out", "foo.in", [[r"%s", "$SOURCE", "$TARGET"]])
'''%copy)
test.write('foo.in', 'foo.in 1 \n')
test.run(arguments='foo.out')
test.write('SConstruct', r'''
env=Environment()
env["COPY"] = File(r"%s")
env["ENV"]
env.Command("foo.out", "foo.in", [["./$COPY", "$SOURCE", "$TARGET"]])
'''%copy)
test.write('foo.in', 'foo.in 2 \n')
test.run(arguments='foo.out')
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
gangadhar-kadam/verve_live_erp
|
refs/heads/v5.0
|
erpnext/contacts/doctype/party_type/__init__.py
|
12133432
| |
willingc/oh-mainline
|
refs/heads/master
|
vendor/packages/gdata/tests/__init__.py
|
12133432
| |
gabrielfalcao/lettuce
|
refs/heads/master
|
tests/integration/lib/Django-1.3/django/contrib/localflavor/pe/__init__.py
|
12133432
| |
shakamunyi/sahara
|
refs/heads/master
|
sahara/tests/unit/plugins/storm/__init__.py
|
12133432
| |
stevenewey/django
|
refs/heads/master
|
django/conf/locale/ka/__init__.py
|
12133432
| |
dsm054/pandas
|
refs/heads/master
|
pandas/tests/groupby/aggregate/test_aggregate.py
|
1
|
# -*- coding: utf-8 -*-
"""
test .agg behavior / note that .apply is tested generally in test_groupby.py
"""
import pytest
import numpy as np
import pandas as pd
from pandas import concat, DataFrame, Index, MultiIndex, Series
from pandas.core.groupby.grouper import Grouping
from pandas.core.base import SpecificationError
from pandas.compat import OrderedDict
import pandas.util.testing as tm
def test_agg_regression1(tsframe):
grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_agg_must_agg(df):
grouped = df.groupby('A')['C']
msg = "Must produce aggregated value"
with pytest.raises(Exception, match=msg):
grouped.agg(lambda x: x.describe())
with pytest.raises(Exception, match=msg):
grouped.agg(lambda x: x.index[:2])
def test_agg_ser_multi_key(df):
# TODO(wesm): unused
ser = df.C # noqa
f = lambda x: x.sum()
results = df.C.groupby([df.A, df.B]).aggregate(f)
expected = df.groupby(['A', 'B']).sum()['C']
tm.assert_series_equal(results, expected)
def test_groupby_aggregation_mixed_dtype():
# GH 6212
expected = DataFrame({
'v1': [5, 5, 7, np.nan, 3, 3, 4, 1],
'v2': [55, 55, 77, np.nan, 33, 33, 44, 11]},
index=MultiIndex.from_tuples([(1, 95), (1, 99), (2, 95), (2, 99),
('big', 'damp'),
('blue', 'dry'),
('red', 'red'), ('red', 'wet')],
names=['by1', 'by2']))
df = DataFrame({
'v1': [1, 3, 5, 7, 8, 3, 5, np.nan, 4, 5, 7, 9],
'v2': [11, 33, 55, 77, 88, 33, 55, np.nan, 44, 55, 77, 99],
'by1': ["red", "blue", 1, 2, np.nan, "big", 1, 2, "red", 1, np.nan,
12],
'by2': ["wet", "dry", 99, 95, np.nan, "damp", 95, 99, "red", 99,
np.nan, np.nan]
})
g = df.groupby(['by1', 'by2'])
result = g[['v1', 'v2']].mean()
tm.assert_frame_equal(result, expected)
def test_agg_apply_corner(ts, tsframe):
# nothing to group, all NA
grouped = ts.groupby(ts * np.nan)
assert ts.dtype == np.float64
# groupby float64 values results in Float64Index
exp = Series([], dtype=np.float64,
index=pd.Index([], dtype=np.float64))
tm.assert_series_equal(grouped.sum(), exp)
tm.assert_series_equal(grouped.agg(np.sum), exp)
tm.assert_series_equal(grouped.apply(np.sum), exp,
check_index_type=False)
# DataFrame
grouped = tsframe.groupby(tsframe['A'] * np.nan)
exp_df = DataFrame(columns=tsframe.columns, dtype=float,
index=pd.Index([], dtype=np.float64))
tm.assert_frame_equal(grouped.sum(), exp_df, check_names=False)
tm.assert_frame_equal(grouped.agg(np.sum), exp_df, check_names=False)
tm.assert_frame_equal(grouped.apply(np.sum), exp_df.iloc[:, :0],
check_names=False)
def test_agg_grouping_is_list_tuple(ts):
df = tm.makeTimeDataFrame()
grouped = df.groupby(lambda x: x.year)
grouper = grouped.grouper.groupings[0].grouper
grouped.grouper.groupings[0] = Grouping(ts.index, list(grouper))
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
grouped.grouper.groupings[0] = Grouping(ts.index, tuple(grouper))
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_agg_python_multiindex(mframe):
grouped = mframe.groupby(['A', 'B'])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize('groupbyfunc', [
lambda x: x.weekday(),
[lambda x: x.month, lambda x: x.weekday()],
])
def test_aggregate_str_func(tsframe, groupbyfunc):
grouped = tsframe.groupby(groupbyfunc)
# single series
result = grouped['A'].agg('std')
expected = grouped['A'].std()
tm.assert_series_equal(result, expected)
# group frame by function name
result = grouped.aggregate('var')
expected = grouped.var()
tm.assert_frame_equal(result, expected)
# group frame by function dict
result = grouped.agg(OrderedDict([['A', 'var'],
['B', 'std'],
['C', 'mean'],
['D', 'sem']]))
expected = DataFrame(OrderedDict([['A', grouped['A'].var()],
['B', grouped['B'].std()],
['C', grouped['C'].mean()],
['D', grouped['D'].sem()]]))
tm.assert_frame_equal(result, expected)
def test_aggregate_item_by_item(df):
grouped = df.groupby('A')
aggfun = lambda ser: ser.size
result = grouped.agg(aggfun)
foo = (df.A == 'foo').sum()
bar = (df.A == 'bar').sum()
K = len(result.columns)
# GH5782
# odd comparisons can result here, so cast to make easy
exp = pd.Series(np.array([foo] * K), index=list('BCD'),
dtype=np.float64, name='foo')
tm.assert_series_equal(result.xs('foo'), exp)
exp = pd.Series(np.array([bar] * K), index=list('BCD'),
dtype=np.float64, name='bar')
tm.assert_almost_equal(result.xs('bar'), exp)
def aggfun(ser):
return ser.size
result = DataFrame().groupby(df.A).agg(aggfun)
assert isinstance(result, DataFrame)
assert len(result) == 0
def test_wrap_agg_out(three_group):
grouped = three_group.groupby(['A', 'B'])
def func(ser):
if ser.dtype == np.object:
raise TypeError
else:
return ser.sum()
result = grouped.aggregate(func)
exp_grouped = three_group.loc[:, three_group.columns != 'C']
expected = exp_grouped.groupby(['A', 'B']).aggregate(func)
tm.assert_frame_equal(result, expected)
def test_agg_multiple_functions_maintain_order(df):
# GH #610
funcs = [('mean', np.mean), ('max', np.max), ('min', np.min)]
result = df.groupby('A')['C'].agg(funcs)
exp_cols = Index(['mean', 'max', 'min'])
tm.assert_index_equal(result.columns, exp_cols)
def test_multiple_functions_tuples_and_non_tuples(df):
# #1359
funcs = [('foo', 'mean'), 'std']
ex_funcs = [('foo', 'mean'), ('std', 'std')]
result = df.groupby('A')['C'].agg(funcs)
expected = df.groupby('A')['C'].agg(ex_funcs)
tm.assert_frame_equal(result, expected)
result = df.groupby('A').agg(funcs)
expected = df.groupby('A').agg(ex_funcs)
tm.assert_frame_equal(result, expected)
def test_agg_multiple_functions_too_many_lambdas(df):
grouped = df.groupby('A')
funcs = ['mean', lambda x: x.mean(), lambda x: x.std()]
msg = 'Function names must be unique, found multiple named <lambda>'
with pytest.raises(SpecificationError, match=msg):
grouped.agg(funcs)
def test_more_flexible_frame_multi_function(df):
grouped = df.groupby('A')
exmean = grouped.agg(OrderedDict([['C', np.mean], ['D', np.mean]]))
exstd = grouped.agg(OrderedDict([['C', np.std], ['D', np.std]]))
expected = concat([exmean, exstd], keys=['mean', 'std'], axis=1)
expected = expected.swaplevel(0, 1, axis=1).sort_index(level=0, axis=1)
d = OrderedDict([['C', [np.mean, np.std]], ['D', [np.mean, np.std]]])
result = grouped.aggregate(d)
tm.assert_frame_equal(result, expected)
# be careful
result = grouped.aggregate(OrderedDict([['C', np.mean],
['D', [np.mean, np.std]]]))
expected = grouped.aggregate(OrderedDict([['C', np.mean],
['D', [np.mean, np.std]]]))
tm.assert_frame_equal(result, expected)
def foo(x):
return np.mean(x)
def bar(x):
return np.std(x, ddof=1)
# this uses column selection & renaming
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
d = OrderedDict([['C', np.mean],
['D', OrderedDict([['foo', np.mean],
['bar', np.std]])]])
result = grouped.aggregate(d)
d = OrderedDict([['C', [np.mean]], ['D', [foo, bar]]])
expected = grouped.aggregate(d)
tm.assert_frame_equal(result, expected)
def test_multi_function_flexible_mix(df):
# GH #1268
grouped = df.groupby('A')
# Expected
d = OrderedDict([['C', OrderedDict([['foo', 'mean'], ['bar', 'std']])],
['D', {'sum': 'sum'}]])
# this uses column selection & renaming
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
expected = grouped.aggregate(d)
# Test 1
d = OrderedDict([['C', OrderedDict([['foo', 'mean'], ['bar', 'std']])],
['D', 'sum']])
# this uses column selection & renaming
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = grouped.aggregate(d)
tm.assert_frame_equal(result, expected)
# Test 2
d = OrderedDict([['C', OrderedDict([['foo', 'mean'], ['bar', 'std']])],
['D', ['sum']]])
# this uses column selection & renaming
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = grouped.aggregate(d)
tm.assert_frame_equal(result, expected)
|
sameerparekh/pants
|
refs/heads/master
|
src/python/pants/backend/android/tasks/dx_compile.py
|
9
|
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pants.backend.android.targets.android_binary import AndroidBinary
from pants.backend.android.tasks.android_task import AndroidTask
from pants.backend.jvm.tasks.nailgun_task import NailgunTask
from pants.backend.jvm.tasks.unpack_jars import UnpackJars
from pants.base.exceptions import TaskError
class DxCompile(AndroidTask, NailgunTask):
"""
Compile java classes into dex files, Dalvik executables, for AndroidBinary targets.
Gather the class files of the AndroidBinary and all of its dependencies. This includes the
AndroidLibrary targets that the AndroidBinary depends on. AndroidLibrary artifacts (.jars and
.aars) were unpacked during the UnpackLibraries task. The DxCompile task will gather all
those classes and compile them into a dex file. When gathering the classes, the DxCompile
task will filter unpacked AndroidLibraries in order to honor any include/exclude patterns.
This task will silently skip any duplicate class files but will raise a
DuplicateClassFileException if it detects a version conflict in any AndroidLibrary artifacts.
"""
class DuplicateClassFileException(TaskError):
"""Raise is raised when multiple copies of the same class are being added to dex file."""
class EmptyDexError(TaskError):
"""Raise when no classes are found to be packed into the dex file."""
# Name of output file. "Output name must end with one of: .dex .jar .zip .apk or be a directory."
DEX_NAME = 'classes.dex'
@staticmethod
def is_android_binary(target):
"""Return True if target has class files to be compiled into dex."""
return isinstance(target, AndroidBinary)
@classmethod
def register_options(cls, register):
super(DxCompile, cls).register_options(register)
register('--build-tools-version',
help='Create the dex file using this version of the Android build tools.')
register('--jvm-options', action='append', metavar='<option>...',
help='Run dx with these JVM options.')
@classmethod
def product_types(cls):
return ['dex']
@classmethod
def prepare(cls, options, round_manager):
super(DxCompile, cls).prepare(options, round_manager)
round_manager.require_data('classes_by_target')
round_manager.require_data('unpacked_libraries')
def __init__(self, *args, **kwargs):
super(DxCompile, self).__init__(*args, **kwargs)
self._forced_build_tools = self.get_options().build_tools_version
self._forced_jvm_options = self.get_options().jvm_options
@property
def cache_target_dirs(self):
return True
def _render_args(self, outdir, classes):
dex_file = os.path.join(outdir, self.DEX_NAME)
args = []
# Glossary of dx.jar flags.
# : '--dex' to create a Dalvik executable.
# : '--no-strict' allows the dx.jar to skip verifying the package path. This allows us to
# pass a list of classes as opposed to a top-level dir.
# : '--output' tells the dx.jar where to put and what to name the created file.
# See comment on self.classes_dex for restrictions.
args.extend(['--dex', '--no-strict', '--output={0}'.format(dex_file)])
args.extend(classes)
return args
def _compile_dex(self, args, build_tools_version):
classpath = [self.dx_jar_tool(build_tools_version)]
# TODO(mateor) Declare a task_subsystems dependency on JVM and use that to get options.
jvm_options = self._forced_jvm_options if self._forced_jvm_options else None
java_main = 'com.android.dx.command.Main'
return self.runjava(classpath=classpath, jvm_options=jvm_options, main=java_main,
args=args, workunit_name='dx')
def _filter_unpacked_dir(self, target, unpacked_dir, class_files):
# The Dx tool returns failure if more than one copy of a class is packed into the dex file and
# it is easy to fetch duplicate libraries (as well as conflicting versions) from the SDK repos.
# This filters the contents of the unpacked_dir against the include/exclude patterns of the
# target, then compares the filtered files against previously gathered class_files to
# dedupe and detect version conflicts.
file_filter = UnpackJars.get_unpack_filter(target)
for root, _, file_names in os.walk(unpacked_dir):
for filename in file_names:
# Calculate the filename relative to the unpacked_dir and then filter.
relative_dir = os.path.relpath(root, unpacked_dir)
class_file = os.path.join(relative_dir, filename)
if file_filter(class_file):
class_location = os.path.join(root, filename)
# If the class_file (e.g. 'a/b/c/Hello.class') has already been added, then compare the
# full path. If the full path is identical then we can ignore it as a duplicate. If
# the path is different, that means that there is probably conflicting version
# numbers amongst the library deps and so we raise an exception.
if class_file in class_files:
if class_files[class_file] != class_location:
raise TaskError("Dependency:\n{}\n\nConflicts\n1: {} "
"\n2: {}".format(target, class_location, class_files[class_file]))
class_files[class_file] = class_location
return class_files.values()
def _gather_classes(self, target):
# Gather relevant classes from a walk of AndroidBinary's dependency graph.
classes_by_target = self.context.products.get_data('classes_by_target')
unpacked_archives = self.context.products.get('unpacked_libraries')
gathered_classes = set()
class_files = {}
def get_classes(tgt):
# Classes allowed to be None for testing ease - TODO(mateor) update tests to not require this.
target_classes = classes_by_target.get(tgt) if classes_by_target else None
if target_classes:
for _, products in target_classes.abs_paths():
gathered_classes.update(products)
# Gather classes from the contents of unpacked libraries.
unpacked = unpacked_archives.get(tgt)
if unpacked:
# If there are unpacked_archives then we know this target is an AndroidLibrary.
for archives in unpacked.values():
for unpacked_dir in archives:
try:
gathered_classes.update(self._filter_unpacked_dir(tgt, unpacked_dir, class_files))
except TaskError as e:
raise self.DuplicateClassFileException(
"Attempted to add duplicate class files from separate libraries into dex file! "
"This likely indicates a version conflict in the target's dependencies.\n"
"\nTarget:\n{}\n{}".format(target, e))
target.walk(get_classes)
return gathered_classes
def execute(self):
targets = self.context.targets(self.is_android_binary)
with self.invalidated(targets) as invalidation_check:
for vt in invalidation_check.all_vts:
if not vt.valid:
classes = self._gather_classes(vt.target)
if not classes:
raise self.EmptyDexError("No classes were found for {}.".format(vt.target))
args = self._render_args(vt.results_dir, classes)
self._compile_dex(args, vt.target.build_tools_version)
self.context.products.get('dex').add(vt.target, vt.results_dir).append(self.DEX_NAME)
def dx_jar_tool(self, build_tools_version):
"""Return the appropriate dx.jar.
:param string build_tools_version: The Android build-tools version number (e.g. '19.1.0').
"""
build_tools = self._forced_build_tools if self._forced_build_tools else build_tools_version
dx_jar = os.path.join('build-tools', build_tools, 'lib', 'dx.jar')
return self.android_sdk.register_android_tool(dx_jar)
|
benwaa/iPhotoCloudSync
|
refs/heads/master
|
lib/python2.7/tilutil/imageutils.py
|
1
|
'''Helpers to use with images files
@author: tsporkert@gmail.com
'''
# Copyright 2010 Google 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 logging
import os
import re
import shutil
import sys
import tilutil.systemutils as su
import unicodedata
# ImageMagick "convert" tool. Obsolete - should use _SIPS_TOOL only.
CONVERT_TOOL = "convert"
# Image processing tool
_SIPS_TOOL = u"sips"
# TODO: make this list configurable, or better, eliminate the need for it.
_IGNORE_LIST = ("pspbrwse.jbf", "thumbs.db", "desktop.ini",
"ipod photo cache", "picasa.ini",
"feed.rss", "view online.url",
"albumdata.xml", "albumdata2.xml", "pkginfo", "imovie data",
"dir.data", "iphoto.ipspot", "iphotolock.data", "library.data",
"library.iphoto", "library6.iphoto", "caches")
class _NullHandler(logging.Handler):
"""A logging handler that doesn't emit anything."""
def emit(self, record):
pass
_logger = logging.getLogger("google.imageutils")
_logger.addHandler(_NullHandler())
def check_convert():
"""Tests if ImageMagick convert tool is available. Prints error message
to sys.stderr if there is a problem."""
found_it = False
try:
output = su.execandcombine([CONVERT_TOOL, "-version" ])
if output.find("ImageMagick") >= 0:
found_it = True
except StandardError:
pass
if not found_it:
print >> sys.stderr, """Cannot execute "%s".
Make sure you have ImageMagick installed. You can download a copy
from http://www.imagemagick.org/script/index.php
""" % (CONVERT_TOOL)
return False
return True
def should_create(options):
"""Returns True if a create should be performed, based on options. Does not
check options.dryrun."""
if not options.max_create:
print 'Item not created because create limit has been reached.'
return False
if options.max_create != -1:
options.max_create -= 1
return True
def should_delete(options):
"""Returns True if a delete should be performed, based on options. Does not
check options.dryrun."""
if not options.delete:
if not options.dryrun:
print 'Invoke phoshare with the -d option to delete this item.'
return False
if not options.max_delete:
print 'Item not deleted because delete limit has been reached.'
return False
if options.max_delete != -1:
options.max_delete -= 1
return True
def should_update(options):
"""Returns True if an update should be performed, based on options. Does not
check options.dryrun."""
if not options.update:
if not options.dryrun:
print 'Invoke phoshare with the -u option to update this item.'
return False
if not options.max_update:
print 'Item not updated because update limit has been reached.'
return False
if options.max_update != -1:
options.max_update -= 1
return True
def is_ignore(file_name):
"""returns True if the file name is in a list of names to ignore."""
if file_name.startswith("."):
if file_name == ".picasaoriginals":
return False
return True
name = file_name.lower()
return name in _IGNORE_LIST
def make_foldername(name):
"""Returns a valid folder name by replacing problematic characters."""
result = u''
for c in name.strip():
if c.isdigit() or c.isalpha() or c in (',', ' ', '.', '-', '/'):
result += c
elif c == ':':
result += "."
else:
result += '_'
return result
def make_image_filename(name):
"""Returns a valid file name by replacing problematic characters."""
result = u''
for c in name:
if c.isalnum() or c.isspace() or c == '_':
result += c
elif c == ":":
result += '.'
elif c == "/" or c == '-':
result += '-'
else:
result += ' '
return unicodedata.normalize("NFC", result)
def is_image_file(file_name):
"""Tests if the file (name or full path) is an image file."""
return su.getfileextension(file_name) in ("jpg", "jpeg", "tif", "png",
"psd", "nef", "dng", "cr2")
def is_sharable_image_file(file_name):
"""Tests if the file (name or full path) is an image file in a format suitable for sharing."""
return su.getfileextension(file_name) in ("jpg", "jpeg", "tif", "png")
def is_movie_file(file_name):
"""Tests if the file (name or full path) is a movie file."""
return su.getfileextension(file_name) in ("mov", "avi", "m4v", "mpg", "3pg")
def is_media_file(file_name):
"""Tests if the file (name or full path) is either an image or a movie file
"""
return is_image_file(file_name) or is_movie_file(file_name)
def _get_integer(value):
"""Converts a string into an integer.
Args:
value: string to convert.
Returns:
value converted into an integer, or 0 if conversion is not possible.
"""
try:
return int(value)
except ValueError:
return 0
def get_image_width_height(file_name):
"""Gets the width and height of an image file.
Args:
file_name: path to image file.
Returns:
Tuple with image width and height, or (0, 0) if dimensions could not be
determined.
"""
result = su.execandcapture([_SIPS_TOOL, '-g', 'pixelWidth',
'-g', 'pixelHeight', file_name])
height = 0
width = 0
for line in result:
if line.startswith('pixelHeight:'):
height = _get_integer(line[13:])
elif line.startswith('pixelWidth:'):
width = _get_integer(line[12:])
return (width, height)
def resize_image(source, output, height_width_max, out_format='jpeg',
enlarge=False):
"""Converts an image to a new format and resizes it.
Args:
source: path to inputimage file.
output: path to output image file.
height_width_max: resize image so height and width aren't greater
than this value.
out_format: output file format (like "jpeg")
enlarge: if set, enlarge images that are smaller than height_width_max.
Returns:
Output from running "sips" command if it failed, None on success.
"""
# To use ImageMagick:
#result = su.execandcombine(
# [imageutils.CONVERT_TOOL, source, '-delete', '1--1', '-quality', '90%',
# '-resize', "%dx%d^" % (height_width_max, height_width_max),output])
out_height_width_max = 0
if enlarge:
out_height_width_max = height_width_max
else:
(width, height) = get_image_width_height(source)
if height > height_width_max or width > height_width_max:
out_height_width_max = height_width_max
args = [_SIPS_TOOL, '-s', 'format', out_format]
if out_height_width_max:
args.extend(['--resampleHeightWidthMax', '%d' % (out_height_width_max)])
# TODO(tilmansp): This has problems with non-ASCII output folders.
args.extend([source, '--out', output])
result = su.fsdec(su.execandcombine(args))
if result.find('Error') != -1 or result.find('Warning') != -1 or result.find('Trace') != -1:
return result
return None
def compare_keywords(new_keywords, old_keywords):
"""Compares two lists of keywords, and returns True if they are the same.
Args:
new_keywords: first list of keywords
old_keywords: second list of keywords
Returns:
True if the two lists contain the same keywords, ignoring trailing
and leading whitespace, and order.
"""
if new_keywords == None:
new_keywords = []
if old_keywords == None:
old_keywords = []
if len(new_keywords) != len(old_keywords):
return False
new_sorted = sorted([k.strip() for k in new_keywords])
old_sorted = sorted([k.strip() for k in old_keywords])
return new_sorted == old_sorted
class GpsLocation(object):
"""Tracks a Gps location (without altitude), as latitude and longitude.
"""
# How much rounding "error" do we allow for two GPS coordinates
# to be considered identical.
_MIN_GPS_DIFF = 0.0001
def __init__(self, latitude=0.0, longitude=0.0):
"""Constructs a GpsLocation object."""
self.latitude = latitude
self.longitude = longitude
def from_gdata_point(self, point):
"""Sets location from a Point.
Args:
point: gdata.geo.Point
Returns:
this location.
"""
if point and point.pos and point.pos.text:
pos = point.pos.text.split(' ')
self.latitude = float(pos[0])
self.longitude = float(pos[1])
else:
self.latitude = 0.0
self.longitude = 0.0
return self
def from_composite(self, latitude, longitude):
"""Sets location from a latitude and longitude in
"37.642567 N" format.
Args:
latitude: latitude like "37.645267 N"
longitude: longitude like "122.419373 W"
Returns:
this location.
"""
lat_split = latitude.split(' ', 1)
self.latitude = float(lat_split[0])
if len(lat_split) > 1 and 'S' == lat_split[1]:
self.latitude = -self.latitude
long_split = longitude.split(' ', 1)
self.longitude = float(long_split[0])
if len(long_split) > 1 and 'W' == long_split[1]:
self.longitude = -self.longitude
return self
def latitude_ref(self):
"""Returns the latitude suffix as either 'N' or 'S'."""
return 'N' if self.latitude >= 0.0 else 'S'
def longitude_ref(self):
"""Returns the longitude suffix as either 'E' or 'W'."""
return 'E' if self.longitude >= 0.0 else 'W'
def is_same(self, other):
"""Tests if two GpsData locations are equal with regards to GPS accuracy
(6 decimal digits)
Args:
other: the GpsLocation to compare against.
Returns: True if the two locatoins are the same.
"""
return (abs(self.latitude - other.latitude) <= self._MIN_GPS_DIFF and
abs(self.longitude - other.longitude) <= self._MIN_GPS_DIFF)
def to_string(self):
"""Returns the location as a string in (37.645267, -11.419373) format.
"""
return '(%.6f, %.6f)' % (self.latitude, self.longitude)
_CAPTION_PATTERN_INDEX = re.compile(
r'([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9]) (.*) - [0-9]+')
_CAPTION_PATTERN = re.compile(
r'([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9]) (.*)')
def check_faces_in_caption(photo):
"""Checks if all faces are mentioned in the caption."""
comment = photo.comment
if photo.getfaces() and not comment:
return False
for face in photo.getfaces():
parts = face.split(" ")
# Look for the full name or just the first name.
if (comment.find(face) == -1 and
(len(parts) <= 1 or comment.find(parts[0]) == -1)):
return False
return True
# Obsolete
def get_faces_left_to_right(photo):
"""Return a list of face names, sorted by appearance in the image from left to right."""
faces = photo.getfaces()
names = {}
for i in xrange(len(faces)):
x = photo.face_rectangles[i][0]
while names.has_key(x):
x += 0.00001
names[x] = faces[i]
return [names[x] for x in sorted(names.keys())]
def get_photo_caption(photo, container, caption_template):
"""Gets the caption for a IPhotoImage photo, using a template. Supports:
{caption} - the iPhoto caption (title).
{description} - the iPhoto comment.
{dated_caption_description} - the caption and comments from an
IPhotoImage combined into a single string, nicely formatted like
YYYY/MM/DD title: description.
{folder_description} - the iPhoto comment from the enclosing event, folder, or album
Args:
photo - an IPhotoImage photo.
caption_template - a format string.
"""
nodate_title_description = photo.caption
match = re.match(_CAPTION_PATTERN_INDEX, photo.caption)
if not match:
match = re.match(_CAPTION_PATTERN, photo.caption)
else:
# Strip off trailing index
nodate_title_description = '%s%s%s %s' % (
match.group(1), match.group(2), match.group(3), match.group(4))
if match:
# Strip of leading date
nodate_title_description = nodate_title_description[8:].strip()
title_description = photo.caption
if photo.comment:
title_description += ': ' + photo.comment
nodate_title_description += ': ' + photo.comment
folder_description = container.getcommentwithouthints().strip()
if photo.date:
year = str(photo.date.year)
month = str(photo.date.month).zfill(2)
day = str(photo.date.day).zfill(2)
else:
year = ''
month = ''
day = ''
names = photo.getfaces()
if names:
face_list = '(%s)' % (', '.join(names))
else:
face_list = ''
if check_faces_in_caption(photo):
opt_face_list = ''
else:
opt_face_list = '(%s)' % (', '.join(photo.getfaces()))
try:
return caption_template.format(
title=photo.caption,
description=photo.comment,
title_description=title_description,
nodate_title_description=nodate_title_description,
folder_description=folder_description,
yyyy=year,
mm=month,
dd=day,
face_list=face_list,
opt_face_list=opt_face_list).strip()
except KeyError, ex:
su.pout(u'Unrecognized field in caption template: %s. Use one of: title, description, '
'title_description, yyyy, mm, dd.' % (str(ex)))
return caption_template
_YEAR_PATTERN_INDEX = re.compile(r'([0-9][0-9][0-9][0-9]) (.*)')
def format_album_name(album, name, folder_template):
"""Formats a folder name using a template.
Args:
album - an IPhotoContainer.
name - name of the album (typically from album.album_name)
folder_template - a format string.
"""
if name is None:
name = ''
ascii_name = name.encode('ascii', 'replace')
plain_name = ascii_name.replace(' ', '')
nodate_name = name
match = re.match(_YEAR_PATTERN_INDEX, name)
if match:
nodate_name = match.group(2)
if album.date:
year = str(album.date.year)
month = str(album.date.month).zfill(2)
day = str(album.date.day).zfill(2)
else:
year = ''
month = ''
day = ''
folderhint = album.getfolderhint()
if not folderhint:
folderhint = ''
try:
return folder_template.format(
album=name,
name=name,
ascii_name=ascii_name,
plain_name=plain_name,
nodate_album=nodate_name,
hint=folderhint,
yyyy=year,
mm=month,
dd=day)
except KeyError, ex:
su.pout(u'Unrecognized field in folder template: %s. Use one of: name, ascii_name, '
'plain_name, hint, yyyy, mm, dd.' % (str(ex)))
return folder_template
def format_photo_name(photo, album_name, index, padded_index,
name_template):
"""Formats an image name based on a template."""
# default image caption filenames have the file extension on them
# already, so remove it or the export filename will look like
# "IMG 0087 JPG.jpg"
orig_basename = re.sub(
re.compile(r'\.(jpeg|jpg|mpg|mpeg|mov|png|tif|tiff)$',
re.IGNORECASE), '', photo.caption)
if photo.date:
year = str(photo.date.year)
month = str(photo.date.month).zfill(2)
day = str(photo.date.day).zfill(2)
else:
year = ''
month = ''
day = ''
nodate_album_name = album_name
match = re.match(_YEAR_PATTERN_INDEX, nodate_album_name)
if match:
nodate_album_name = match.group(2)
nodate_event_name = photo.event_name
match = re.match(_YEAR_PATTERN_INDEX, nodate_event_name)
if match:
nodate_event_name = match.group(2)
ascii_title = orig_basename.encode('ascii', 'replace')
plain_title = ascii_title.replace(' ', '')
ascii_album_name = album_name.encode('ascii', 'replace')
plain_album_name = ascii_album_name.replace(' ', '')
ascii_event = photo.event_name.encode('ascii', 'replace')
plain_event = ascii_event.replace(' ', '')
try:
formatted_name = name_template.format(index=index,
index0=padded_index,
event_index=photo.event_index,
event_index0=photo.event_index0,
album=album_name,
ascii_album=ascii_album_name,
plain_album=plain_album_name,
event=photo.event_name,
ascii_event=ascii_event,
plain_event=plain_event,
nodate_album=nodate_album_name,
nodate_event=nodate_event_name,
title=orig_basename,
caption=orig_basename, # backward compatibility
ascii_title=ascii_title,
plain_title=plain_title,
yyyy=year,
mm=month,
dd=day)
except KeyError, ex:
su.pout(u'Unrecognized field in name template: %s. Use one of: index, index0, event_index, '
'event_index0, album, ascii_album, event, ascii_event, title, ascii_title, '
'yyyy, mm, or dd.' % (str(ex)))
formatted_name = name_template
# Take out invalid characters, like '/'
return make_image_filename(formatted_name)
def copy_or_link_file(source, target, dryrun=False, link=False, size=None,
options=None):
"""copies, links, or converts an image file.
Returns: True if the file exists.
"""
try:
if size:
mode = " (resize)"
elif link:
mode = " (link)"
else:
mode = " (copy)"
if os.path.exists(target):
_logger.info("Needs update: " + target + mode)
if options and not should_update(options):
return True
if not dryrun:
os.remove(target)
else:
_logger.info("New file: " + target + mode)
if options and not should_create(options):
return False
if dryrun:
return False
if link:
_logger.debug(u'os.link(%s, %s)', source, target)
os.link(source, target)
elif size:
result = resize_image(source, target, size)
if result:
_logger.error(u'%s: %s' % (source, result))
return False
else:
_logger.debug(u'shutil.copy2(%s, %s)', source, target)
shutil.copy2(source, target)
return True
except (OSError, IOError) as ex:
_logger.error(u'%s: %s' % (source, str(ex)))
return False
def get_missing_face_keywords(iptc_data, face_list=None):
"""Checks if keywords need to be added for faces. Returns the keywords that need
to be added."""
missing_keywords = []
if face_list == None:
face_list = iptc_data.region_names
for name in face_list:
# Look for the full name or just the first name.
if name in iptc_data.keywords:
continue
parts = name.split(" ")
if len(parts) <= 1 or not parts[0] in iptc_data.keywords:
missing_keywords.append(name)
return missing_keywords
def get_missing_face_hierarchical_keywords(iptc_data, face_list=None):
"""Checks if keywords need to be added for faces. Returns the keywords that need
to be added."""
missing_keywords = []
if face_list == None:
face_list = iptc_data.region_names
for name in face_list:
# Look for the full name or just the first name.
if "People|" + name in iptc_data.hierarchical_subject:
continue
parts = name.split(" ")
if len(parts) <= 1 or not "People|" + parts[0] in iptc_data.hierarchical_subject:
missing_keywords.append("People|" + name)
return missing_keywords
def get_face_caption_update(iptc_data, old_caption=None, face_list=None):
"""Checks if the caption of an image needs to be updated to mention
all persons. Returns the new caption if it needs to be changed,
None otherwise."""
if old_caption == None:
old_caption = iptc_data.caption.strip() if iptc_data.caption else u''
new_caption = old_caption
# See if everybody is mentioned
all_mentioned = True
if face_list == None:
face_list = iptc_data.region_names
for name in face_list:
parts = name.split(" ")
# Look for the full name or just the first name.
if (old_caption.find(name) == -1 and
(len(parts) <= 1 or old_caption.find(parts[0]) == -1)):
all_mentioned = False
break
if all_mentioned:
return None
new_suffix = '(' + ', '.join(face_list) + ')'
# See if the old caption ends with what looks like a list of names already.
if old_caption:
old_caption = _strip_old_names(old_caption, face_list)
if old_caption:
new_caption = old_caption + ' ' + new_suffix
else:
new_caption = new_suffix
return new_caption
def _strip_old_names(caption, names):
"""Strips off a "(name1, name2)" comment from the end of a caption if all the words
are names."""
if not caption.endswith(')'):
return caption
start = caption.rfind('(')
if start == -1:
return caption
# Check that all mentioned names are in the new list (we don't want to remove
# a comment if it mentions people that are not tagged)
substring = caption[start + 1:-1]
old_names = [n.strip() for n in substring.split(",")]
# Build a list of new names, using both the full name and just the first name.
new_names = names[:]
for name in names:
parts = name.split(" ")
if len(parts) > 1:
new_names.append(parts[0])
all_mentioned = True
for old_name in old_names:
if not old_name in new_names:
all_mentioned = False
break
if not all_mentioned:
return caption
# Yes, we got names, so lets strip it off.
new_caption = caption[:start].strip()
# Do it recursively in case we've added extra (...) sections before
return _strip_old_names(new_caption, names)
|
pdellaert/ansible
|
refs/heads/devel
|
test/units/modules/network/onyx/test_onyx_igmp.py
|
68
|
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.onyx import onyx_igmp
from units.modules.utils import set_module_args
from .onyx_module import TestOnyxModule, load_fixture
class TestOnyxIgmpModule(TestOnyxModule):
module = onyx_igmp
enabled = False
def setUp(self):
self.enabled = False
super(TestOnyxIgmpModule, self).setUp()
self.mock_get_config = patch.object(
onyx_igmp.OnyxIgmpModule, "_show_igmp")
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch(
'ansible.module_utils.network.onyx.onyx.load_config')
self.load_config = self.mock_load_config.start()
def tearDown(self):
super(TestOnyxIgmpModule, self).tearDown()
self.mock_get_config.stop()
self.mock_load_config.stop()
def load_fixtures(self, commands=None, transport='cli'):
config_file = 'onyx_igmp_show.cfg'
data = load_fixture(config_file)
if self.enabled:
data[0]['IGMP snooping globally'] = 'enabled'
self.get_config.return_value = data
self.load_config.return_value = None
def test_igmp_no_change(self):
set_module_args(dict(state='disabled'))
self.execute_module(changed=False)
def test_igmp_enable(self):
set_module_args(dict(state='enabled'))
commands = ['ip igmp snooping']
self.execute_module(changed=True, commands=commands)
def test_igmp_last_member_query_interval(self):
set_module_args(dict(state='enabled',
last_member_query_interval=10))
commands = ['ip igmp snooping',
'ip igmp snooping last-member-query-interval 10']
self.execute_module(changed=True, commands=commands)
def test_igmp_mrouter_timeout(self):
set_module_args(dict(state='enabled',
mrouter_timeout=100))
commands = ['ip igmp snooping',
'ip igmp snooping mrouter-timeout 100']
self.execute_module(changed=True, commands=commands)
def test_igmp_port_purge_timeout(self):
set_module_args(dict(state='enabled',
port_purge_timeout=150))
commands = ['ip igmp snooping',
'ip igmp snooping port-purge-timeout 150']
self.execute_module(changed=True, commands=commands)
def test_igmp_report_suppression_interval(self):
set_module_args(dict(state='enabled',
report_suppression_interval=10))
commands = ['ip igmp snooping',
'ip igmp snooping report-suppression-interval 10']
self.execute_module(changed=True, commands=commands)
def test_igmp_proxy_reporting_disabled(self):
set_module_args(dict(state='enabled',
proxy_reporting='disabled'))
commands = ['ip igmp snooping']
self.execute_module(changed=True, commands=commands)
def test_igmp_proxy_reporting_enabled(self):
set_module_args(dict(state='enabled',
proxy_reporting='enabled'))
commands = ['ip igmp snooping',
'ip igmp snooping proxy reporting']
self.execute_module(changed=True, commands=commands)
def test_igmp_unregistered_multicast_flood(self):
set_module_args(dict(state='enabled',
unregistered_multicast='flood'))
commands = ['ip igmp snooping']
self.execute_module(changed=True, commands=commands)
def test_igmp_unregistered_multicast_forward(self):
set_module_args(
dict(state='enabled',
unregistered_multicast='forward-to-mrouter-ports'))
commands = [
'ip igmp snooping',
'ip igmp snooping unregistered multicast forward-to-mrouter-ports'
]
self.execute_module(changed=True, commands=commands)
def test_igmp_version_v2(self):
set_module_args(dict(state='enabled',
default_version='V2'))
commands = ['ip igmp snooping',
'ip igmp snooping version 2']
self.execute_module(changed=True, commands=commands)
def test_igmp_version_v3(self):
set_module_args(dict(state='enabled',
default_version='V3'))
commands = ['ip igmp snooping']
self.execute_module(changed=True, commands=commands)
def test_igmp_disable(self):
self.enabled = True
set_module_args(dict(state='disabled'))
commands = ['no ip igmp snooping']
self.execute_module(changed=True, commands=commands)
|
airtame/linux
|
refs/heads/master
|
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/SchedGui.py
|
12980
|
# SchedGui.py - Python extension for perf script, basic GUI code for
# traces drawing and overview.
#
# Copyright (C) 2010 by Frederic Weisbecker <fweisbec@gmail.com>
#
# This software is distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
try:
import wx
except ImportError:
raise ImportError, "You need to install the wxpython lib for this script"
class RootFrame(wx.Frame):
Y_OFFSET = 100
RECT_HEIGHT = 100
RECT_SPACE = 50
EVENT_MARKING_WIDTH = 5
def __init__(self, sched_tracer, title, parent = None, id = -1):
wx.Frame.__init__(self, parent, id, title)
(self.screen_width, self.screen_height) = wx.GetDisplaySize()
self.screen_width -= 10
self.screen_height -= 10
self.zoom = 0.5
self.scroll_scale = 20
self.sched_tracer = sched_tracer
self.sched_tracer.set_root_win(self)
(self.ts_start, self.ts_end) = sched_tracer.interval()
self.update_width_virtual()
self.nr_rects = sched_tracer.nr_rectangles() + 1
self.height_virtual = RootFrame.Y_OFFSET + (self.nr_rects * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE))
# whole window panel
self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height))
# scrollable container
self.scroll = wx.ScrolledWindow(self.panel)
self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale)
self.scroll.EnableScrolling(True, True)
self.scroll.SetFocus()
# scrollable drawing area
self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width - 15, self.screen_height / 2))
self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint)
self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press)
self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down)
self.scroll.Bind(wx.EVT_PAINT, self.on_paint)
self.scroll.Bind(wx.EVT_KEY_DOWN, self.on_key_press)
self.scroll.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down)
self.scroll.Fit()
self.Fit()
self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, self.height_virtual, wx.SIZE_USE_EXISTING)
self.txt = None
self.Show(True)
def us_to_px(self, val):
return val / (10 ** 3) * self.zoom
def px_to_us(self, val):
return (val / self.zoom) * (10 ** 3)
def scroll_start(self):
(x, y) = self.scroll.GetViewStart()
return (x * self.scroll_scale, y * self.scroll_scale)
def scroll_start_us(self):
(x, y) = self.scroll_start()
return self.px_to_us(x)
def paint_rectangle_zone(self, nr, color, top_color, start, end):
offset_px = self.us_to_px(start - self.ts_start)
width_px = self.us_to_px(end - self.ts_start)
offset_py = RootFrame.Y_OFFSET + (nr * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE))
width_py = RootFrame.RECT_HEIGHT
dc = self.dc
if top_color is not None:
(r, g, b) = top_color
top_color = wx.Colour(r, g, b)
brush = wx.Brush(top_color, wx.SOLID)
dc.SetBrush(brush)
dc.DrawRectangle(offset_px, offset_py, width_px, RootFrame.EVENT_MARKING_WIDTH)
width_py -= RootFrame.EVENT_MARKING_WIDTH
offset_py += RootFrame.EVENT_MARKING_WIDTH
(r ,g, b) = color
color = wx.Colour(r, g, b)
brush = wx.Brush(color, wx.SOLID)
dc.SetBrush(brush)
dc.DrawRectangle(offset_px, offset_py, width_px, width_py)
def update_rectangles(self, dc, start, end):
start += self.ts_start
end += self.ts_start
self.sched_tracer.fill_zone(start, end)
def on_paint(self, event):
dc = wx.PaintDC(self.scroll_panel)
self.dc = dc
width = min(self.width_virtual, self.screen_width)
(x, y) = self.scroll_start()
start = self.px_to_us(x)
end = self.px_to_us(x + width)
self.update_rectangles(dc, start, end)
def rect_from_ypixel(self, y):
y -= RootFrame.Y_OFFSET
rect = y / (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)
height = y % (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)
if rect < 0 or rect > self.nr_rects - 1 or height > RootFrame.RECT_HEIGHT:
return -1
return rect
def update_summary(self, txt):
if self.txt:
self.txt.Destroy()
self.txt = wx.StaticText(self.panel, -1, txt, (0, (self.screen_height / 2) + 50))
def on_mouse_down(self, event):
(x, y) = event.GetPositionTuple()
rect = self.rect_from_ypixel(y)
if rect == -1:
return
t = self.px_to_us(x) + self.ts_start
self.sched_tracer.mouse_down(rect, t)
def update_width_virtual(self):
self.width_virtual = self.us_to_px(self.ts_end - self.ts_start)
def __zoom(self, x):
self.update_width_virtual()
(xpos, ypos) = self.scroll.GetViewStart()
xpos = self.us_to_px(x) / self.scroll_scale
self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale, xpos, ypos)
self.Refresh()
def zoom_in(self):
x = self.scroll_start_us()
self.zoom *= 2
self.__zoom(x)
def zoom_out(self):
x = self.scroll_start_us()
self.zoom /= 2
self.__zoom(x)
def on_key_press(self, event):
key = event.GetRawKeyCode()
if key == ord("+"):
self.zoom_in()
return
if key == ord("-"):
self.zoom_out()
return
key = event.GetKeyCode()
(x, y) = self.scroll.GetViewStart()
if key == wx.WXK_RIGHT:
self.scroll.Scroll(x + 1, y)
elif key == wx.WXK_LEFT:
self.scroll.Scroll(x - 1, y)
elif key == wx.WXK_DOWN:
self.scroll.Scroll(x, y + 1)
elif key == wx.WXK_UP:
self.scroll.Scroll(x, y - 1)
|
bruecksen/isimip
|
refs/heads/master
|
isi_mip/pages/migrations/0029_auto_20181114_1549.py
|
1
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-14 14:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import isi_mip.contrib.blocks
import modelcluster.fields
import wagtail.contrib.table_block.blocks
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.embeds.blocks
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0021_image_file_hash'),
('wagtailcore', '0040_page_draft_title'),
('pages', '0028_auto_20171207_1606'),
]
operations = [
migrations.CreateModel(
name='PaperOverviewPage',
fields=[
('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('content', wagtail.core.fields.StreamField([('heading', isi_mip.contrib.blocks.HeadingBlock()), ('rich_text', isi_mip.contrib.blocks.RichTextBlock()), ('horizontal_ruler', wagtail.core.blocks.StreamBlock([])), ('embed', wagtail.embeds.blocks.EmbedBlock()), ('image', isi_mip.contrib.blocks.ImageBlock()), ('table', wagtail.contrib.table_block.blocks.TableBlock()), ('monospace_text', isi_mip.contrib.blocks.MonospaceTextBlock())], blank=True)),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
migrations.CreateModel(
name='PaperPage',
fields=[
('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('author', models.CharField(max_length=1000)),
('journal', models.CharField(max_length=1000)),
('link', models.URLField()),
('picture', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='wagtailimages.Image')),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
migrations.CreateModel(
name='PaperPageTag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
],
),
migrations.AlterField(
model_name='formfield',
name='field_type',
field=models.CharField(choices=[('singleline', 'Single line text'), ('multiline', 'Multi-line text'), ('email', 'Email'), ('number', 'Number'), ('url', 'URL'), ('checkbox', 'Checkbox'), ('checkboxes', 'Checkboxes'), ('dropdown', 'Drop down'), ('multiselect', 'Multiple select'), ('radio', 'Radio buttons'), ('date', 'Date'), ('datetime', 'Date/time'), ('hidden', 'Hidden field')], max_length=16, verbose_name='field type'),
),
migrations.AddField(
model_name='paperpage',
name='tags',
field=modelcluster.fields.ParentalManyToManyField(blank=True, to='pages.PaperPageTag'),
),
]
|
sjlehtin/django
|
refs/heads/master
|
tests/utils_tests/test_autoreload.py
|
44
|
import gettext
import os
import shutil
import tempfile
from importlib import import_module
from unittest import mock
import _thread
from django import conf
from django.contrib import admin
from django.test import SimpleTestCase, override_settings
from django.test.utils import extend_sys_path
from django.utils import autoreload
from django.utils.translation import trans_real
LOCALE_PATH = os.path.join(os.path.dirname(__file__), 'locale')
class TestFilenameGenerator(SimpleTestCase):
def clear_autoreload_caches(self):
autoreload._cached_modules = set()
autoreload._cached_filenames = []
def assertFileFound(self, filename):
self.clear_autoreload_caches()
# Test uncached access
self.assertIn(filename, autoreload.gen_filenames())
# Test cached access
self.assertIn(filename, autoreload.gen_filenames())
def assertFileNotFound(self, filename):
self.clear_autoreload_caches()
# Test uncached access
self.assertNotIn(filename, autoreload.gen_filenames())
# Test cached access
self.assertNotIn(filename, autoreload.gen_filenames())
def assertFileFoundOnlyNew(self, filename):
self.clear_autoreload_caches()
# Test uncached access
self.assertIn(filename, autoreload.gen_filenames(only_new=True))
# Test cached access
self.assertNotIn(filename, autoreload.gen_filenames(only_new=True))
def test_django_locales(self):
"""
gen_filenames() yields the built-in Django locale files.
"""
django_dir = os.path.join(os.path.dirname(conf.__file__), 'locale')
django_mo = os.path.join(django_dir, 'nl', 'LC_MESSAGES', 'django.mo')
self.assertFileFound(django_mo)
@override_settings(LOCALE_PATHS=[LOCALE_PATH])
def test_locale_paths_setting(self):
"""
gen_filenames also yields from LOCALE_PATHS locales.
"""
locale_paths_mo = os.path.join(LOCALE_PATH, 'nl', 'LC_MESSAGES', 'django.mo')
self.assertFileFound(locale_paths_mo)
@override_settings(INSTALLED_APPS=[])
def test_project_root_locale(self):
"""
gen_filenames() also yields from the current directory (project root).
"""
old_cwd = os.getcwd()
os.chdir(os.path.dirname(__file__))
current_dir = os.path.join(os.path.dirname(__file__), 'locale')
current_dir_mo = os.path.join(current_dir, 'nl', 'LC_MESSAGES', 'django.mo')
try:
self.assertFileFound(current_dir_mo)
finally:
os.chdir(old_cwd)
@override_settings(INSTALLED_APPS=['django.contrib.admin'])
def test_app_locales(self):
"""
gen_filenames() also yields from locale dirs in installed apps.
"""
admin_dir = os.path.join(os.path.dirname(admin.__file__), 'locale')
admin_mo = os.path.join(admin_dir, 'nl', 'LC_MESSAGES', 'django.mo')
self.assertFileFound(admin_mo)
@override_settings(USE_I18N=False)
def test_no_i18n(self):
"""
If i18n machinery is disabled, there is no need for watching the
locale files.
"""
django_dir = os.path.join(os.path.dirname(conf.__file__), 'locale')
django_mo = os.path.join(django_dir, 'nl', 'LC_MESSAGES', 'django.mo')
self.assertFileNotFound(django_mo)
def test_paths_are_native_strings(self):
for filename in autoreload.gen_filenames():
self.assertIsInstance(filename, str)
def test_only_new_files(self):
"""
When calling a second time gen_filenames with only_new = True, only
files from newly loaded modules should be given.
"""
dirname = tempfile.mkdtemp()
filename = os.path.join(dirname, 'test_only_new_module.py')
self.addCleanup(shutil.rmtree, dirname)
with open(filename, 'w'):
pass
# Test uncached access
self.clear_autoreload_caches()
filenames = set(autoreload.gen_filenames(only_new=True))
filenames_reference = set(autoreload.gen_filenames())
self.assertEqual(filenames, filenames_reference)
# Test cached access: no changes
filenames = set(autoreload.gen_filenames(only_new=True))
self.assertEqual(filenames, set())
# Test cached access: add a module
with extend_sys_path(dirname):
import_module('test_only_new_module')
filenames = set(autoreload.gen_filenames(only_new=True))
self.assertEqual(filenames, {filename})
def test_deleted_removed(self):
"""
When a file is deleted, gen_filenames() no longer returns it.
"""
dirname = tempfile.mkdtemp()
filename = os.path.join(dirname, 'test_deleted_removed_module.py')
self.addCleanup(shutil.rmtree, dirname)
with open(filename, 'w'):
pass
with extend_sys_path(dirname):
import_module('test_deleted_removed_module')
self.assertFileFound(filename)
os.unlink(filename)
self.assertFileNotFound(filename)
def test_check_errors(self):
"""
When a file containing an error is imported in a function wrapped by
check_errors(), gen_filenames() returns it.
"""
dirname = tempfile.mkdtemp()
filename = os.path.join(dirname, 'test_syntax_error.py')
self.addCleanup(shutil.rmtree, dirname)
with open(filename, 'w') as f:
f.write("Ceci n'est pas du Python.")
with extend_sys_path(dirname):
with self.assertRaises(SyntaxError):
autoreload.check_errors(import_module)('test_syntax_error')
self.assertFileFound(filename)
def test_check_errors_only_new(self):
"""
When a file containing an error is imported in a function wrapped by
check_errors(), gen_filenames(only_new=True) returns it.
"""
dirname = tempfile.mkdtemp()
filename = os.path.join(dirname, 'test_syntax_error.py')
self.addCleanup(shutil.rmtree, dirname)
with open(filename, 'w') as f:
f.write("Ceci n'est pas du Python.")
with extend_sys_path(dirname):
with self.assertRaises(SyntaxError):
autoreload.check_errors(import_module)('test_syntax_error')
self.assertFileFoundOnlyNew(filename)
def test_check_errors_catches_all_exceptions(self):
"""
Since Python may raise arbitrary exceptions when importing code,
check_errors() must catch Exception, not just some subclasses.
"""
dirname = tempfile.mkdtemp()
filename = os.path.join(dirname, 'test_exception.py')
self.addCleanup(shutil.rmtree, dirname)
with open(filename, 'w') as f:
f.write("raise Exception")
with extend_sys_path(dirname):
with self.assertRaises(Exception):
autoreload.check_errors(import_module)('test_exception')
self.assertFileFound(filename)
class CleanFilesTests(SimpleTestCase):
TEST_MAP = {
# description: (input_file_list, expected_returned_file_list)
'falsies': ([None, False], []),
'pycs': (['myfile.pyc'], ['myfile.py']),
'pyos': (['myfile.pyo'], ['myfile.py']),
'$py.class': (['myclass$py.class'], ['myclass.py']),
'combined': (
[None, 'file1.pyo', 'file2.pyc', 'myclass$py.class'],
['file1.py', 'file2.py', 'myclass.py'],
)
}
def _run_tests(self, mock_files_exist=True):
with mock.patch('django.utils.autoreload.os.path.exists', return_value=mock_files_exist):
for description, values in self.TEST_MAP.items():
filenames, expected_returned_filenames = values
self.assertEqual(
autoreload.clean_files(filenames),
expected_returned_filenames if mock_files_exist else [],
msg='{} failed for input file list: {}; returned file list: {}'.format(
description, filenames, expected_returned_filenames
),
)
def test_files_exist(self):
"""
If the file exists, any compiled files (pyc, pyo, $py.class) are
transformed as their source files.
"""
self._run_tests()
def test_files_do_not_exist(self):
"""
If the files don't exist, they aren't in the returned file list.
"""
self._run_tests(mock_files_exist=False)
class ResetTranslationsTests(SimpleTestCase):
def setUp(self):
self.gettext_translations = gettext._translations.copy()
self.trans_real_translations = trans_real._translations.copy()
def tearDown(self):
gettext._translations = self.gettext_translations
trans_real._translations = self.trans_real_translations
def test_resets_gettext(self):
gettext._translations = {'foo': 'bar'}
autoreload.reset_translations()
self.assertEqual(gettext._translations, {})
def test_resets_trans_real(self):
trans_real._translations = {'foo': 'bar'}
trans_real._default = 1
trans_real._active = False
autoreload.reset_translations()
self.assertEqual(trans_real._translations, {})
self.assertIsNone(trans_real._default)
self.assertIsInstance(trans_real._active, _thread._local)
|
joshisa/zulip
|
refs/heads/master
|
analytics/management/commands/active_user_stats.py
|
116
|
from __future__ import absolute_import
from django.core.management.base import BaseCommand
from zerver.models import UserPresence, UserActivity
from zerver.lib.utils import statsd, statsd_key
from datetime import datetime, timedelta
from collections import defaultdict
class Command(BaseCommand):
help = """Sends active user statistics to statsd.
Run as a cron job that runs every 10 minutes."""
def handle(self, *args, **options):
# Get list of all active users in the last 1 week
cutoff = datetime.now() - timedelta(minutes=30, hours=168)
users = UserPresence.objects.select_related().filter(timestamp__gt=cutoff)
# Calculate 10min, 2hrs, 12hrs, 1day, 2 business days (TODO business days), 1 week bucket of stats
hour_buckets = [0.16, 2, 12, 24, 48, 168]
user_info = defaultdict(dict)
for last_presence in users:
if last_presence.status == UserPresence.IDLE:
known_active = last_presence.timestamp - timedelta(minutes=30)
else:
known_active = last_presence.timestamp
for bucket in hour_buckets:
if not bucket in user_info[last_presence.user_profile.realm.domain]:
user_info[last_presence.user_profile.realm.domain][bucket] = []
if datetime.now(known_active.tzinfo) - known_active < timedelta(hours=bucket):
user_info[last_presence.user_profile.realm.domain][bucket].append(last_presence.user_profile.email)
for realm, buckets in user_info.items():
print("Realm %s" % realm)
for hr, users in sorted(buckets.items()):
print("\tUsers for %s: %s" % (hr, len(users)))
statsd.gauge("users.active.%s.%shr" % (statsd_key(realm, True), statsd_key(hr, True)), len(users))
# Also do stats for how many users have been reading the app.
users_reading = UserActivity.objects.select_related().filter(query="/json/update_message_flags")
user_info = defaultdict(dict)
for activity in users_reading:
for bucket in hour_buckets:
if not bucket in user_info[activity.user_profile.realm.domain]:
user_info[activity.user_profile.realm.domain][bucket] = []
if datetime.now(activity.last_visit.tzinfo) - activity.last_visit < timedelta(hours=bucket):
user_info[activity.user_profile.realm.domain][bucket].append(activity.user_profile.email)
for realm, buckets in user_info.items():
print("Realm %s" % realm)
for hr, users in sorted(buckets.items()):
print("\tUsers reading for %s: %s" % (hr, len(users)))
statsd.gauge("users.reading.%s.%shr" % (statsd_key(realm, True), statsd_key(hr, True)), len(users))
|
Jimdo/ansible-modules-core
|
refs/heads/devel
|
files/lineinfile.py
|
27
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
# (c) 2014, Ahti Kitsik <ak@ahtik.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import pipes
import re
import os
import tempfile
DOCUMENTATION = """
---
module: lineinfile
author: Daniel Hokka Zakrisson, Ahti Kitsik
extends_documentation_fragment: files
short_description: Ensure a particular line is in a file, or replace an
existing line using a back-referenced regular expression.
description:
- This module will search a file for a line, and ensure that it is present or absent.
- This is primarily useful when you want to change a single line in
a file only. See the M(replace) module if you want to change
multiple, similar lines; for other cases, see the M(copy) or
M(template) modules.
version_added: "0.7"
options:
dest:
required: true
aliases: [ name, destfile ]
description:
- The file to modify.
regexp:
required: false
version_added: 1.7
description:
- The regular expression to look for in every line of the file. For
C(state=present), the pattern to replace if found; only the last line
found will be replaced. For C(state=absent), the pattern of the line
to remove. Uses Python regular expressions; see
U(http://docs.python.org/2/library/re.html).
state:
required: false
choices: [ present, absent ]
default: "present"
aliases: []
description:
- Whether the line should be there or not.
line:
required: false
description:
- Required for C(state=present). The line to insert/replace into the
file. If C(backrefs) is set, may contain backreferences that will get
expanded with the C(regexp) capture groups if the regexp matches. The
backreferences should be double escaped (see examples).
backrefs:
required: false
default: "no"
choices: [ "yes", "no" ]
version_added: "1.1"
description:
- Used with C(state=present). If set, line can contain backreferences
(both positional and named) that will get populated if the C(regexp)
matches. This flag changes the operation of the module slightly;
C(insertbefore) and C(insertafter) will be ignored, and if the C(regexp)
doesn't match anywhere in the file, the file will be left unchanged.
If the C(regexp) does match, the last matching line will be replaced by
the expanded line parameter.
insertafter:
required: false
default: EOF
description:
- Used with C(state=present). If specified, the line will be inserted
after the last match of specified regular expression. A special value is
available; C(EOF) for inserting the line at the end of the file.
If specified regular expresion has no matches, EOF will be used instead.
May not be used with C(backrefs).
choices: [ 'EOF', '*regex*' ]
insertbefore:
required: false
version_added: "1.1"
description:
- Used with C(state=present). If specified, the line will be inserted
before the last match of specified regular expression. A value is
available; C(BOF) for inserting the line at the beginning of the file.
If specified regular expresion has no matches, the line will be
inserted at the end of the file. May not be used with C(backrefs).
choices: [ 'BOF', '*regex*' ]
create:
required: false
choices: [ "yes", "no" ]
default: "no"
description:
- Used with C(state=present). If specified, the file will be created
if it does not already exist. By default it will fail if the file
is missing.
backup:
required: false
default: "no"
choices: [ "yes", "no" ]
description:
- Create a backup file including the timestamp information so you can
get the original file back if you somehow clobbered it incorrectly.
validate:
required: false
description:
- validation to run before copying into place.
Use %s in the command to indicate the current file to validate.
The command is passed securely so shell features like
expansion and pipes won't work.
required: false
default: None
version_added: "1.4"
others:
description:
- All arguments accepted by the M(file) module also work here.
required: false
"""
EXAMPLES = r"""
- lineinfile: dest=/etc/selinux/config regexp=^SELINUX= line=SELINUX=enforcing
- lineinfile: dest=/etc/sudoers state=absent regexp="^%wheel"
- lineinfile: dest=/etc/hosts regexp='^127\.0\.0\.1' line='127.0.0.1 localhost' owner=root group=root mode=0644
- lineinfile: dest=/etc/httpd/conf/httpd.conf regexp="^Listen " insertafter="^#Listen " line="Listen 8080"
- lineinfile: dest=/etc/services regexp="^# port for http" insertbefore="^www.*80/tcp" line="# port for http by default"
# Add a line to a file if it does not exist, without passing regexp
- lineinfile: dest=/tmp/testfile line="192.168.1.99 foo.lab.net foo"
# Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
- lineinfile: "dest=/etc/sudoers state=present regexp='^%wheel' line='%wheel ALL=(ALL) NOPASSWD: ALL'"
- lineinfile: dest=/opt/jboss-as/bin/standalone.conf regexp='^(.*)Xms(\d+)m(.*)$' line='\1Xms${xms}m\3' backrefs=yes
# Validate the sudoers file before saving
- lineinfile: dest=/etc/sudoers state=present regexp='^%ADMIN ALL\=' line='%ADMIN ALL=(ALL) NOPASSWD:ALL' validate='visudo -cf %s'
"""
def write_changes(module,lines,dest):
tmpfd, tmpfile = tempfile.mkstemp()
f = os.fdopen(tmpfd,'wb')
f.writelines(lines)
f.close()
validate = module.params.get('validate', None)
valid = not validate
if validate:
if "%s" not in validate:
module.fail_json(msg="validate must contain %%s: %s" % (validate))
(rc, out, err) = module.run_command(validate % tmpfile)
valid = rc == 0
if rc != 0:
module.fail_json(msg='failed to validate: '
'rc:%s error:%s' % (rc,err))
if valid:
module.atomic_move(tmpfile, os.path.realpath(dest))
def check_file_attrs(module, changed, message):
file_args = module.load_file_common_arguments(module.params)
if module.set_fs_attributes_if_different(file_args, False):
if changed:
message += " and "
changed = True
message += "ownership, perms or SE linux context changed"
return message, changed
def present(module, dest, regexp, line, insertafter, insertbefore, create,
backup, backrefs):
if not os.path.exists(dest):
if not create:
module.fail_json(rc=257, msg='Destination %s does not exist !' % dest)
destpath = os.path.dirname(dest)
if not os.path.exists(destpath) and not module.check_mode:
os.makedirs(destpath)
lines = []
else:
f = open(dest, 'rb')
lines = f.readlines()
f.close()
msg = ""
if regexp is not None:
mre = re.compile(regexp)
if insertafter not in (None, 'BOF', 'EOF'):
insre = re.compile(insertafter)
elif insertbefore not in (None, 'BOF'):
insre = re.compile(insertbefore)
else:
insre = None
# index[0] is the line num where regexp has been found
# index[1] is the line num where insertafter/inserbefore has been found
index = [-1, -1]
m = None
for lineno, cur_line in enumerate(lines):
if regexp is not None:
match_found = mre.search(cur_line)
else:
match_found = line == cur_line.rstrip('\r\n')
if match_found:
index[0] = lineno
m = match_found
elif insre is not None and insre.search(cur_line):
if insertafter:
# + 1 for the next line
index[1] = lineno + 1
if insertbefore:
# + 1 for the previous line
index[1] = lineno
msg = ''
changed = False
# Regexp matched a line in the file
if index[0] != -1:
if backrefs:
new_line = m.expand(line)
else:
# Don't do backref expansion if not asked.
new_line = line
if lines[index[0]] != new_line + os.linesep:
lines[index[0]] = new_line + os.linesep
msg = 'line replaced'
changed = True
elif backrefs:
# Do absolutely nothing, since it's not safe generating the line
# without the regexp matching to populate the backrefs.
pass
# Add it to the beginning of the file
elif insertbefore == 'BOF' or insertafter == 'BOF':
lines.insert(0, line + os.linesep)
msg = 'line added'
changed = True
# Add it to the end of the file if requested or
# if insertafter/insertbefore didn't match anything
# (so default behaviour is to add at the end)
elif insertafter == 'EOF' or index[1] == -1:
# If the file is not empty then ensure there's a newline before the added line
if len(lines)>0 and not (lines[-1].endswith('\n') or lines[-1].endswith('\r')):
lines.append(os.linesep)
lines.append(line + os.linesep)
msg = 'line added'
changed = True
# insert* matched, but not the regexp
else:
lines.insert(index[1], line + os.linesep)
msg = 'line added'
changed = True
backupdest = ""
if changed and not module.check_mode:
if backup and os.path.exists(dest):
backupdest = module.backup_local(dest)
write_changes(module, lines, dest)
if module.check_mode and not os.path.exists(dest):
module.exit_json(changed=changed, msg=msg, backup=backupdest)
msg, changed = check_file_attrs(module, changed, msg)
module.exit_json(changed=changed, msg=msg, backup=backupdest)
def absent(module, dest, regexp, line, backup):
if not os.path.exists(dest):
module.exit_json(changed=False, msg="file not present")
msg = ""
f = open(dest, 'rb')
lines = f.readlines()
f.close()
if regexp is not None:
cre = re.compile(regexp)
found = []
def matcher(cur_line):
if regexp is not None:
match_found = cre.search(cur_line)
else:
match_found = line == cur_line.rstrip('\r\n')
if match_found:
found.append(cur_line)
return not match_found
lines = filter(matcher, lines)
changed = len(found) > 0
backupdest = ""
if changed and not module.check_mode:
if backup:
backupdest = module.backup_local(dest)
write_changes(module, lines, dest)
if changed:
msg = "%s line(s) removed" % len(found)
msg, changed = check_file_attrs(module, changed, msg)
module.exit_json(changed=changed, found=len(found), msg=msg, backup=backupdest)
def main():
module = AnsibleModule(
argument_spec=dict(
dest=dict(required=True, aliases=['name', 'destfile']),
state=dict(default='present', choices=['absent', 'present']),
regexp=dict(default=None),
line=dict(aliases=['value']),
insertafter=dict(default=None),
insertbefore=dict(default=None),
backrefs=dict(default=False, type='bool'),
create=dict(default=False, type='bool'),
backup=dict(default=False, type='bool'),
validate=dict(default=None, type='str'),
),
mutually_exclusive=[['insertbefore', 'insertafter']],
add_file_common_args=True,
supports_check_mode=True
)
params = module.params
create = module.params['create']
backup = module.params['backup']
backrefs = module.params['backrefs']
dest = os.path.expanduser(params['dest'])
if os.path.isdir(dest):
module.fail_json(rc=256, msg='Destination %s is a directory !' % dest)
if params['state'] == 'present':
if backrefs and params['regexp'] is None:
module.fail_json(msg='regexp= is required with backrefs=true')
if params.get('line', None) is None:
module.fail_json(msg='line= is required with state=present')
# Deal with the insertafter default value manually, to avoid errors
# because of the mutually_exclusive mechanism.
ins_bef, ins_aft = params['insertbefore'], params['insertafter']
if ins_bef is None and ins_aft is None:
ins_aft = 'EOF'
line = params['line']
# The safe_eval call will remove some quoting, but not others,
# so we need to know if we should specifically unquote it.
should_unquote = not is_quoted(line)
# always add one layer of quotes
line = "'%s'" % line
# Replace escape sequences like '\n' while being sure
# not to replace octal escape sequences (\ooo) since they
# match the backref syntax.
if backrefs:
line = re.sub(r'(\\[0-9]{1,3})', r'\\\1', line)
line = module.safe_eval(line)
# Now remove quotes around the string, if needed after
# removing the layer we added above
line = unquote(line)
if should_unquote:
line = unquote(line)
present(module, dest, params['regexp'], line,
ins_aft, ins_bef, create, backup, backrefs)
else:
if params['regexp'] is None and params.get('line', None) is None:
module.fail_json(msg='one of line= or regexp= is required with state=absent')
absent(module, dest, params['regexp'], params.get('line', None), backup)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.splitter import *
main()
|
IndonesiaX/edx-platform
|
refs/heads/master
|
common/test/acceptance/pages/lms/index.py
|
5
|
# -*- coding: utf-8 -*-
"""
LMS index (home) page.
"""
from bok_choy.page_object import PageObject
from . import BASE_URL
BANNER_SELECTOR = 'section.home header div.outer-wrapper div.title hgroup h1'
INTRO_VIDEO_SELECTOR = 'div.play-intro'
VIDEO_MODAL_SELECTOR = 'section#video-modal.modal.home-page-video-modal.video-modal'
class IndexPage(PageObject):
"""
LMS index (home) page, the default landing page for Open edX users when they are not logged in
"""
def __init__(self, browser):
"""Initialize the page.
Arguments:
browser (Browser): The browser instance.
"""
super(IndexPage, self).__init__(browser)
url = "{base}/".format(base=BASE_URL)
def is_browser_on_page(self):
"""
Returns a browser query object representing the video modal element
"""
element = self.q(css=BANNER_SELECTOR)
return element.visible and element.text[0] == "Welcome to Open edX!"
@property
def banner_element(self):
"""
Returns a browser query object representing the video modal element
"""
return self.q(css=BANNER_SELECTOR)
@property
def intro_video_element(self):
"""
Returns a browser query object representing the video modal element
"""
return self.q(css=INTRO_VIDEO_SELECTOR)
@property
def video_modal_element(self):
"""
Returns a browser query object representing the video modal element
"""
return self.q(css=VIDEO_MODAL_SELECTOR)
|
yencarnacion/jaikuengine
|
refs/heads/master
|
.google_appengine/lib/django-1.5/django/contrib/messages/middleware.py
|
1220
|
from django.conf import settings
from django.contrib.messages.storage import default_storage
class MessageMiddleware(object):
"""
Middleware that handles temporary messages.
"""
def process_request(self, request):
request._messages = default_storage(request)
def process_response(self, request, response):
"""
Updates the storage backend (i.e., saves the messages).
If not all messages could not be stored and ``DEBUG`` is ``True``, a
``ValueError`` is raised.
"""
# A higher middleware layer may return a request which does not contain
# messages storage, so make no assumption that it will be there.
if hasattr(request, '_messages'):
unstored_messages = request._messages.update(response)
if unstored_messages and settings.DEBUG:
raise ValueError('Not all temporary messages could be stored.')
return response
|
bolster/sorl-url
|
refs/heads/master
|
sorl_url/tests.py
|
6666
|
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
|
jomauricio/abgthe
|
refs/heads/master
|
abgthe/profiles/views.py
|
2
|
from .models import Profile
from .forms import ProfilesForm
from braces.views import LoginRequiredMixin
from django.views.generic import UpdateView, DetailView, RedirectView
from django.core.urlresolvers import reverse
class ProfileDetailView(LoginRequiredMixin, DetailView):
model = Profile
form_class = ProfilesForm
template_name = "profiles/profile_detail.html"
slug_field = "username"
slug_url_kwarg = "username"
class ProfileUpdateView(LoginRequiredMixin, UpdateView):
model = Profile
form_class = ProfilesForm
template_name = 'profiles/profile_update.html'
slug_field = "username"
slug_url_kwarg = "username"
class ProfileRedirectView(LoginRequiredMixin, RedirectView):
permanent = False
def get_redirect_url(self):
return reverse("profiles:profile_detail",
kwargs={"username": self.request.user.username})
|
ftomassetti/intellij-community
|
refs/heads/master
|
python/testData/mover/theSameLevelMultiple_afterUp.py
|
83
|
try:
a = 1
except ImportError as A:
import <caret>tmp2; import tmp1
print xrange
|
mlassnig/pilot
|
refs/heads/master
|
movers/__init__.py
|
3
|
"""
Site Movers package
:author: Alexey Anisenkov
"""
from .base import BaseSiteMover
# import evertying here to allow import movers explicitly by its name from the package
from .sitemovers import *
import sitemovers
def getSiteMover(name):
""" Resolve Site Mover class by its ID name """
# get all mover classes
mclasses = dict([getattr(sitemovers, key).getID(), getattr(sitemovers, key)] for key in dir(sitemovers) if not key.startswith('_') \
and issubclass(getattr(sitemovers, key), BaseSiteMover))
# resolve mover by name
mover = mclasses.get(name)
if not mover:
raise ValueError('SiteMoverFactory: Failed to resolve site mover by name="%s": NOT IMPLEMENTED, accepted_names=%s' % (name, sorted(mclasses)))
return mover
def getSiteMoverByScheme(scheme, allowed_movers=None):
"""
Resolve Site Mover class by protocol scheme
Default (hard-coded) map
"""
# list of movers supported for following scheme protocols
cmap = {
#'scheme': [ordered list of preferred movers by DEFAULT] -- site can restrict the list of preferred movers by passing allowed_movers variable
'root': ['xrdcp', 'rucio', 'lcgcp', 'lsm'],
'srm': ['rucio', 'lcgcp', 'lsm'],
'dcap': ['dccp'],
#'gsiftp': ['rucio'],
#'https': ['rucio'],
# default sitemover to be used
#'default': ['rucio']
}
dat = cmap.get(scheme) or cmap.get('default', [])
for mover in dat:
if allowed_movers and mover not in allowed_movers:
continue
return getSiteMover(mover)
return None
raise ValueError('SiteMoverFactory/getSiteMoverByScheme: Failed to resolve site mover for scheme="%s", allowed_movers=%s .. associated_movers=%s' % (scheme, allowed_movers, dat))
from .mover import JobMover
|
syaiful6/django
|
refs/heads/master
|
tests/save_delete_hooks/__init__.py
|
12133432
| |
msherry/PyXB-1.1.4
|
refs/heads/master
|
pyxb_114/bundles/wssplat/__init__.py
|
12133432
| |
vladmm/intellij-community
|
refs/heads/master
|
python/testData/resolve/multiFile/localImport/mypackage/__init__.py
|
12133432
| |
cpenv/cpenv
|
refs/heads/master
|
cpenv/vendor/yaml/yaml2/resolver.py
|
76
|
__all__ = ['BaseResolver', 'Resolver']
from error import *
from nodes import *
import re
class ResolverError(YAMLError):
pass
class BaseResolver(object):
DEFAULT_SCALAR_TAG = u'tag:yaml.org,2002:str'
DEFAULT_SEQUENCE_TAG = u'tag:yaml.org,2002:seq'
DEFAULT_MAPPING_TAG = u'tag:yaml.org,2002:map'
yaml_implicit_resolvers = {}
yaml_path_resolvers = {}
def __init__(self):
self.resolver_exact_paths = []
self.resolver_prefix_paths = []
def add_implicit_resolver(cls, tag, regexp, first):
if not 'yaml_implicit_resolvers' in cls.__dict__:
implicit_resolvers = {}
for key in cls.yaml_implicit_resolvers:
implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:]
cls.yaml_implicit_resolvers = implicit_resolvers
if first is None:
first = [None]
for ch in first:
cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp))
add_implicit_resolver = classmethod(add_implicit_resolver)
def add_path_resolver(cls, tag, path, kind=None):
# Note: `add_path_resolver` is experimental. The API could be changed.
# `new_path` is a pattern that is matched against the path from the
# root to the node that is being considered. `node_path` elements are
# tuples `(node_check, index_check)`. `node_check` is a node class:
# `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None`
# matches any kind of a node. `index_check` could be `None`, a boolean
# value, a string value, or a number. `None` and `False` match against
# any _value_ of sequence and mapping nodes. `True` matches against
# any _key_ of a mapping node. A string `index_check` matches against
# a mapping value that corresponds to a scalar key which content is
# equal to the `index_check` value. An integer `index_check` matches
# against a sequence value with the index equal to `index_check`.
if not 'yaml_path_resolvers' in cls.__dict__:
cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy()
new_path = []
for element in path:
if isinstance(element, (list, tuple)):
if len(element) == 2:
node_check, index_check = element
elif len(element) == 1:
node_check = element[0]
index_check = True
else:
raise ResolverError("Invalid path element: %s" % element)
else:
node_check = None
index_check = element
if node_check is str:
node_check = ScalarNode
elif node_check is list:
node_check = SequenceNode
elif node_check is dict:
node_check = MappingNode
elif node_check not in [ScalarNode, SequenceNode, MappingNode] \
and not isinstance(node_check, basestring) \
and node_check is not None:
raise ResolverError("Invalid node checker: %s" % node_check)
if not isinstance(index_check, (basestring, int)) \
and index_check is not None:
raise ResolverError("Invalid index checker: %s" % index_check)
new_path.append((node_check, index_check))
if kind is str:
kind = ScalarNode
elif kind is list:
kind = SequenceNode
elif kind is dict:
kind = MappingNode
elif kind not in [ScalarNode, SequenceNode, MappingNode] \
and kind is not None:
raise ResolverError("Invalid node kind: %s" % kind)
cls.yaml_path_resolvers[tuple(new_path), kind] = tag
add_path_resolver = classmethod(add_path_resolver)
def descend_resolver(self, current_node, current_index):
if not self.yaml_path_resolvers:
return
exact_paths = {}
prefix_paths = []
if current_node:
depth = len(self.resolver_prefix_paths)
for path, kind in self.resolver_prefix_paths[-1]:
if self.check_resolver_prefix(depth, path, kind,
current_node, current_index):
if len(path) > depth:
prefix_paths.append((path, kind))
else:
exact_paths[kind] = self.yaml_path_resolvers[path, kind]
else:
for path, kind in self.yaml_path_resolvers:
if not path:
exact_paths[kind] = self.yaml_path_resolvers[path, kind]
else:
prefix_paths.append((path, kind))
self.resolver_exact_paths.append(exact_paths)
self.resolver_prefix_paths.append(prefix_paths)
def ascend_resolver(self):
if not self.yaml_path_resolvers:
return
self.resolver_exact_paths.pop()
self.resolver_prefix_paths.pop()
def check_resolver_prefix(self, depth, path, kind,
current_node, current_index):
node_check, index_check = path[depth-1]
if isinstance(node_check, basestring):
if current_node.tag != node_check:
return
elif node_check is not None:
if not isinstance(current_node, node_check):
return
if index_check is True and current_index is not None:
return
if (index_check is False or index_check is None) \
and current_index is None:
return
if isinstance(index_check, basestring):
if not (isinstance(current_index, ScalarNode)
and index_check == current_index.value):
return
elif isinstance(index_check, int) and not isinstance(index_check, bool):
if index_check != current_index:
return
return True
def resolve(self, kind, value, implicit):
if kind is ScalarNode and implicit[0]:
if value == u'':
resolvers = self.yaml_implicit_resolvers.get(u'', [])
else:
resolvers = self.yaml_implicit_resolvers.get(value[0], [])
resolvers += self.yaml_implicit_resolvers.get(None, [])
for tag, regexp in resolvers:
if regexp.match(value):
return tag
implicit = implicit[1]
if self.yaml_path_resolvers:
exact_paths = self.resolver_exact_paths[-1]
if kind in exact_paths:
return exact_paths[kind]
if None in exact_paths:
return exact_paths[None]
if kind is ScalarNode:
return self.DEFAULT_SCALAR_TAG
elif kind is SequenceNode:
return self.DEFAULT_SEQUENCE_TAG
elif kind is MappingNode:
return self.DEFAULT_MAPPING_TAG
class Resolver(BaseResolver):
pass
Resolver.add_implicit_resolver(
u'tag:yaml.org,2002:bool',
re.compile(ur'''^(?:yes|Yes|YES|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF)$''', re.X),
list(u'yYnNtTfFoO'))
Resolver.add_implicit_resolver(
u'tag:yaml.org,2002:float',
re.compile(ur'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
|\.[0-9_]+(?:[eE][-+][0-9]+)?
|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
|[-+]?\.(?:inf|Inf|INF)
|\.(?:nan|NaN|NAN))$''', re.X),
list(u'-+0123456789.'))
Resolver.add_implicit_resolver(
u'tag:yaml.org,2002:int',
re.compile(ur'''^(?:[-+]?0b[0-1_]+
|[-+]?0[0-7_]+
|[-+]?(?:0|[1-9][0-9_]*)
|[-+]?0x[0-9a-fA-F_]+
|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
list(u'-+0123456789'))
Resolver.add_implicit_resolver(
u'tag:yaml.org,2002:merge',
re.compile(ur'^(?:<<)$'),
[u'<'])
Resolver.add_implicit_resolver(
u'tag:yaml.org,2002:null',
re.compile(ur'''^(?: ~
|null|Null|NULL
| )$''', re.X),
[u'~', u'n', u'N', u''])
Resolver.add_implicit_resolver(
u'tag:yaml.org,2002:timestamp',
re.compile(ur'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
|[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
(?:[Tt]|[ \t]+)[0-9][0-9]?
:[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)?
(?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
list(u'0123456789'))
Resolver.add_implicit_resolver(
u'tag:yaml.org,2002:value',
re.compile(ur'^(?:=)$'),
[u'='])
# The following resolver is only for documentation purposes. It cannot work
# because plain scalars cannot start with '!', '&', or '*'.
Resolver.add_implicit_resolver(
u'tag:yaml.org,2002:yaml',
re.compile(ur'^(?:!|&|\*)$'),
list(u'!&*'))
|
strogo/flask-babel
|
refs/heads/master
|
tests/tests.py
|
12
|
# -*- coding: utf-8 -*-
from __future__ import with_statement
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
import unittest
from decimal import Decimal
import flask
from datetime import datetime
from flaskext import babel
from flaskext.babel import gettext, ngettext, lazy_gettext
class DateFormattingTestCase(unittest.TestCase):
def test_basics(self):
app = flask.Flask(__name__)
b = babel.Babel(app)
d = datetime(2010, 4, 12, 13, 46)
with app.test_request_context():
assert babel.format_datetime(d) == 'Apr 12, 2010 1:46:00 PM'
assert babel.format_date(d) == 'Apr 12, 2010'
assert babel.format_time(d) == '1:46:00 PM'
with app.test_request_context():
app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna'
assert babel.format_datetime(d) == 'Apr 12, 2010 3:46:00 PM'
assert babel.format_date(d) == 'Apr 12, 2010'
assert babel.format_time(d) == '3:46:00 PM'
with app.test_request_context():
app.config['BABEL_DEFAULT_LOCALE'] = 'de_DE'
assert babel.format_datetime(d, 'long') == \
'12. April 2010 15:46:00 MESZ'
def test_init_app(self):
b = babel.Babel()
app = flask.Flask(__name__)
b.init_app(app)
d = datetime(2010, 4, 12, 13, 46)
with app.test_request_context():
assert babel.format_datetime(d) == 'Apr 12, 2010 1:46:00 PM'
assert babel.format_date(d) == 'Apr 12, 2010'
assert babel.format_time(d) == '1:46:00 PM'
with app.test_request_context():
app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna'
assert babel.format_datetime(d) == 'Apr 12, 2010 3:46:00 PM'
assert babel.format_date(d) == 'Apr 12, 2010'
assert babel.format_time(d) == '3:46:00 PM'
with app.test_request_context():
app.config['BABEL_DEFAULT_LOCALE'] = 'de_DE'
assert babel.format_datetime(d, 'long') == \
'12. April 2010 15:46:00 MESZ'
def test_custom_formats(self):
app = flask.Flask(__name__)
app.config.update(
BABEL_DEFAULT_LOCALE='en_US',
BABEL_DEFAULT_TIMEZONE='Pacific/Johnston'
)
b = babel.Babel(app)
b.date_formats['datetime'] = 'long'
b.date_formats['datetime.long'] = 'MMMM d, yyyy h:mm:ss a'
d = datetime(2010, 4, 12, 13, 46)
with app.test_request_context():
assert babel.format_datetime(d) == 'April 12, 2010 3:46:00 AM'
def test_custom_locale_selector(self):
app = flask.Flask(__name__)
b = babel.Babel(app)
d = datetime(2010, 4, 12, 13, 46)
the_timezone = 'UTC'
the_locale = 'en_US'
@b.localeselector
def select_locale():
return the_locale
@b.timezoneselector
def select_timezone():
return the_timezone
with app.test_request_context():
assert babel.format_datetime(d) == 'Apr 12, 2010 1:46:00 PM'
the_locale = 'de_DE'
the_timezone = 'Europe/Vienna'
with app.test_request_context():
assert babel.format_datetime(d) == '12.04.2010 15:46:00'
def test_refreshing(self):
app = flask.Flask(__name__)
b = babel.Babel(app)
d = datetime(2010, 4, 12, 13, 46)
with app.test_request_context():
assert babel.format_datetime(d) == 'Apr 12, 2010 1:46:00 PM'
app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna'
babel.refresh()
assert babel.format_datetime(d) == 'Apr 12, 2010 3:46:00 PM'
class NumberFormattingTestCase(unittest.TestCase):
def test_basics(self):
app = flask.Flask(__name__)
b = babel.Babel(app)
n = 1099
with app.test_request_context():
assert babel.format_number(n) == u'1,099'
assert babel.format_decimal(Decimal('1010.99')) == u'1,010.99'
assert babel.format_currency(n, 'USD') == '$1,099.00'
assert babel.format_percent(0.19) == '19%'
assert babel.format_scientific(10000) == u'1E4'
class GettextTestCase(unittest.TestCase):
def test_basics(self):
app = flask.Flask(__name__)
b = babel.Babel(app, default_locale='de_DE')
with app.test_request_context():
assert gettext(u'Hello %(name)s!', name='Peter') == 'Hallo Peter!'
assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 3) == u'3 Äpfel'
assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 1) == u'1 Apfel'
def test_template_basics(self):
app = flask.Flask(__name__)
b = babel.Babel(app, default_locale='de_DE')
t = lambda x: flask.render_template_string('{{ %s }}' % x)
with app.test_request_context():
assert t("gettext('Hello %(name)s!', name='Peter')") == 'Hallo Peter!'
assert t("ngettext('%(num)s Apple', '%(num)s Apples', 3)") == u'3 Äpfel'
assert t("ngettext('%(num)s Apple', '%(num)s Apples', 1)") == u'1 Apfel'
assert flask.render_template_string('''
{% trans %}Hello {{ name }}!{% endtrans %}
''', name='Peter').strip() == 'Hallo Peter!'
assert flask.render_template_string('''
{% trans num=3 %}{{ num }} Apple
{%- pluralize %}{{ num }} Apples{% endtrans %}
''', name='Peter').strip() == u'3 Äpfel'
def test_lazy_gettext(self):
app = flask.Flask(__name__)
b = babel.Babel(app, default_locale='de_DE')
yes = lazy_gettext(u'Yes')
with app.test_request_context():
assert unicode(yes) == 'Ja'
app.config['BABEL_DEFAULT_LOCALE'] = 'en_US'
with app.test_request_context():
assert unicode(yes) == 'Yes'
def test_list_translations(self):
app = flask.Flask(__name__)
b = babel.Babel(app, default_locale='de_DE')
translations = b.list_translations()
assert len(translations) == 1
assert str(translations[0]) == 'de'
if __name__ == '__main__':
unittest.main()
|
caotianwei/django
|
refs/heads/master
|
tests/model_options/__init__.py
|
12133432
| |
oceanobservatories/mi-instrument
|
refs/heads/master
|
mi/instrument/seabird/__init__.py
|
12133432
| |
zorojean/scikit-learn
|
refs/heads/master
|
sklearn/utils/tests/test_optimize.py
|
135
|
import numpy as np
from sklearn.utils.optimize import newton_cg
from scipy.optimize import fmin_ncg
from sklearn.utils.testing import assert_array_almost_equal
def test_newton_cg():
# Test that newton_cg gives same result as scipy's fmin_ncg
rng = np.random.RandomState(0)
A = rng.normal(size=(10, 10))
x0 = np.ones(10)
def func(x):
Ax = A.dot(x)
return .5 * (Ax).dot(Ax)
def grad(x):
return A.T.dot(A.dot(x))
def hess(x, p):
return p.dot(A.T.dot(A.dot(x.all())))
def grad_hess(x):
return grad(x), lambda x: A.T.dot(A.dot(x))
assert_array_almost_equal(
newton_cg(grad_hess, func, grad, x0, tol=1e-10),
fmin_ncg(f=func, x0=x0, fprime=grad, fhess_p=hess)
)
|
ryano144/intellij-community
|
refs/heads/master
|
python/lib/Lib/UserString.py
|
91
|
#!/usr/bin/env python
## vim:ts=4:et:nowrap
"""A user-defined wrapper around string objects
Note: string objects have grown methods in Python 1.6
This module requires Python 1.6 or later.
"""
import sys
__all__ = ["UserString","MutableString"]
class UserString:
def __init__(self, seq):
if isinstance(seq, basestring):
self.data = seq
elif isinstance(seq, UserString):
self.data = seq.data[:]
else:
self.data = str(seq)
def __str__(self): return str(self.data)
def __repr__(self): return repr(self.data)
def __int__(self): return int(self.data)
def __long__(self): return long(self.data)
def __float__(self): return float(self.data)
def __complex__(self): return complex(self.data)
def __hash__(self): return hash(self.data)
def __cmp__(self, string):
if isinstance(string, UserString):
return cmp(self.data, string.data)
else:
return cmp(self.data, string)
def __contains__(self, char):
return char in self.data
def __len__(self): return len(self.data)
def __getitem__(self, index): return self.__class__(self.data[index])
def __getslice__(self, start, end):
start = max(start, 0); end = max(end, 0)
return self.__class__(self.data[start:end])
def __add__(self, other):
if isinstance(other, UserString):
return self.__class__(self.data + other.data)
elif isinstance(other, basestring):
return self.__class__(self.data + other)
else:
return self.__class__(self.data + str(other))
def __radd__(self, other):
if isinstance(other, basestring):
return self.__class__(other + self.data)
else:
return self.__class__(str(other) + self.data)
def __mul__(self, n):
return self.__class__(self.data*n)
__rmul__ = __mul__
def __mod__(self, args):
return self.__class__(self.data % args)
# the following methods are defined in alphabetical order:
def capitalize(self): return self.__class__(self.data.capitalize())
def center(self, width, *args):
return self.__class__(self.data.center(width, *args))
def count(self, sub, start=0, end=sys.maxint):
return self.data.count(sub, start, end)
def decode(self, encoding=None, errors=None): # XXX improve this?
if encoding:
if errors:
return self.__class__(self.data.decode(encoding, errors))
else:
return self.__class__(self.data.decode(encoding))
else:
return self.__class__(self.data.decode())
def encode(self, encoding=None, errors=None): # XXX improve this?
if encoding:
if errors:
return self.__class__(self.data.encode(encoding, errors))
else:
return self.__class__(self.data.encode(encoding))
else:
return self.__class__(self.data.encode())
def endswith(self, suffix, start=0, end=sys.maxint):
return self.data.endswith(suffix, start, end)
def expandtabs(self, tabsize=8):
return self.__class__(self.data.expandtabs(tabsize))
def find(self, sub, start=0, end=sys.maxint):
return self.data.find(sub, start, end)
def index(self, sub, start=0, end=sys.maxint):
return self.data.index(sub, start, end)
def isalpha(self): return self.data.isalpha()
def isalnum(self): return self.data.isalnum()
def isdecimal(self): return self.data.isdecimal()
def isdigit(self): return self.data.isdigit()
def islower(self): return self.data.islower()
def isnumeric(self): return self.data.isnumeric()
def isspace(self): return self.data.isspace()
def istitle(self): return self.data.istitle()
def isupper(self): return self.data.isupper()
def join(self, seq): return self.data.join(seq)
def ljust(self, width, *args):
return self.__class__(self.data.ljust(width, *args))
def lower(self): return self.__class__(self.data.lower())
def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
def partition(self, sep):
return self.data.partition(sep)
def replace(self, old, new, maxsplit=-1):
return self.__class__(self.data.replace(old, new, maxsplit))
def rfind(self, sub, start=0, end=sys.maxint):
return self.data.rfind(sub, start, end)
def rindex(self, sub, start=0, end=sys.maxint):
return self.data.rindex(sub, start, end)
def rjust(self, width, *args):
return self.__class__(self.data.rjust(width, *args))
def rpartition(self, sep):
return self.data.rpartition(sep)
def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars))
def split(self, sep=None, maxsplit=-1):
return self.data.split(sep, maxsplit)
def rsplit(self, sep=None, maxsplit=-1):
return self.data.rsplit(sep, maxsplit)
def splitlines(self, keepends=0): return self.data.splitlines(keepends)
def startswith(self, prefix, start=0, end=sys.maxint):
return self.data.startswith(prefix, start, end)
def strip(self, chars=None): return self.__class__(self.data.strip(chars))
def swapcase(self): return self.__class__(self.data.swapcase())
def title(self): return self.__class__(self.data.title())
def translate(self, *args):
return self.__class__(self.data.translate(*args))
def upper(self): return self.__class__(self.data.upper())
def zfill(self, width): return self.__class__(self.data.zfill(width))
class MutableString(UserString):
"""mutable string objects
Python strings are immutable objects. This has the advantage, that
strings may be used as dictionary keys. If this property isn't needed
and you insist on changing string values in place instead, you may cheat
and use MutableString.
But the purpose of this class is an educational one: to prevent
people from inventing their own mutable string class derived
from UserString and than forget thereby to remove (override) the
__hash__ method inherited from UserString. This would lead to
errors that would be very hard to track down.
A faster and better solution is to rewrite your program using lists."""
def __init__(self, string=""):
self.data = string
def __hash__(self):
raise TypeError, "unhashable type (it is mutable)"
def __setitem__(self, index, sub):
if index < 0:
index += len(self.data)
if index < 0 or index >= len(self.data): raise IndexError
self.data = self.data[:index] + sub + self.data[index+1:]
def __delitem__(self, index):
if index < 0:
index += len(self.data)
if index < 0 or index >= len(self.data): raise IndexError
self.data = self.data[:index] + self.data[index+1:]
def __setslice__(self, start, end, sub):
start = max(start, 0); end = max(end, 0)
if isinstance(sub, UserString):
self.data = self.data[:start]+sub.data+self.data[end:]
elif isinstance(sub, basestring):
self.data = self.data[:start]+sub+self.data[end:]
else:
self.data = self.data[:start]+str(sub)+self.data[end:]
def __delslice__(self, start, end):
start = max(start, 0); end = max(end, 0)
self.data = self.data[:start] + self.data[end:]
def immutable(self):
return UserString(self.data)
def __iadd__(self, other):
if isinstance(other, UserString):
self.data += other.data
elif isinstance(other, basestring):
self.data += other
else:
self.data += str(other)
return self
def __imul__(self, n):
self.data *= n
return self
if __name__ == "__main__":
# execute the regression test to stdout, if called as a script:
import os
called_in_dir, called_as = os.path.split(sys.argv[0])
called_as, py = os.path.splitext(called_as)
if '-q' in sys.argv:
from test import test_support
test_support.verbose = 0
__import__('test.test_' + called_as.lower())
|
Benedicte/vibrational_motion
|
refs/heads/master
|
abavib.py
|
1
|
"""
Copyright (c) 2013-2014 Benedicte Ofstad
Distributed under the GNU Lesser General Public License v3.0.
For full terms see the file LICENSE.md.
"""
import read_input as ri
import Molecule as mol
import Propertyclasses as pr
import pydoc
"""
The module working as the interface of the command line based program.
Initiated the other modules and funcions needed to perform the
calculations requested.
"""
if __name__ == '__main__':
print("In order to calculate molecular properties, make sure to have made a directory named\
input_(molecule_name) where a copy of the MOLECULE.INP, hessian, and cubic_force_field\
files from DALTON are present. In addition to this a copy of the current propety run\
in DALTON is needed for every property which is to be calculated.")
print("")
print("")
molecule_name = raw_input('Which molecule should calculations be made for? (ex. h2o)')
if (molecule_name == ""):
molecule_name = "fluoromethane"
molecule_name = "fluoromethane"
dft = raw_input('at DFT or at HF level?')
#if(dft == "dft"):
molecule_name = "dft_" + molecule_name
molecule = mol.Molecule(molecule_name)
prop_name = raw_input('Which property should be calculated? For options enter "opt"')
if(prop_name == "opt"):
print("Dipole Moment")
print("Magnetizability")
print("g-factor")
print("Nuclear spin-rotation")
print("Molecular quadropole moment")
print("Spin-spin coupling")
print("Polarizability")
print("Nuclear shielding")
print("Nuclear spin correction")
print("Nuclear quadropole moment")
print("Optical rotation")
elif(prop_name == "Dipole Moment"):
prop = pr.Property_1_Tensor(molecule, prop_name)
elif(prop_name == "Magnetizability"):
prop = pr.Property_2_Tensor(molecule, prop_name)
elif(prop_name == "g-factor"):
prop = pr.Property_2_Tensor(molecule, prop_name)
elif(prop_name == "Nuclear spin-rotation"):
prop = pr.Property_3_Tensor(molecule, prop_name)
elif(prop_name == "Molecular quadropole moment"):
prop = pr.Property_2_Tensor(molecule, prop_name)
elif(prop_name == "Spin-spin coupling"):
prop = pr.Property_2_Tensor(molecule, prop_name)
elif(prop_name == "Polarizability"):
prop = pr.Polarizability(molecule, prop_name)
elif(prop_name == "Nuclear shielding"):
prop = pr.Property_3_Tensor(molecule, prop_name)
elif(prop_name == "Nuclear spin correction"):
prop = pr.Property_3_Tensor(molecule, prop_name)
elif(prop_name == "Nuclear quadropole moment"):
prop = pr.Property_3_Tensor(molecule, prop_name)
elif(prop_name == "Optical rotation"):
prop = pr.Property_2_Tensor(molecule, prop_name)
elif(prop_name == "all"):
prop = pr.Property_1_Tensor(molecule, "Dipole Moment")
prop()
prop = pr.Property_3_Tensor(molecule, "Nuclear spin-rotation")
prop()
prop = pr.Property_2_Tensor(molecule, "Molecular quadropole moment")
prop()
prop = pr.Property_3_Tensor(molecule, "Nuclear shielding")
prop()
prop = pr.Property_3_Tensor(molecule, "Nuclear quadropole moment")
else:
print ("Not a supported property")
prop()
|
MJafarMashhadi/django-rest-framework
|
refs/heads/master
|
rest_framework/utils/__init__.py
|
12133432
| |
thumbimigwe/echorizr
|
refs/heads/master
|
lib/python2.7/site-packages/django/conf/locale/fr/__init__.py
|
12133432
| |
harej/requestoid
|
refs/heads/master
|
migrations/__init__.py
|
12133432
| |
poldracklab/open_fmri
|
refs/heads/master
|
open_fmri/apps/dataset/migrations/0007_task_dataset.py
|
1
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dataset', '0006_auto_20151008_2052'),
]
operations = [
migrations.AddField(
model_name='task',
name='dataset',
field=models.ForeignKey(to='dataset.Dataset', default=1),
preserve_default=False,
),
]
|
SAug3n/burpPlatform
|
refs/heads/master
|
compoment/mysql_burp.py
|
1
|
# -*- coding: UTF-8 -*-
import MySQLdb
import burp
import logging
class mysql_burp(burp.burp):
def burp_thread(self,password):
if self.stop_signal:
return None
try:
db = MySQLdb.connect(host=self.target,port=self.port,user=self.now_user,passwd=password)
db.close()
self.result_pool[self.target+'_'+str(self.port)] = (self.now_user,password)
self.stop_signal = True
except Exception,e:
logging.error(e)
if __name__ == '__main__':
burp_test = mysql_burp()
burp_test.init_target('127.0.0.1',3306)
burp_test.init_uspw(['root'],['root'])
burp_test.start_burp()
burp_test.checkstate()
|
knorrium/firefox-ios
|
refs/heads/master
|
scripts/clean-xliff.py
|
41
|
#! /usr/bin/env python
#
# clean-xliff.py <l10n_folder>
#
# Remove targets from a locale, remove target-language attribute
#
from glob import glob
from lxml import etree
import argparse
import os
NS = {'x':'urn:oasis:names:tc:xliff:document:1.2'}
def indent(elem, level=0):
# Prettify XML output
# http://effbot.org/zone/element-lib.htm#prettyprint
i = '\n' + level*' '
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + ' '
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def main():
xliff_filename = 'firefox-ios.xliff'
parser = argparse.ArgumentParser()
parser.add_argument('l10n_folder', help='Path to locale folder to clean up')
args = parser.parse_args()
file_path = os.path.join(
os.path.realpath(args.l10n_folder),
xliff_filename
)
print 'Updating %s' % file_path
# Read localized file XML
locale_tree = etree.parse(file_path)
locale_root = locale_tree.getroot()
# Remove existing localizations and target-language
for trans_node in locale_root.xpath('//x:trans-unit', namespaces=NS):
for child in trans_node.xpath('./x:target', namespaces=NS):
child.getparent().remove(child)
# Remove target-language where defined
for file_node in locale_root.xpath('//x:file', namespaces=NS):
if file_node.get('target-language'):
file_node.attrib.pop('target-language')
# Replace the existing locale file with the new XML content
with open(file_path, 'w') as fp:
# Fix indentations
indent(locale_root)
xliff_content = etree.tostring(
locale_tree,
encoding='UTF-8',
xml_declaration=True,
pretty_print=True
)
fp.write(xliff_content)
if __name__ == '__main__':
main()
|
tfeagle/mitmproxy
|
refs/heads/master
|
test/tools/bench.py
|
41
|
from __future__ import print_function
import requests
import time
n = 100
url = "http://192.168.1.1/"
proxy = "http://192.168.1.115:8080/"
start = time.time()
for _ in range(n):
requests.get(url, allow_redirects=False, proxies=dict(http=proxy))
print(".", end="")
t_mitmproxy = time.time() - start
print("\r\nTotal time with mitmproxy: {}".format(t_mitmproxy))
start = time.time()
for _ in range(n):
requests.get(url, allow_redirects=False)
print(".", end="")
t_without = time.time() - start
print("\r\nTotal time without mitmproxy: {}".format(t_without))
|
0k/odoo
|
refs/heads/master
|
addons/point_of_sale/report/pos_invoice.py
|
317
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014-Today OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import osv
from openerp.tools.translate import _
class PosInvoiceReport(osv.AbstractModel):
_name = 'report.point_of_sale.report_invoice'
def render_html(self, cr, uid, ids, data=None, context=None):
report_obj = self.pool['report']
posorder_obj = self.pool['pos.order']
report = report_obj._get_report_from_name(cr, uid, 'account.report_invoice')
selected_orders = posorder_obj.browse(cr, uid, ids, context=context)
ids_to_print = []
invoiced_posorders_ids = []
for order in selected_orders:
if order.invoice_id:
ids_to_print.append(order.invoice_id.id)
invoiced_posorders_ids.append(order.id)
not_invoiced_orders_ids = list(set(ids) - set(invoiced_posorders_ids))
if not_invoiced_orders_ids:
not_invoiced_posorders = posorder_obj.browse(cr, uid, not_invoiced_orders_ids, context=context)
not_invoiced_orders_names = list(map(lambda a: a.name, not_invoiced_posorders))
raise osv.except_osv(_('Error!'), _('No link to an invoice for %s.' % ', '.join(not_invoiced_orders_names)))
docargs = {
'doc_ids': ids_to_print,
'doc_model': report.model,
'docs': selected_orders,
}
return report_obj.render(cr, uid, ids, 'account.report_invoice', docargs, context=context)
|
eecsu/BET
|
refs/heads/master
|
examples/validationExample/myModel.py
|
2
|
# Copyright (C) 2016 The BET Development Team
# -*- coding: utf-8 -*-
import numpy as np
# Define a model that is a linear QoI map
def my_model(parameter_samples):
Q_map = np.array([[0.506, 0.463], [0.253, 0.918]])
QoI_samples = np.dot(parameter_samples,Q_map)
return QoI_samples
|
moto-timo/ironpython3
|
refs/heads/master
|
Src/StdLib/Lib/distutils/dir_util.py
|
79
|
"""distutils.dir_util
Utility functions for manipulating directories and directory trees."""
import os
import errno
from distutils.errors import DistutilsFileError, DistutilsInternalError
from distutils import log
# cache for by mkpath() -- in addition to cheapening redundant calls,
# eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
_path_created = {}
# I don't use os.makedirs because a) it's new to Python 1.5.2, and
# b) it blows up if the directory already exists (I want to silently
# succeed in that case).
def mkpath(name, mode=0o777, verbose=1, dry_run=0):
"""Create a directory and any missing ancestor directories.
If the directory already exists (or if 'name' is the empty string, which
means the current directory, which of course exists), then do nothing.
Raise DistutilsFileError if unable to create some directory along the way
(eg. some sub-path exists, but is a file rather than a directory).
If 'verbose' is true, print a one-line summary of each mkdir to stdout.
Return the list of directories actually created.
"""
global _path_created
# Detect a common bug -- name is None
if not isinstance(name, str):
raise DistutilsInternalError(
"mkpath: 'name' must be a string (got %r)" % (name,))
# XXX what's the better way to handle verbosity? print as we create
# each directory in the path (the current behaviour), or only announce
# the creation of the whole path? (quite easy to do the latter since
# we're not using a recursive algorithm)
name = os.path.normpath(name)
created_dirs = []
if os.path.isdir(name) or name == '':
return created_dirs
if _path_created.get(os.path.abspath(name)):
return created_dirs
(head, tail) = os.path.split(name)
tails = [tail] # stack of lone dirs to create
while head and tail and not os.path.isdir(head):
(head, tail) = os.path.split(head)
tails.insert(0, tail) # push next higher dir onto stack
# now 'head' contains the deepest directory that already exists
# (that is, the child of 'head' in 'name' is the highest directory
# that does *not* exist)
for d in tails:
#print "head = %s, d = %s: " % (head, d),
head = os.path.join(head, d)
abs_head = os.path.abspath(head)
if _path_created.get(abs_head):
continue
if verbose >= 1:
log.info("creating %s", head)
if not dry_run:
try:
os.mkdir(head, mode)
except OSError as exc:
if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
raise DistutilsFileError(
"could not create '%s': %s" % (head, exc.args[-1]))
created_dirs.append(head)
_path_created[abs_head] = 1
return created_dirs
def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):
"""Create all the empty directories under 'base_dir' needed to put 'files'
there.
'base_dir' is just the name of a directory which doesn't necessarily
exist yet; 'files' is a list of filenames to be interpreted relative to
'base_dir'. 'base_dir' + the directory portion of every file in 'files'
will be created if it doesn't already exist. 'mode', 'verbose' and
'dry_run' flags are as for 'mkpath()'.
"""
# First get the list of directories to create
need_dir = set()
for file in files:
need_dir.add(os.path.join(base_dir, os.path.dirname(file)))
# Now create them
for dir in sorted(need_dir):
mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
preserve_symlinks=0, update=0, verbose=1, dry_run=0):
"""Copy an entire directory tree 'src' to a new location 'dst'.
Both 'src' and 'dst' must be directory names. If 'src' is not a
directory, raise DistutilsFileError. If 'dst' does not exist, it is
created with 'mkpath()'. The end result of the copy is that every
file in 'src' is copied to 'dst', and directories under 'src' are
recursively copied to 'dst'. Return the list of files that were
copied or might have been copied, using their output name. The
return value is unaffected by 'update' or 'dry_run': it is simply
the list of all files under 'src', with the names changed to be
under 'dst'.
'preserve_mode' and 'preserve_times' are the same as for
'copy_file'; note that they only apply to regular files, not to
directories. If 'preserve_symlinks' is true, symlinks will be
copied as symlinks (on platforms that support them!); otherwise
(the default), the destination of the symlink will be copied.
'update' and 'verbose' are the same as for 'copy_file'.
"""
from distutils.file_util import copy_file
if not dry_run and not os.path.isdir(src):
raise DistutilsFileError(
"cannot copy tree '%s': not a directory" % src)
try:
names = os.listdir(src)
except OSError as e:
if dry_run:
names = []
else:
raise DistutilsFileError(
"error listing files in '%s': %s" % (src, e.strerror))
if not dry_run:
mkpath(dst, verbose=verbose)
outputs = []
for n in names:
src_name = os.path.join(src, n)
dst_name = os.path.join(dst, n)
if n.startswith('.nfs'):
# skip NFS rename files
continue
if preserve_symlinks and os.path.islink(src_name):
link_dest = os.readlink(src_name)
if verbose >= 1:
log.info("linking %s -> %s", dst_name, link_dest)
if not dry_run:
os.symlink(link_dest, dst_name)
outputs.append(dst_name)
elif os.path.isdir(src_name):
outputs.extend(
copy_tree(src_name, dst_name, preserve_mode,
preserve_times, preserve_symlinks, update,
verbose=verbose, dry_run=dry_run))
else:
copy_file(src_name, dst_name, preserve_mode,
preserve_times, update, verbose=verbose,
dry_run=dry_run)
outputs.append(dst_name)
return outputs
def _build_cmdtuple(path, cmdtuples):
"""Helper for remove_tree()."""
for f in os.listdir(path):
real_f = os.path.join(path,f)
if os.path.isdir(real_f) and not os.path.islink(real_f):
_build_cmdtuple(real_f, cmdtuples)
else:
cmdtuples.append((os.remove, real_f))
cmdtuples.append((os.rmdir, path))
def remove_tree(directory, verbose=1, dry_run=0):
"""Recursively remove an entire directory tree.
Any errors are ignored (apart from being reported to stdout if 'verbose'
is true).
"""
global _path_created
if verbose >= 1:
log.info("removing '%s' (and everything under it)", directory)
if dry_run:
return
cmdtuples = []
_build_cmdtuple(directory, cmdtuples)
for cmd in cmdtuples:
try:
cmd[0](cmd[1])
# remove dir from cache if it's already there
abspath = os.path.abspath(cmd[1])
if abspath in _path_created:
del _path_created[abspath]
except OSError as exc:
log.warn("error removing %s: %s", directory, exc)
def ensure_relative(path):
"""Take the full path 'path', and make it a relative path.
This is useful to make 'path' the second argument to os.path.join().
"""
drive, path = os.path.splitdrive(path)
if path[0:1] == os.sep:
path = drive + path[1:]
return path
|
jjp9624022/angularFlaskBlog
|
refs/heads/master
|
server/app/__init__.py
|
12133432
| |
DNFcode/edx-platform
|
refs/heads/master
|
common/djangoapps/student/management/commands/transfer_students.py
|
108
|
"""
Transfer Student Management Command
"""
from django.db import transaction
from opaque_keys.edx.keys import CourseKey
from optparse import make_option
from django.contrib.auth.models import User
from student.models import CourseEnrollment
from shoppingcart.models import CertificateItem
from track.management.tracked_command import TrackedCommand
class TransferStudentError(Exception):
"""Generic Error when handling student transfers."""
pass
class Command(TrackedCommand):
"""Management Command for transferring students from one course to new courses."""
help = """
This command takes two course ids as input and transfers
all students enrolled in one course into the other. This will
remove them from the first class and enroll them in the specified
class(es) in the same mode as the first one. eg. honor, verified,
audit.
example:
# Transfer students from the old demoX class to a new one.
manage.py ... transfer_students -f edX/Open_DemoX/edx_demo_course -t edX/Open_DemoX/new_demoX
# Transfer students from old course to new, with original certificate items.
manage.py ... transfer_students -f edX/Open_DemoX/edx_demo_course -t edX/Open_DemoX/new_demoX -c true
# Transfer students from the old demoX class into two new classes.
manage.py ... transfer_students -f edX/Open_DemoX/edx_demo_course
-t edX/Open_DemoX/new_demoX,edX/Open_DemoX/edX_Insider
"""
option_list = TrackedCommand.option_list + (
make_option('-f', '--from',
metavar='SOURCE_COURSE',
dest='source_course',
help='The course to transfer students from.'),
make_option('-t', '--to',
metavar='DEST_COURSE_LIST',
dest='dest_course_list',
help='The new course(es) to enroll the student into.'),
make_option('-c', '--transfer-certificates',
metavar='TRANSFER_CERTIFICATES',
dest='transfer_certificates',
help="If True, try to transfer certificate items to the new course.")
)
@transaction.commit_manually
def handle(self, *args, **options): # pylint: disable=unused-argument
source_key = CourseKey.from_string(options.get('source_course', ''))
dest_keys = []
for course_key in options.get('dest_course_list', '').split(','):
dest_keys.append(CourseKey.from_string(course_key))
if not source_key or not dest_keys:
raise TransferStudentError(u"Must have a source course and destination course specified.")
tc_option = options.get('transfer_certificates', '')
transfer_certificates = ('true' == tc_option.lower()) if tc_option else False
if transfer_certificates and len(dest_keys) != 1:
raise TransferStudentError(u"Cannot transfer certificate items from one course to many.")
source_students = User.objects.filter(
courseenrollment__course_id=source_key
)
for user in source_students:
with transaction.commit_on_success():
print("Moving {}.".format(user.username))
# Find the old enrollment.
enrollment = CourseEnrollment.objects.get(
user=user,
course_id=source_key
)
# Move the Student between the classes.
mode = enrollment.mode
old_is_active = enrollment.is_active
CourseEnrollment.unenroll(user, source_key, skip_refund=True)
print(u"Unenrolled {} from {}".format(user.username, unicode(source_key)))
for dest_key in dest_keys:
if CourseEnrollment.is_enrolled(user, dest_key):
# Un Enroll from source course but don't mess
# with the enrollment in the destination course.
msg = u"Skipping {}, already enrolled in destination course {}"
print(msg.format(user.username, unicode(dest_key)))
else:
new_enrollment = CourseEnrollment.enroll(user, dest_key, mode=mode)
# Un-enroll from the new course if the user had un-enrolled
# form the old course.
if not old_is_active:
new_enrollment.update_enrollment(is_active=False, skip_refund=True)
if transfer_certificates:
self._transfer_certificate_item(source_key, enrollment, user, dest_keys, new_enrollment)
@staticmethod
def _transfer_certificate_item(source_key, enrollment, user, dest_keys, new_enrollment):
""" Transfer the certificate item from one course to another.
Do not use this generally, since certificate items are directly associated with a particular purchase.
This should only be used when a single course to a new location. This cannot be used when transferring
from one course to many.
Args:
source_key (str): The course key string representation for the original course.
enrollment (CourseEnrollment): The original enrollment to move the certificate item from.
user (User): The user to transfer the item for.
dest_keys (list): A list of course key strings to transfer the item to.
new_enrollment (CourseEnrollment): The new enrollment to associate the certificate item with.
Returns:
None
"""
try:
certificate_item = CertificateItem.objects.get(
course_id=source_key,
course_enrollment=enrollment
)
except CertificateItem.DoesNotExist:
print(u"No certificate for {}".format(user))
return
certificate_item.course_id = dest_keys[0]
certificate_item.course_enrollment = new_enrollment
|
DaniilLeksin/gc
|
refs/heads/master
|
wx/richtext.py
|
1
|
# This file was created automatically by SWIG 1.3.29.
# Don't modify this file, modify the SWIG interface instead.
import _richtext
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 _windows
import _core
import _controls
wx = _core
__docfilter__ = wx.__DocFilter(globals())
#---------------------------------------------------------------------------
RICHTEXT_TYPE_ANY = _richtext.RICHTEXT_TYPE_ANY
RICHTEXT_TYPE_TEXT = _richtext.RICHTEXT_TYPE_TEXT
RICHTEXT_TYPE_XML = _richtext.RICHTEXT_TYPE_XML
RICHTEXT_TYPE_HTML = _richtext.RICHTEXT_TYPE_HTML
RICHTEXT_TYPE_RTF = _richtext.RICHTEXT_TYPE_RTF
RICHTEXT_TYPE_PDF = _richtext.RICHTEXT_TYPE_PDF
RICHTEXT_FIXED_WIDTH = _richtext.RICHTEXT_FIXED_WIDTH
RICHTEXT_FIXED_HEIGHT = _richtext.RICHTEXT_FIXED_HEIGHT
RICHTEXT_VARIABLE_WIDTH = _richtext.RICHTEXT_VARIABLE_WIDTH
RICHTEXT_VARIABLE_HEIGHT = _richtext.RICHTEXT_VARIABLE_HEIGHT
RICHTEXT_LAYOUT_SPECIFIED_RECT = _richtext.RICHTEXT_LAYOUT_SPECIFIED_RECT
RICHTEXT_DRAW_IGNORE_CACHE = _richtext.RICHTEXT_DRAW_IGNORE_CACHE
RICHTEXT_FORMATTED = _richtext.RICHTEXT_FORMATTED
RICHTEXT_UNFORMATTED = _richtext.RICHTEXT_UNFORMATTED
RICHTEXT_CACHE_SIZE = _richtext.RICHTEXT_CACHE_SIZE
RICHTEXT_HEIGHT_ONLY = _richtext.RICHTEXT_HEIGHT_ONLY
RICHTEXT_SETSTYLE_NONE = _richtext.RICHTEXT_SETSTYLE_NONE
RICHTEXT_SETSTYLE_WITH_UNDO = _richtext.RICHTEXT_SETSTYLE_WITH_UNDO
RICHTEXT_SETSTYLE_OPTIMIZE = _richtext.RICHTEXT_SETSTYLE_OPTIMIZE
RICHTEXT_SETSTYLE_PARAGRAPHS_ONLY = _richtext.RICHTEXT_SETSTYLE_PARAGRAPHS_ONLY
RICHTEXT_SETSTYLE_CHARACTERS_ONLY = _richtext.RICHTEXT_SETSTYLE_CHARACTERS_ONLY
RICHTEXT_SETSTYLE_RENUMBER = _richtext.RICHTEXT_SETSTYLE_RENUMBER
RICHTEXT_SETSTYLE_SPECIFY_LEVEL = _richtext.RICHTEXT_SETSTYLE_SPECIFY_LEVEL
RICHTEXT_SETSTYLE_RESET = _richtext.RICHTEXT_SETSTYLE_RESET
RICHTEXT_SETSTYLE_REMOVE = _richtext.RICHTEXT_SETSTYLE_REMOVE
RICHTEXT_INSERT_NONE = _richtext.RICHTEXT_INSERT_NONE
RICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE = _richtext.RICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE
RICHTEXT_INSERT_INTERACTIVE = _richtext.RICHTEXT_INSERT_INTERACTIVE
TEXT_ATTR_KEEP_FIRST_PARA_STYLE = _richtext.TEXT_ATTR_KEEP_FIRST_PARA_STYLE
RICHTEXT_HITTEST_NONE = _richtext.RICHTEXT_HITTEST_NONE
RICHTEXT_HITTEST_BEFORE = _richtext.RICHTEXT_HITTEST_BEFORE
RICHTEXT_HITTEST_AFTER = _richtext.RICHTEXT_HITTEST_AFTER
RICHTEXT_HITTEST_ON = _richtext.RICHTEXT_HITTEST_ON
RICHTEXT_HITTEST_OUTSIDE = _richtext.RICHTEXT_HITTEST_OUTSIDE
RICHTEXT_HITTEST_NO_NESTED_OBJECTS = _richtext.RICHTEXT_HITTEST_NO_NESTED_OBJECTS
RICHTEXT_HITTEST_NO_FLOATING_OBJECTS = _richtext.RICHTEXT_HITTEST_NO_FLOATING_OBJECTS
TEXT_BOX_ATTR_FLOAT = _richtext.TEXT_BOX_ATTR_FLOAT
TEXT_BOX_ATTR_CLEAR = _richtext.TEXT_BOX_ATTR_CLEAR
TEXT_BOX_ATTR_COLLAPSE_BORDERS = _richtext.TEXT_BOX_ATTR_COLLAPSE_BORDERS
TEXT_BOX_ATTR_VERTICAL_ALIGNMENT = _richtext.TEXT_BOX_ATTR_VERTICAL_ALIGNMENT
TEXT_BOX_ATTR_BOX_STYLE_NAME = _richtext.TEXT_BOX_ATTR_BOX_STYLE_NAME
TEXT_ATTR_UNITS_TENTHS_MM = _richtext.TEXT_ATTR_UNITS_TENTHS_MM
TEXT_ATTR_UNITS_PIXELS = _richtext.TEXT_ATTR_UNITS_PIXELS
TEXT_ATTR_UNITS_PERCENTAGE = _richtext.TEXT_ATTR_UNITS_PERCENTAGE
TEXT_ATTR_UNITS_POINTS = _richtext.TEXT_ATTR_UNITS_POINTS
TEXT_ATTR_UNITS_MASK = _richtext.TEXT_ATTR_UNITS_MASK
TEXT_BOX_ATTR_POSITION_STATIC = _richtext.TEXT_BOX_ATTR_POSITION_STATIC
TEXT_BOX_ATTR_POSITION_RELATIVE = _richtext.TEXT_BOX_ATTR_POSITION_RELATIVE
TEXT_BOX_ATTR_POSITION_ABSOLUTE = _richtext.TEXT_BOX_ATTR_POSITION_ABSOLUTE
TEXT_BOX_ATTR_POSITION_MASK = _richtext.TEXT_BOX_ATTR_POSITION_MASK
#---------------------------------------------------------------------------
class TextAttrDimension(object):
"""Proxy of C++ TextAttrDimension 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) -> TextAttrDimension
__init__(self, int value, int units=TEXT_ATTR_UNITS_TENTHS_MM) -> TextAttrDimension
"""
_richtext.TextAttrDimension_swiginit(self,_richtext.new_TextAttrDimension(*args))
__swig_destroy__ = _richtext.delete_TextAttrDimension
__del__ = lambda self : None;
def Reset(*args, **kwargs):
"""Reset(self)"""
return _richtext.TextAttrDimension_Reset(*args, **kwargs)
def EqPartial(*args, **kwargs):
"""EqPartial(self, TextAttrDimension dim) -> bool"""
return _richtext.TextAttrDimension_EqPartial(*args, **kwargs)
def Apply(*args, **kwargs):
"""Apply(self, TextAttrDimension dim, TextAttrDimension compareWith=None) -> bool"""
return _richtext.TextAttrDimension_Apply(*args, **kwargs)
def CollectCommonAttributes(*args, **kwargs):
"""
CollectCommonAttributes(self, TextAttrDimension attr, TextAttrDimension clashingAttr,
TextAttrDimension absentAttr)
"""
return _richtext.TextAttrDimension_CollectCommonAttributes(*args, **kwargs)
def __eq__(*args, **kwargs):
"""__eq__(self, TextAttrDimension dim) -> bool"""
return _richtext.TextAttrDimension___eq__(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> int"""
return _richtext.TextAttrDimension_GetValue(*args, **kwargs)
def GetValueMM(*args, **kwargs):
"""GetValueMM(self) -> float"""
return _richtext.TextAttrDimension_GetValueMM(*args, **kwargs)
def SetValueMM(*args, **kwargs):
"""SetValueMM(self, float value)"""
return _richtext.TextAttrDimension_SetValueMM(*args, **kwargs)
def SetValue(*args):
"""
SetValue(self, int value)
SetValue(self, int value, TextAttrDimensionFlags flags)
SetValue(self, TextAttrDimension dim)
"""
return _richtext.TextAttrDimension_SetValue(*args)
def GetUnits(*args, **kwargs):
"""GetUnits(self) -> int"""
return _richtext.TextAttrDimension_GetUnits(*args, **kwargs)
def SetUnits(*args, **kwargs):
"""SetUnits(self, int units)"""
return _richtext.TextAttrDimension_SetUnits(*args, **kwargs)
def GetPosition(*args, **kwargs):
"""GetPosition(self) -> int"""
return _richtext.TextAttrDimension_GetPosition(*args, **kwargs)
def SetPosition(*args, **kwargs):
"""SetPosition(self, int pos)"""
return _richtext.TextAttrDimension_SetPosition(*args, **kwargs)
def GetFlags(*args, **kwargs):
"""GetFlags(self) -> TextAttrDimensionFlags"""
return _richtext.TextAttrDimension_GetFlags(*args, **kwargs)
def SetFlags(*args, **kwargs):
"""SetFlags(self, TextAttrDimensionFlags flags)"""
return _richtext.TextAttrDimension_SetFlags(*args, **kwargs)
m_value = property(_richtext.TextAttrDimension_m_value_get, _richtext.TextAttrDimension_m_value_set)
m_flags = property(_richtext.TextAttrDimension_m_flags_get, _richtext.TextAttrDimension_m_flags_set)
_richtext.TextAttrDimension_swigregister(TextAttrDimension)
class TextAttrDimensions(object):
"""Proxy of C++ TextAttrDimensions 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) -> TextAttrDimensions"""
_richtext.TextAttrDimensions_swiginit(self,_richtext.new_TextAttrDimensions(*args, **kwargs))
__swig_destroy__ = _richtext.delete_TextAttrDimensions
__del__ = lambda self : None;
def Reset(*args, **kwargs):
"""Reset(self)"""
return _richtext.TextAttrDimensions_Reset(*args, **kwargs)
def __eq__(*args, **kwargs):
"""__eq__(self, TextAttrDimensions dims) -> bool"""
return _richtext.TextAttrDimensions___eq__(*args, **kwargs)
def EqPartial(*args, **kwargs):
"""EqPartial(self, TextAttrDimensions dims) -> bool"""
return _richtext.TextAttrDimensions_EqPartial(*args, **kwargs)
def Apply(*args, **kwargs):
"""Apply(self, TextAttrDimensions dims, TextAttrDimensions compareWith=None) -> bool"""
return _richtext.TextAttrDimensions_Apply(*args, **kwargs)
def CollectCommonAttributes(*args, **kwargs):
"""
CollectCommonAttributes(self, TextAttrDimensions attr, TextAttrDimensions clashingAttr,
TextAttrDimensions absentAttr)
"""
return _richtext.TextAttrDimensions_CollectCommonAttributes(*args, **kwargs)
def RemoveStyle(*args, **kwargs):
"""RemoveStyle(self, TextAttrDimensions attr) -> bool"""
return _richtext.TextAttrDimensions_RemoveStyle(*args, **kwargs)
def GetLeft(*args, **kwargs):
"""GetLeft(self) -> TextAttrDimension"""
return _richtext.TextAttrDimensions_GetLeft(*args, **kwargs)
def GetRight(*args, **kwargs):
"""GetRight(self) -> TextAttrDimension"""
return _richtext.TextAttrDimensions_GetRight(*args, **kwargs)
def GetTop(*args, **kwargs):
"""GetTop(self) -> TextAttrDimension"""
return _richtext.TextAttrDimensions_GetTop(*args, **kwargs)
def GetBottom(*args, **kwargs):
"""GetBottom(self) -> TextAttrDimension"""
return _richtext.TextAttrDimensions_GetBottom(*args, **kwargs)
def IsValid(*args, **kwargs):
"""IsValid(self) -> bool"""
return _richtext.TextAttrDimensions_IsValid(*args, **kwargs)
m_left = property(_richtext.TextAttrDimensions_m_left_get, _richtext.TextAttrDimensions_m_left_set)
m_top = property(_richtext.TextAttrDimensions_m_top_get, _richtext.TextAttrDimensions_m_top_set)
m_right = property(_richtext.TextAttrDimensions_m_right_get, _richtext.TextAttrDimensions_m_right_set)
m_bottom = property(_richtext.TextAttrDimensions_m_bottom_get, _richtext.TextAttrDimensions_m_bottom_set)
_richtext.TextAttrDimensions_swigregister(TextAttrDimensions)
class TextAttrDimensionConverter(object):
"""Proxy of C++ TextAttrDimensionConverter 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, DC dc, double scale=1.0, Size parentSize=DefaultSize) -> TextAttrDimensionConverter
__init__(self, int ppi, double scale=1.0, Size parentSize=DefaultSize) -> TextAttrDimensionConverter
"""
_richtext.TextAttrDimensionConverter_swiginit(self,_richtext.new_TextAttrDimensionConverter(*args))
__swig_destroy__ = _richtext.delete_TextAttrDimensionConverter
__del__ = lambda self : None;
def GetPixels(*args, **kwargs):
"""GetPixels(self, TextAttrDimension dim, int direction=HORIZONTAL) -> int"""
return _richtext.TextAttrDimensionConverter_GetPixels(*args, **kwargs)
def GetTenthsMM(*args, **kwargs):
"""GetTenthsMM(self, TextAttrDimension dim) -> int"""
return _richtext.TextAttrDimensionConverter_GetTenthsMM(*args, **kwargs)
def ConvertTenthsMMToPixels(*args, **kwargs):
"""ConvertTenthsMMToPixels(self, int units) -> int"""
return _richtext.TextAttrDimensionConverter_ConvertTenthsMMToPixels(*args, **kwargs)
def ConvertPixelsToTenthsMM(*args, **kwargs):
"""ConvertPixelsToTenthsMM(self, int pixels) -> int"""
return _richtext.TextAttrDimensionConverter_ConvertPixelsToTenthsMM(*args, **kwargs)
m_ppi = property(_richtext.TextAttrDimensionConverter_m_ppi_get, _richtext.TextAttrDimensionConverter_m_ppi_set)
m_scale = property(_richtext.TextAttrDimensionConverter_m_scale_get, _richtext.TextAttrDimensionConverter_m_scale_set)
m_parentSize = property(_richtext.TextAttrDimensionConverter_m_parentSize_get, _richtext.TextAttrDimensionConverter_m_parentSize_set)
_richtext.TextAttrDimensionConverter_swigregister(TextAttrDimensionConverter)
TEXT_BOX_ATTR_BORDER_NONE = _richtext.TEXT_BOX_ATTR_BORDER_NONE
TEXT_BOX_ATTR_BORDER_SOLID = _richtext.TEXT_BOX_ATTR_BORDER_SOLID
TEXT_BOX_ATTR_BORDER_DOTTED = _richtext.TEXT_BOX_ATTR_BORDER_DOTTED
TEXT_BOX_ATTR_BORDER_DASHED = _richtext.TEXT_BOX_ATTR_BORDER_DASHED
TEXT_BOX_ATTR_BORDER_DOUBLE = _richtext.TEXT_BOX_ATTR_BORDER_DOUBLE
TEXT_BOX_ATTR_BORDER_GROOVE = _richtext.TEXT_BOX_ATTR_BORDER_GROOVE
TEXT_BOX_ATTR_BORDER_RIDGE = _richtext.TEXT_BOX_ATTR_BORDER_RIDGE
TEXT_BOX_ATTR_BORDER_INSET = _richtext.TEXT_BOX_ATTR_BORDER_INSET
TEXT_BOX_ATTR_BORDER_OUTSET = _richtext.TEXT_BOX_ATTR_BORDER_OUTSET
TEXT_BOX_ATTR_BORDER_STYLE = _richtext.TEXT_BOX_ATTR_BORDER_STYLE
TEXT_BOX_ATTR_BORDER_COLOUR = _richtext.TEXT_BOX_ATTR_BORDER_COLOUR
TEXT_BOX_ATTR_BORDER_THIN = _richtext.TEXT_BOX_ATTR_BORDER_THIN
TEXT_BOX_ATTR_BORDER_MEDIUM = _richtext.TEXT_BOX_ATTR_BORDER_MEDIUM
TEXT_BOX_ATTR_BORDER_THICK = _richtext.TEXT_BOX_ATTR_BORDER_THICK
TEXT_BOX_ATTR_FLOAT_NONE = _richtext.TEXT_BOX_ATTR_FLOAT_NONE
TEXT_BOX_ATTR_FLOAT_LEFT = _richtext.TEXT_BOX_ATTR_FLOAT_LEFT
TEXT_BOX_ATTR_FLOAT_RIGHT = _richtext.TEXT_BOX_ATTR_FLOAT_RIGHT
TEXT_BOX_ATTR_CLEAR_NONE = _richtext.TEXT_BOX_ATTR_CLEAR_NONE
TEXT_BOX_ATTR_CLEAR_LEFT = _richtext.TEXT_BOX_ATTR_CLEAR_LEFT
TEXT_BOX_ATTR_CLEAR_RIGHT = _richtext.TEXT_BOX_ATTR_CLEAR_RIGHT
TEXT_BOX_ATTR_CLEAR_BOTH = _richtext.TEXT_BOX_ATTR_CLEAR_BOTH
TEXT_BOX_ATTR_COLLAPSE_NONE = _richtext.TEXT_BOX_ATTR_COLLAPSE_NONE
TEXT_BOX_ATTR_COLLAPSE_FULL = _richtext.TEXT_BOX_ATTR_COLLAPSE_FULL
TEXT_BOX_ATTR_VERTICAL_ALIGNMENT_NONE = _richtext.TEXT_BOX_ATTR_VERTICAL_ALIGNMENT_NONE
TEXT_BOX_ATTR_VERTICAL_ALIGNMENT_TOP = _richtext.TEXT_BOX_ATTR_VERTICAL_ALIGNMENT_TOP
TEXT_BOX_ATTR_VERTICAL_ALIGNMENT_CENTRE = _richtext.TEXT_BOX_ATTR_VERTICAL_ALIGNMENT_CENTRE
TEXT_BOX_ATTR_VERTICAL_ALIGNMENT_BOTTOM = _richtext.TEXT_BOX_ATTR_VERTICAL_ALIGNMENT_BOTTOM
class TextAttrBorder(object):
"""Proxy of C++ TextAttrBorder 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) -> TextAttrBorder"""
_richtext.TextAttrBorder_swiginit(self,_richtext.new_TextAttrBorder(*args, **kwargs))
def __eq__(*args, **kwargs):
"""__eq__(self, TextAttrBorder border) -> bool"""
return _richtext.TextAttrBorder___eq__(*args, **kwargs)
def Reset(*args, **kwargs):
"""Reset(self)"""
return _richtext.TextAttrBorder_Reset(*args, **kwargs)
def EqPartial(*args, **kwargs):
"""EqPartial(self, TextAttrBorder border) -> bool"""
return _richtext.TextAttrBorder_EqPartial(*args, **kwargs)
def Apply(*args, **kwargs):
"""Apply(self, TextAttrBorder border, TextAttrBorder compareWith=None) -> bool"""
return _richtext.TextAttrBorder_Apply(*args, **kwargs)
def RemoveStyle(*args, **kwargs):
"""RemoveStyle(self, TextAttrBorder attr) -> bool"""
return _richtext.TextAttrBorder_RemoveStyle(*args, **kwargs)
def CollectCommonAttributes(*args, **kwargs):
"""CollectCommonAttributes(self, TextAttrBorder attr, TextAttrBorder clashingAttr, TextAttrBorder absentAttr)"""
return _richtext.TextAttrBorder_CollectCommonAttributes(*args, **kwargs)
def SetStyle(*args, **kwargs):
"""SetStyle(self, int style)"""
return _richtext.TextAttrBorder_SetStyle(*args, **kwargs)
def GetStyle(*args, **kwargs):
"""GetStyle(self) -> int"""
return _richtext.TextAttrBorder_GetStyle(*args, **kwargs)
def SetColour(*args):
"""
SetColour(self, unsigned long colour)
SetColour(self, Colour colour)
"""
return _richtext.TextAttrBorder_SetColour(*args)
def GetColourLong(*args, **kwargs):
"""GetColourLong(self) -> unsigned long"""
return _richtext.TextAttrBorder_GetColourLong(*args, **kwargs)
def GetColour(*args, **kwargs):
"""GetColour(self) -> Colour"""
return _richtext.TextAttrBorder_GetColour(*args, **kwargs)
def GetWidth(*args):
"""
GetWidth(self) -> TextAttrDimension
GetWidth(self) -> TextAttrDimension
"""
return _richtext.TextAttrBorder_GetWidth(*args)
def SetWidth(*args):
"""
SetWidth(self, TextAttrDimension width)
SetWidth(self, int value, int units=TEXT_ATTR_UNITS_TENTHS_MM)
"""
return _richtext.TextAttrBorder_SetWidth(*args)
def HasStyle(*args, **kwargs):
"""HasStyle(self) -> bool"""
return _richtext.TextAttrBorder_HasStyle(*args, **kwargs)
def HasColour(*args, **kwargs):
"""HasColour(self) -> bool"""
return _richtext.TextAttrBorder_HasColour(*args, **kwargs)
def HasWidth(*args, **kwargs):
"""HasWidth(self) -> bool"""
return _richtext.TextAttrBorder_HasWidth(*args, **kwargs)
def IsValid(*args, **kwargs):
"""IsValid(self) -> bool"""
return _richtext.TextAttrBorder_IsValid(*args, **kwargs)
def MakeValid(*args, **kwargs):
"""MakeValid(self)"""
return _richtext.TextAttrBorder_MakeValid(*args, **kwargs)
def GetFlags(*args, **kwargs):
"""GetFlags(self) -> int"""
return _richtext.TextAttrBorder_GetFlags(*args, **kwargs)
def SetFlags(*args, **kwargs):
"""SetFlags(self, int flags)"""
return _richtext.TextAttrBorder_SetFlags(*args, **kwargs)
def AddFlag(*args, **kwargs):
"""AddFlag(self, int flag)"""
return _richtext.TextAttrBorder_AddFlag(*args, **kwargs)
def RemoveFlag(*args, **kwargs):
"""RemoveFlag(self, int flag)"""
return _richtext.TextAttrBorder_RemoveFlag(*args, **kwargs)
m_borderStyle = property(_richtext.TextAttrBorder_m_borderStyle_get, _richtext.TextAttrBorder_m_borderStyle_set)
m_borderColour = property(_richtext.TextAttrBorder_m_borderColour_get, _richtext.TextAttrBorder_m_borderColour_set)
m_borderWidth = property(_richtext.TextAttrBorder_m_borderWidth_get, _richtext.TextAttrBorder_m_borderWidth_set)
m_flags = property(_richtext.TextAttrBorder_m_flags_get, _richtext.TextAttrBorder_m_flags_set)
_richtext.TextAttrBorder_swigregister(TextAttrBorder)
class TextAttrBorders(object):
"""Proxy of C++ TextAttrBorders 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) -> TextAttrBorders"""
_richtext.TextAttrBorders_swiginit(self,_richtext.new_TextAttrBorders(*args, **kwargs))
def __eq__(*args, **kwargs):
"""__eq__(self, TextAttrBorders borders) -> bool"""
return _richtext.TextAttrBorders___eq__(*args, **kwargs)
def SetStyle(*args, **kwargs):
"""SetStyle(self, int style)"""
return _richtext.TextAttrBorders_SetStyle(*args, **kwargs)
def SetColour(*args):
"""
SetColour(self, unsigned long colour)
SetColour(self, Colour colour)
"""
return _richtext.TextAttrBorders_SetColour(*args)
def SetWidth(*args):
"""
SetWidth(self, TextAttrDimension width)
SetWidth(self, int value, int units=TEXT_ATTR_UNITS_TENTHS_MM)
"""
return _richtext.TextAttrBorders_SetWidth(*args)
def Reset(*args, **kwargs):
"""Reset(self)"""
return _richtext.TextAttrBorders_Reset(*args, **kwargs)
def EqPartial(*args, **kwargs):
"""EqPartial(self, TextAttrBorders borders) -> bool"""
return _richtext.TextAttrBorders_EqPartial(*args, **kwargs)
def Apply(*args, **kwargs):
"""Apply(self, TextAttrBorders borders, TextAttrBorders compareWith=None) -> bool"""
return _richtext.TextAttrBorders_Apply(*args, **kwargs)
def RemoveStyle(*args, **kwargs):
"""RemoveStyle(self, TextAttrBorders attr) -> bool"""
return _richtext.TextAttrBorders_RemoveStyle(*args, **kwargs)
def CollectCommonAttributes(*args, **kwargs):
"""
CollectCommonAttributes(self, TextAttrBorders attr, TextAttrBorders clashingAttr,
TextAttrBorders absentAttr)
"""
return _richtext.TextAttrBorders_CollectCommonAttributes(*args, **kwargs)
def IsValid(*args, **kwargs):
"""IsValid(self) -> bool"""
return _richtext.TextAttrBorders_IsValid(*args, **kwargs)
def GetLeft(*args):
"""
GetLeft(self) -> TextAttrBorder
GetLeft(self) -> TextAttrBorder
"""
return _richtext.TextAttrBorders_GetLeft(*args)
def GetRight(*args):
"""
GetRight(self) -> TextAttrBorder
GetRight(self) -> TextAttrBorder
"""
return _richtext.TextAttrBorders_GetRight(*args)
def GetTop(*args):
"""
GetTop(self) -> TextAttrBorder
GetTop(self) -> TextAttrBorder
"""
return _richtext.TextAttrBorders_GetTop(*args)
def GetBottom(*args):
"""
GetBottom(self) -> TextAttrBorder
GetBottom(self) -> TextAttrBorder
"""
return _richtext.TextAttrBorders_GetBottom(*args)
m_left = property(_richtext.TextAttrBorders_m_left_get, _richtext.TextAttrBorders_m_left_set)
m_right = property(_richtext.TextAttrBorders_m_right_get, _richtext.TextAttrBorders_m_right_set)
m_top = property(_richtext.TextAttrBorders_m_top_get, _richtext.TextAttrBorders_m_top_set)
m_bottom = property(_richtext.TextAttrBorders_m_bottom_get, _richtext.TextAttrBorders_m_bottom_set)
_richtext.TextAttrBorders_swigregister(TextAttrBorders)
class TextBoxAttr(object):
"""Proxy of C++ TextBoxAttr 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) -> TextBoxAttr
__init__(self, TextBoxAttr attr) -> TextBoxAttr
"""
_richtext.TextBoxAttr_swiginit(self,_richtext.new_TextBoxAttr(*args))
def Init(*args, **kwargs):
"""Init(self)"""
return _richtext.TextBoxAttr_Init(*args, **kwargs)
def Reset(*args, **kwargs):
"""Reset(self)"""
return _richtext.TextBoxAttr_Reset(*args, **kwargs)
def __eq__(*args, **kwargs):
"""__eq__(self, TextBoxAttr attr) -> bool"""
return _richtext.TextBoxAttr___eq__(*args, **kwargs)
def EqPartial(*args, **kwargs):
"""EqPartial(self, TextBoxAttr attr) -> bool"""
return _richtext.TextBoxAttr_EqPartial(*args, **kwargs)
def Apply(*args, **kwargs):
"""Apply(self, TextBoxAttr style, TextBoxAttr compareWith=None) -> bool"""
return _richtext.TextBoxAttr_Apply(*args, **kwargs)
def CollectCommonAttributes(*args, **kwargs):
"""CollectCommonAttributes(self, TextBoxAttr attr, TextBoxAttr clashingAttr, TextBoxAttr absentAttr)"""
return _richtext.TextBoxAttr_CollectCommonAttributes(*args, **kwargs)
def RemoveStyle(*args, **kwargs):
"""RemoveStyle(self, TextBoxAttr attr) -> bool"""
return _richtext.TextBoxAttr_RemoveStyle(*args, **kwargs)
def SetFlags(*args, **kwargs):
"""SetFlags(self, int flags)"""
return _richtext.TextBoxAttr_SetFlags(*args, **kwargs)
def GetFlags(*args, **kwargs):
"""GetFlags(self) -> int"""
return _richtext.TextBoxAttr_GetFlags(*args, **kwargs)
def HasFlag(*args, **kwargs):
"""HasFlag(self, int flag) -> bool"""
return _richtext.TextBoxAttr_HasFlag(*args, **kwargs)
def RemoveFlag(*args, **kwargs):
"""RemoveFlag(self, int flag)"""
return _richtext.TextBoxAttr_RemoveFlag(*args, **kwargs)
def AddFlag(*args, **kwargs):
"""AddFlag(self, int flag)"""
return _richtext.TextBoxAttr_AddFlag(*args, **kwargs)
def GetFloatMode(*args, **kwargs):
"""GetFloatMode(self) -> int"""
return _richtext.TextBoxAttr_GetFloatMode(*args, **kwargs)
def SetFloatMode(*args, **kwargs):
"""SetFloatMode(self, int mode)"""
return _richtext.TextBoxAttr_SetFloatMode(*args, **kwargs)
def HasFloatMode(*args, **kwargs):
"""HasFloatMode(self) -> bool"""
return _richtext.TextBoxAttr_HasFloatMode(*args, **kwargs)
def IsFloating(*args, **kwargs):
"""IsFloating(self) -> bool"""
return _richtext.TextBoxAttr_IsFloating(*args, **kwargs)
def GetClearMode(*args, **kwargs):
"""GetClearMode(self) -> int"""
return _richtext.TextBoxAttr_GetClearMode(*args, **kwargs)
def SetClearMode(*args, **kwargs):
"""SetClearMode(self, int mode)"""
return _richtext.TextBoxAttr_SetClearMode(*args, **kwargs)
def HasClearMode(*args, **kwargs):
"""HasClearMode(self) -> bool"""
return _richtext.TextBoxAttr_HasClearMode(*args, **kwargs)
def GetCollapseBorders(*args, **kwargs):
"""GetCollapseBorders(self) -> int"""
return _richtext.TextBoxAttr_GetCollapseBorders(*args, **kwargs)
def SetCollapseBorders(*args, **kwargs):
"""SetCollapseBorders(self, int collapse)"""
return _richtext.TextBoxAttr_SetCollapseBorders(*args, **kwargs)
def HasCollapseBorders(*args, **kwargs):
"""HasCollapseBorders(self) -> bool"""
return _richtext.TextBoxAttr_HasCollapseBorders(*args, **kwargs)
def GetVerticalAlignment(*args, **kwargs):
"""GetVerticalAlignment(self) -> int"""
return _richtext.TextBoxAttr_GetVerticalAlignment(*args, **kwargs)
def SetVerticalAlignment(*args, **kwargs):
"""SetVerticalAlignment(self, int verticalAlignment)"""
return _richtext.TextBoxAttr_SetVerticalAlignment(*args, **kwargs)
def HasVerticalAlignment(*args, **kwargs):
"""HasVerticalAlignment(self) -> bool"""
return _richtext.TextBoxAttr_HasVerticalAlignment(*args, **kwargs)
def GetMargins(*args):
"""
GetMargins(self) -> TextAttrDimensions
GetMargins(self) -> TextAttrDimensions
"""
return _richtext.TextBoxAttr_GetMargins(*args)
def GetLeftMargin(*args):
"""
GetLeftMargin(self) -> TextAttrDimension
GetLeftMargin(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetLeftMargin(*args)
def GetRightMargin(*args):
"""
GetRightMargin(self) -> TextAttrDimension
GetRightMargin(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetRightMargin(*args)
def GetTopMargin(*args):
"""
GetTopMargin(self) -> TextAttrDimension
GetTopMargin(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetTopMargin(*args)
def GetBottomMargin(*args):
"""
GetBottomMargin(self) -> TextAttrDimension
GetBottomMargin(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetBottomMargin(*args)
def GetPosition(*args):
"""
GetPosition(self) -> TextAttrDimensions
GetPosition(self) -> TextAttrDimensions
"""
return _richtext.TextBoxAttr_GetPosition(*args)
def GetLeft(*args):
"""
GetLeft(self) -> TextAttrDimension
GetLeft(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetLeft(*args)
def GetRight(*args):
"""
GetRight(self) -> TextAttrDimension
GetRight(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetRight(*args)
def GetTop(*args):
"""
GetTop(self) -> TextAttrDimension
GetTop(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetTop(*args)
def GetBottom(*args):
"""
GetBottom(self) -> TextAttrDimension
GetBottom(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetBottom(*args)
def GetPadding(*args):
"""
GetPadding(self) -> TextAttrDimensions
GetPadding(self) -> TextAttrDimensions
"""
return _richtext.TextBoxAttr_GetPadding(*args)
def GetLeftPadding(*args):
"""
GetLeftPadding(self) -> TextAttrDimension
GetLeftPadding(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetLeftPadding(*args)
def GetRightPadding(*args):
"""
GetRightPadding(self) -> TextAttrDimension
GetRightPadding(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetRightPadding(*args)
def GetTopPadding(*args):
"""
GetTopPadding(self) -> TextAttrDimension
GetTopPadding(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetTopPadding(*args)
def GetBottomPadding(*args):
"""
GetBottomPadding(self) -> TextAttrDimension
GetBottomPadding(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetBottomPadding(*args)
def GetBorder(*args):
"""
GetBorder(self) -> TextAttrBorders
GetBorder(self) -> TextAttrBorders
"""
return _richtext.TextBoxAttr_GetBorder(*args)
def GetLeftBorder(*args):
"""
GetLeftBorder(self) -> TextAttrBorder
GetLeftBorder(self) -> TextAttrBorder
"""
return _richtext.TextBoxAttr_GetLeftBorder(*args)
def GetTopBorder(*args):
"""
GetTopBorder(self) -> TextAttrBorder
GetTopBorder(self) -> TextAttrBorder
"""
return _richtext.TextBoxAttr_GetTopBorder(*args)
def GetRightBorder(*args):
"""
GetRightBorder(self) -> TextAttrBorder
GetRightBorder(self) -> TextAttrBorder
"""
return _richtext.TextBoxAttr_GetRightBorder(*args)
def GetBottomBorder(*args):
"""
GetBottomBorder(self) -> TextAttrBorder
GetBottomBorder(self) -> TextAttrBorder
"""
return _richtext.TextBoxAttr_GetBottomBorder(*args)
def GetOutline(*args):
"""
GetOutline(self) -> TextAttrBorders
GetOutline(self) -> TextAttrBorders
"""
return _richtext.TextBoxAttr_GetOutline(*args)
def GetLeftOutline(*args):
"""
GetLeftOutline(self) -> TextAttrBorder
GetLeftOutline(self) -> TextAttrBorder
"""
return _richtext.TextBoxAttr_GetLeftOutline(*args)
def GetTopOutline(*args):
"""
GetTopOutline(self) -> TextAttrBorder
GetTopOutline(self) -> TextAttrBorder
"""
return _richtext.TextBoxAttr_GetTopOutline(*args)
def GetRightOutline(*args):
"""
GetRightOutline(self) -> TextAttrBorder
GetRightOutline(self) -> TextAttrBorder
"""
return _richtext.TextBoxAttr_GetRightOutline(*args)
def GetBottomOutline(*args):
"""
GetBottomOutline(self) -> TextAttrBorder
GetBottomOutline(self) -> TextAttrBorder
"""
return _richtext.TextBoxAttr_GetBottomOutline(*args)
def GetSize(*args):
"""
GetSize(self) -> wxTextAttrSize
GetSize(self) -> wxTextAttrSize
"""
return _richtext.TextBoxAttr_GetSize(*args)
def SetSize(*args, **kwargs):
"""SetSize(self, wxTextAttrSize sz)"""
return _richtext.TextBoxAttr_SetSize(*args, **kwargs)
def GetWidth(*args):
"""
GetWidth(self) -> TextAttrDimension
GetWidth(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetWidth(*args)
def GetHeight(*args):
"""
GetHeight(self) -> TextAttrDimension
GetHeight(self) -> TextAttrDimension
"""
return _richtext.TextBoxAttr_GetHeight(*args)
def GetBoxStyleName(*args, **kwargs):
"""GetBoxStyleName(self) -> String"""
return _richtext.TextBoxAttr_GetBoxStyleName(*args, **kwargs)
def SetBoxStyleName(*args, **kwargs):
"""SetBoxStyleName(self, String name)"""
return _richtext.TextBoxAttr_SetBoxStyleName(*args, **kwargs)
def HasBoxStyleName(*args, **kwargs):
"""HasBoxStyleName(self) -> bool"""
return _richtext.TextBoxAttr_HasBoxStyleName(*args, **kwargs)
m_flags = property(_richtext.TextBoxAttr_m_flags_get, _richtext.TextBoxAttr_m_flags_set)
m_margins = property(_richtext.TextBoxAttr_m_margins_get, _richtext.TextBoxAttr_m_margins_set)
m_padding = property(_richtext.TextBoxAttr_m_padding_get, _richtext.TextBoxAttr_m_padding_set)
m_position = property(_richtext.TextBoxAttr_m_position_get, _richtext.TextBoxAttr_m_position_set)
m_size = property(_richtext.TextBoxAttr_m_size_get, _richtext.TextBoxAttr_m_size_set)
m_border = property(_richtext.TextBoxAttr_m_border_get, _richtext.TextBoxAttr_m_border_set)
m_outline = property(_richtext.TextBoxAttr_m_outline_get, _richtext.TextBoxAttr_m_outline_set)
m_floatMode = property(_richtext.TextBoxAttr_m_floatMode_get, _richtext.TextBoxAttr_m_floatMode_set)
m_clearMode = property(_richtext.TextBoxAttr_m_clearMode_get, _richtext.TextBoxAttr_m_clearMode_set)
m_collapseMode = property(_richtext.TextBoxAttr_m_collapseMode_get, _richtext.TextBoxAttr_m_collapseMode_set)
m_verticalAlignment = property(_richtext.TextBoxAttr_m_verticalAlignment_get, _richtext.TextBoxAttr_m_verticalAlignment_set)
m_boxStyleName = property(_richtext.TextBoxAttr_m_boxStyleName_get, _richtext.TextBoxAttr_m_boxStyleName_set)
_richtext.TextBoxAttr_swigregister(TextBoxAttr)
#---------------------------------------------------------------------------
class RichTextAttr(_controls.TextAttr):
"""Proxy of C++ RichTextAttr 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, TextAttr attr) -> RichTextAttr
__init__(self, RichTextAttr attr) -> RichTextAttr
__init__(self) -> RichTextAttr
"""
_richtext.RichTextAttr_swiginit(self,_richtext.new_RichTextAttr(*args))
__swig_destroy__ = _richtext.delete_RichTextAttr
__del__ = lambda self : None;
def Copy(*args, **kwargs):
"""Copy(self, RichTextAttr attr)"""
return _richtext.RichTextAttr_Copy(*args, **kwargs)
def __eq__(*args, **kwargs):
"""__eq__(self, RichTextAttr attr) -> bool"""
return _richtext.RichTextAttr___eq__(*args, **kwargs)
def EqPartial(*args, **kwargs):
"""EqPartial(self, RichTextAttr attr) -> bool"""
return _richtext.RichTextAttr_EqPartial(*args, **kwargs)
def Apply(*args, **kwargs):
"""Apply(self, RichTextAttr style, RichTextAttr compareWith=None) -> bool"""
return _richtext.RichTextAttr_Apply(*args, **kwargs)
def CollectCommonAttributes(*args, **kwargs):
"""CollectCommonAttributes(self, RichTextAttr attr, RichTextAttr clashingAttr, RichTextAttr absentAttr)"""
return _richtext.RichTextAttr_CollectCommonAttributes(*args, **kwargs)
def RemoveStyle(*args, **kwargs):
"""RemoveStyle(self, RichTextAttr attr) -> bool"""
return _richtext.RichTextAttr_RemoveStyle(*args, **kwargs)
def GetTextBoxAttr(*args):
"""
GetTextBoxAttr(self) -> TextBoxAttr
GetTextBoxAttr(self) -> TextBoxAttr
"""
return _richtext.RichTextAttr_GetTextBoxAttr(*args)
def SetTextBoxAttr(*args, **kwargs):
"""SetTextBoxAttr(self, TextBoxAttr attr)"""
return _richtext.RichTextAttr_SetTextBoxAttr(*args, **kwargs)
m_textBoxAttr = property(_richtext.RichTextAttr_m_textBoxAttr_get, _richtext.RichTextAttr_m_textBoxAttr_set)
_richtext.RichTextAttr_swigregister(RichTextAttr)
class RichTextFontTable(_core.Object):
"""Proxy of C++ RichTextFontTable 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) -> RichTextFontTable"""
_richtext.RichTextFontTable_swiginit(self,_richtext.new_RichTextFontTable(*args, **kwargs))
__swig_destroy__ = _richtext.delete_RichTextFontTable
__del__ = lambda self : None;
def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _richtext.RichTextFontTable_IsOk(*args, **kwargs)
def FindFont(*args, **kwargs):
"""FindFont(self, RichTextAttr fontSpec) -> Font"""
return _richtext.RichTextFontTable_FindFont(*args, **kwargs)
def Clear(*args, **kwargs):
"""Clear(self)"""
return _richtext.RichTextFontTable_Clear(*args, **kwargs)
_richtext.RichTextFontTable_swigregister(RichTextFontTable)
class RichTextRange(object):
"""
RichTextRange is a data structure that represents a range of text
within a `RichTextCtrl`. It simply contains integer ``start`` and
``end`` properties and a few operations useful for dealing with
ranges. In most places in wxPython where a RichTextRange is expected a
2-tuple containing (start, end) can be used instead.
"""
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, long start=0, long end=0) -> RichTextRange
Creates a new range object.
"""
_richtext.RichTextRange_swiginit(self,_richtext.new_RichTextRange(*args, **kwargs))
__swig_destroy__ = _richtext.delete_RichTextRange
__del__ = lambda self : None;
def __eq__(*args, **kwargs):
"""
__eq__(self, PyObject other) -> bool
Test for equality of RichTextRange objects.
"""
return _richtext.RichTextRange___eq__(*args, **kwargs)
def __sub__(*args, **kwargs):
"""__sub__(self, RichTextRange range) -> RichTextRange"""
return _richtext.RichTextRange___sub__(*args, **kwargs)
def __add__(*args, **kwargs):
"""__add__(self, RichTextRange range) -> RichTextRange"""
return _richtext.RichTextRange___add__(*args, **kwargs)
def SetRange(*args, **kwargs):
"""SetRange(self, long start, long end)"""
return _richtext.RichTextRange_SetRange(*args, **kwargs)
def SetStart(*args, **kwargs):
"""SetStart(self, long start)"""
return _richtext.RichTextRange_SetStart(*args, **kwargs)
def GetStart(*args, **kwargs):
"""GetStart(self) -> long"""
return _richtext.RichTextRange_GetStart(*args, **kwargs)
start = property(GetStart, SetStart)
def SetEnd(*args, **kwargs):
"""SetEnd(self, long end)"""
return _richtext.RichTextRange_SetEnd(*args, **kwargs)
def GetEnd(*args, **kwargs):
"""GetEnd(self) -> long"""
return _richtext.RichTextRange_GetEnd(*args, **kwargs)
end = property(GetEnd, SetEnd)
def IsOutside(*args, **kwargs):
"""
IsOutside(self, RichTextRange range) -> bool
Returns true if this range is completely outside 'range'
"""
return _richtext.RichTextRange_IsOutside(*args, **kwargs)
def IsWithin(*args, **kwargs):
"""
IsWithin(self, RichTextRange range) -> bool
Returns true if this range is completely within 'range'
"""
return _richtext.RichTextRange_IsWithin(*args, **kwargs)
def Contains(*args, **kwargs):
"""
Contains(self, long pos) -> bool
Returns true if the given position is within this range. Allow for the
possibility of an empty range - assume the position is within this
empty range.
"""
return _richtext.RichTextRange_Contains(*args, **kwargs)
def LimitTo(*args, **kwargs):
"""
LimitTo(self, RichTextRange range) -> bool
Limit this range to be within 'range'
"""
return _richtext.RichTextRange_LimitTo(*args, **kwargs)
def GetLength(*args, **kwargs):
"""
GetLength(self) -> long
Gets the length of the range
"""
return _richtext.RichTextRange_GetLength(*args, **kwargs)
def Swap(*args, **kwargs):
"""
Swap(self)
Swaps the start and end
"""
return _richtext.RichTextRange_Swap(*args, **kwargs)
def ToInternal(*args, **kwargs):
"""
ToInternal(self) -> RichTextRange
Convert to internal form: (n, n) is the range of a single character.
"""
return _richtext.RichTextRange_ToInternal(*args, **kwargs)
def FromInternal(*args, **kwargs):
"""
FromInternal(self) -> RichTextRange
Convert from internal to public API form: (n, n+1) is the range of a
single character.
"""
return _richtext.RichTextRange_FromInternal(*args, **kwargs)
def Get(*args, **kwargs):
"""
Get() -> (start,end)
Returns the start and end properties as a tuple.
"""
return _richtext.RichTextRange_Get(*args, **kwargs)
def __str__(self): return str(self.Get())
def __repr__(self): return 'RichTextRange'+str(self.Get())
def __len__(self): return len(self.Get())
def __getitem__(self, index): return self.Get()[index]
def __setitem__(self, index, val):
if index == 0: self.start = val
elif index == 1: self.end = val
else: raise IndexError
def __nonzero__(self): return self.Get() != (0,0)
__safe_for_unpickling__ = True
def __reduce__(self): return (RichTextRange, self.Get())
End = property(GetEnd,SetEnd,doc="See `GetEnd` and `SetEnd`")
Length = property(GetLength,doc="See `GetLength`")
Start = property(GetStart,SetStart,doc="See `GetStart` and `SetStart`")
_richtext.RichTextRange_swigregister(RichTextRange)
class RichTextDrawingContext(_core.Object):
"""Proxy of C++ RichTextDrawingContext 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, RichTextBuffer buffer) -> RichTextDrawingContext"""
_richtext.RichTextDrawingContext_swiginit(self,_richtext.new_RichTextDrawingContext(*args, **kwargs))
def Init(*args, **kwargs):
"""Init(self)"""
return _richtext.RichTextDrawingContext_Init(*args, **kwargs)
def HasVirtualAttributes(*args, **kwargs):
"""HasVirtualAttributes(self, RichTextObject obj) -> bool"""
return _richtext.RichTextDrawingContext_HasVirtualAttributes(*args, **kwargs)
def GetVirtualAttributes(*args, **kwargs):
"""GetVirtualAttributes(self, RichTextObject obj) -> RichTextAttr"""
return _richtext.RichTextDrawingContext_GetVirtualAttributes(*args, **kwargs)
def ApplyVirtualAttributes(*args, **kwargs):
"""ApplyVirtualAttributes(self, RichTextAttr attr, RichTextObject obj) -> bool"""
return _richtext.RichTextDrawingContext_ApplyVirtualAttributes(*args, **kwargs)
m_buffer = property(_richtext.RichTextDrawingContext_m_buffer_get, _richtext.RichTextDrawingContext_m_buffer_set)
_richtext.RichTextDrawingContext_swigregister(RichTextDrawingContext)
cvar = _richtext.cvar
RICHTEXT_ALL = cvar.RICHTEXT_ALL
RICHTEXT_NONE = cvar.RICHTEXT_NONE
class RichTextObject(_core.Object):
"""
This is the base class for all drawable objects in a `RichTextCtrl`.
The data displayed in a `RichTextCtrl` is handled by `RichTextBuffer`,
and a `RichTextCtrl` always has one such buffer.
The content is represented by a hierarchy of objects, all derived from
`RichTextObject`. An object might be an image, a fragment of text, a
paragraph, or a whole buffer. Objects store a an attribute object
containing style information; a paragraph object can contain both
paragraph and character information, but content objects such as text
can only store character information. The final style displayed in the
control or in a printout is a combination of base style, paragraph
style and content (character) style.
The top of the hierarchy is the buffer, a kind of
`RichTextParagraphLayoutBox`. containing further `RichTextParagraph`
objects, each of which can include text, images and potentially other
types of objects.
Each object maintains a range (start and end position) measured from
the start of the main parent object.
When Layout is called on an object, it is given a size which the
object must limit itself to, or one or more flexible directions
(vertical or horizontal). So, for example, a centred paragraph is
given the page width to play with (minus any margins), but can extend
indefinitely in the vertical direction. The implementation of Layout
caches the calculated size and position.
When the buffer is modified, a range is invalidated (marked as
requiring layout), so that only the minimum amount of layout is
performed.
A paragraph of pure text with the same style contains just one further
object, a `RichTextPlainText` object. When styling is applied to part
of this object, the object is decomposed into separate objects, one
object for each different character style. So each object within a
paragraph always has just one attribute object to denote its character
style. Of course, this can lead to fragmentation after a lot of edit
operations, potentially leading to several objects with the same style
where just one would do. So a Defragment function is called when
updating the control's display, to ensure that the minimum number of
objects is used.
To implement your own RichTextObjects in Python you must derive a
class from `PyRichTextObject`, which has been instrumented to forward
the virtual C++ method calls to the Python methods in the derived
class. (This class hasn't been implemented yet!)
"""
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__ = _richtext.delete_RichTextObject
__del__ = lambda self : None;
def Draw(*args, **kwargs):
"""
Draw(self, DC dc, RichTextDrawingContext context, RichTextRange range,
wxRichTextSelection selection, Rect rect,
int descent, int style) -> bool
"""
return _richtext.RichTextObject_Draw(*args, **kwargs)
def Layout(*args, **kwargs):
"""
Layout(self, DC dc, RichTextDrawingContext context, Rect rect, Rect parentRect,
int style) -> bool
"""
return _richtext.RichTextObject_Layout(*args, **kwargs)
def HitTest(*args, **kwargs):
"""
HitTest(self, DC dc, RichTextDrawingContext context, Point pt, long OUTPUT,
RichTextObject obj, RichTextObject contextObj,
int flags=0) -> int
"""
return _richtext.RichTextObject_HitTest(*args, **kwargs)
def FindPosition(*args, **kwargs):
"""
FindPosition(self, DC dc, RichTextDrawingContext context, long index,
Point OUTPUT, int OUTPUT, bool forceLineStart) -> bool
"""
return _richtext.RichTextObject_FindPosition(*args, **kwargs)
def GetBestSize(*args, **kwargs):
"""GetBestSize(self) -> Size"""
return _richtext.RichTextObject_GetBestSize(*args, **kwargs)
def GetRangeSize(*args, **kwargs):
"""
GetRangeSize(self, RichTextRange range, Size OUTPUT, int OUTPUT, DC dc,
RichTextDrawingContext context, int flags,
Point position=wxPoint(0,0)) -> bool
"""
return _richtext.RichTextObject_GetRangeSize(*args, **kwargs)
def DoSplit(*args, **kwargs):
"""DoSplit(self, long pos) -> RichTextObject"""
return _richtext.RichTextObject_DoSplit(*args, **kwargs)
def CalculateRange(*args, **kwargs):
"""CalculateRange(self, long start, long OUTPUT)"""
return _richtext.RichTextObject_CalculateRange(*args, **kwargs)
def DeleteRange(*args, **kwargs):
"""DeleteRange(self, RichTextRange range) -> bool"""
return _richtext.RichTextObject_DeleteRange(*args, **kwargs)
def IsEmpty(*args, **kwargs):
"""IsEmpty(self) -> bool"""
return _richtext.RichTextObject_IsEmpty(*args, **kwargs)
def IsFloatable(*args, **kwargs):
"""IsFloatable(self) -> bool"""
return _richtext.RichTextObject_IsFloatable(*args, **kwargs)
def IsFloating(*args, **kwargs):
"""IsFloating(self) -> bool"""
return _richtext.RichTextObject_IsFloating(*args, **kwargs)
def GetFloatDirection(*args, **kwargs):
"""GetFloatDirection(self) -> int"""
return _richtext.RichTextObject_GetFloatDirection(*args, **kwargs)
def GetTextForRange(*args, **kwargs):
"""GetTextForRange(self, RichTextRange range) -> String"""
return _richtext.RichTextObject_GetTextForRange(*args, **kwargs)
def CanMerge(*args, **kwargs):
"""CanMerge(self, RichTextObject object, RichTextDrawingContext context) -> bool"""
return _richtext.RichTextObject_CanMerge(*args, **kwargs)
def Merge(self, obj, context):
"""Merge(self, RichTextObject object) -> bool"""
val = _richtext.RichTextObject_Merge(self, obj, context)
if val:
obj.this.own(True)
return val
def Dump(*args, **kwargs):
"""Dump(self) -> String"""
return _richtext.RichTextObject_Dump(*args, **kwargs)
def CanEditProperties(*args, **kwargs):
"""CanEditProperties(self) -> bool"""
return _richtext.RichTextObject_CanEditProperties(*args, **kwargs)
def EditProperties(*args, **kwargs):
"""EditProperties(self, Window parent, RichTextBuffer buffer) -> bool"""
return _richtext.RichTextObject_EditProperties(*args, **kwargs)
def ImportFromXML(*args, **kwargs):
"""
ImportFromXML(self, RichTextBuffer buffer, wxXmlNode node, RichTextXMLHandler handler,
bool recurse) -> bool
"""
return _richtext.RichTextObject_ImportFromXML(*args, **kwargs)
def ExportXML(*args):
"""
ExportXML(self, wxOutputStream stream, int indent, RichTextXMLHandler handler) -> bool
ExportXML(self, wxXmlNode parent, RichTextXMLHandler handler) -> bool
"""
return _richtext.RichTextObject_ExportXML(*args)
def UsesParagraphAttributes(*args, **kwargs):
"""UsesParagraphAttributes(self) -> bool"""
return _richtext.RichTextObject_UsesParagraphAttributes(*args, **kwargs)
def GetXMLNodeName(*args, **kwargs):
"""GetXMLNodeName(self) -> String"""
return _richtext.RichTextObject_GetXMLNodeName(*args, **kwargs)
def GetCachedSize(*args, **kwargs):
"""GetCachedSize(self) -> Size"""
return _richtext.RichTextObject_GetCachedSize(*args, **kwargs)
def SetCachedSize(*args, **kwargs):
"""SetCachedSize(self, Size sz)"""
return _richtext.RichTextObject_SetCachedSize(*args, **kwargs)
CachedSize = property(GetCachedSize,SetCachedSize)
def GetPosition(*args, **kwargs):
"""GetPosition(self) -> Point"""
return _richtext.RichTextObject_GetPosition(*args, **kwargs)
def SetPosition(*args, **kwargs):
"""SetPosition(self, Point pos)"""
return _richtext.RichTextObject_SetPosition(*args, **kwargs)
Position = property(GetPosition,SetPosition)
def GetRect(*args, **kwargs):
"""GetRect(self) -> Rect"""
return _richtext.RichTextObject_GetRect(*args, **kwargs)
Rect = property(GetRect)
def SetRange(*args, **kwargs):
"""SetRange(self, RichTextRange range)"""
return _richtext.RichTextObject_SetRange(*args, **kwargs)
def GetRange(*args, **kwargs):
"""GetRange(self) -> RichTextRange"""
return _richtext.RichTextObject_GetRange(*args, **kwargs)
Range = property(GetRange,SetRange)
def IsComposite(*args, **kwargs):
"""IsComposite(self) -> bool"""
return _richtext.RichTextObject_IsComposite(*args, **kwargs)
def GetParent(*args, **kwargs):
"""GetParent(self) -> RichTextObject"""
return _richtext.RichTextObject_GetParent(*args, **kwargs)
def SetParent(*args, **kwargs):
"""SetParent(self, RichTextObject parent)"""
return _richtext.RichTextObject_SetParent(*args, **kwargs)
Parent = property(GetParent,SetParent)
def SetSameMargins(*args, **kwargs):
"""SetSameMargins(self, int margin)"""
return _richtext.RichTextObject_SetSameMargins(*args, **kwargs)
def SetMargins(*args, **kwargs):
"""SetMargins(self, int leftMargin, int rightMargin, int topMargin, int bottomMargin)"""
return _richtext.RichTextObject_SetMargins(*args, **kwargs)
def GetLeftMargin(*args, **kwargs):
"""GetLeftMargin(self) -> int"""
return _richtext.RichTextObject_GetLeftMargin(*args, **kwargs)
def GetRightMargin(*args, **kwargs):
"""GetRightMargin(self) -> int"""
return _richtext.RichTextObject_GetRightMargin(*args, **kwargs)
def GetTopMargin(*args, **kwargs):
"""GetTopMargin(self) -> int"""
return _richtext.RichTextObject_GetTopMargin(*args, **kwargs)
def GetBottomMargin(*args, **kwargs):
"""GetBottomMargin(self) -> int"""
return _richtext.RichTextObject_GetBottomMargin(*args, **kwargs)
def SetAttributes(*args, **kwargs):
"""SetAttributes(self, RichTextAttr attr)"""
return _richtext.RichTextObject_SetAttributes(*args, **kwargs)
def GetAttributes(*args, **kwargs):
"""GetAttributes(self) -> RichTextAttr"""
return _richtext.RichTextObject_GetAttributes(*args, **kwargs)
Attributes = property(GetAttributes,SetAttributes)
def SetDescent(*args, **kwargs):
"""SetDescent(self, int descent)"""
return _richtext.RichTextObject_SetDescent(*args, **kwargs)
def GetDescent(*args, **kwargs):
"""GetDescent(self) -> int"""
return _richtext.RichTextObject_GetDescent(*args, **kwargs)
Descent = property(GetDescent,SetDescent)
def GetBuffer(*args, **kwargs):
"""GetBuffer(self) -> RichTextBuffer"""
return _richtext.RichTextObject_GetBuffer(*args, **kwargs)
def Clone(*args, **kwargs):
"""Clone(self) -> RichTextObject"""
return _richtext.RichTextObject_Clone(*args, **kwargs)
def Copy(*args, **kwargs):
"""Copy(self, RichTextObject obj)"""
return _richtext.RichTextObject_Copy(*args, **kwargs)
def Reference(*args, **kwargs):
"""Reference(self)"""
return _richtext.RichTextObject_Reference(*args, **kwargs)
def Dereference(*args, **kwargs):
"""Dereference(self)"""
return _richtext.RichTextObject_Dereference(*args, **kwargs)
def ConvertTenthsMMToPixelsDC(*args, **kwargs):
"""ConvertTenthsMMToPixelsDC(self, DC dc, int units) -> int"""
return _richtext.RichTextObject_ConvertTenthsMMToPixelsDC(*args, **kwargs)
def ConvertTenthsMMToPixels(*args, **kwargs):
"""ConvertTenthsMMToPixels(int ppi, int units, double scale=1.0) -> int"""
return _richtext.RichTextObject_ConvertTenthsMMToPixels(*args, **kwargs)
ConvertTenthsMMToPixels = staticmethod(ConvertTenthsMMToPixels)
def ConvertPixelsToTenthsMM(*args):
"""
ConvertPixelsToTenthsMM(DC dc, int pixels) -> int
ConvertPixelsToTenthsMM(int ppi, int pixels, double scale=1.0) -> int
"""
return _richtext.RichTextObject_ConvertPixelsToTenthsMM(*args)
ConvertPixelsToTenthsMM = staticmethod(ConvertPixelsToTenthsMM)
def DrawBoxAttributes(*args, **kwargs):
"""
DrawBoxAttributes(DC dc, RichTextBuffer buffer, RichTextAttr attr, Rect boxRect,
int flags=0) -> bool
"""
return _richtext.RichTextObject_DrawBoxAttributes(*args, **kwargs)
DrawBoxAttributes = staticmethod(DrawBoxAttributes)
def DrawBorder(*args, **kwargs):
"""
DrawBorder(DC dc, RichTextBuffer buffer, TextAttrBorders attr,
Rect rect, int flags=0) -> bool
"""
return _richtext.RichTextObject_DrawBorder(*args, **kwargs)
DrawBorder = staticmethod(DrawBorder)
def GetBoxRects(*args, **kwargs):
"""
GetBoxRects(DC dc, RichTextBuffer buffer, RichTextAttr attr, Rect marginRect,
Rect borderRect, Rect contentRect,
Rect paddingRect, Rect outlineRect) -> bool
"""
return _richtext.RichTextObject_GetBoxRects(*args, **kwargs)
GetBoxRects = staticmethod(GetBoxRects)
def GetTotalMargin(*args, **kwargs):
"""
GetTotalMargin(DC dc, RichTextBuffer buffer, RichTextAttr attr, int leftMargin,
int rightMargin, int topMargin,
int bottomMargin) -> bool
"""
return _richtext.RichTextObject_GetTotalMargin(*args, **kwargs)
GetTotalMargin = staticmethod(GetTotalMargin)
def AdjustAvailableSpace(*args, **kwargs):
"""
AdjustAvailableSpace(DC dc, RichTextBuffer buffer, RichTextAttr parentAttr,
RichTextAttr childAttr, Rect availableParentSpace,
Rect availableContainerSpace) -> Rect
"""
return _richtext.RichTextObject_AdjustAvailableSpace(*args, **kwargs)
AdjustAvailableSpace = staticmethod(AdjustAvailableSpace)
_richtext.RichTextObject_swigregister(RichTextObject)
def RichTextObject_ConvertTenthsMMToPixels(*args, **kwargs):
"""RichTextObject_ConvertTenthsMMToPixels(int ppi, int units, double scale=1.0) -> int"""
return _richtext.RichTextObject_ConvertTenthsMMToPixels(*args, **kwargs)
def RichTextObject_ConvertPixelsToTenthsMM(*args):
"""
ConvertPixelsToTenthsMM(DC dc, int pixels) -> int
RichTextObject_ConvertPixelsToTenthsMM(int ppi, int pixels, double scale=1.0) -> int
"""
return _richtext.RichTextObject_ConvertPixelsToTenthsMM(*args)
def RichTextObject_DrawBoxAttributes(*args, **kwargs):
"""
RichTextObject_DrawBoxAttributes(DC dc, RichTextBuffer buffer, RichTextAttr attr, Rect boxRect,
int flags=0) -> bool
"""
return _richtext.RichTextObject_DrawBoxAttributes(*args, **kwargs)
def RichTextObject_DrawBorder(*args, **kwargs):
"""
RichTextObject_DrawBorder(DC dc, RichTextBuffer buffer, TextAttrBorders attr,
Rect rect, int flags=0) -> bool
"""
return _richtext.RichTextObject_DrawBorder(*args, **kwargs)
def RichTextObject_GetBoxRects(*args, **kwargs):
"""
RichTextObject_GetBoxRects(DC dc, RichTextBuffer buffer, RichTextAttr attr, Rect marginRect,
Rect borderRect, Rect contentRect,
Rect paddingRect, Rect outlineRect) -> bool
"""
return _richtext.RichTextObject_GetBoxRects(*args, **kwargs)
def RichTextObject_GetTotalMargin(*args, **kwargs):
"""
RichTextObject_GetTotalMargin(DC dc, RichTextBuffer buffer, RichTextAttr attr, int leftMargin,
int rightMargin, int topMargin,
int bottomMargin) -> bool
"""
return _richtext.RichTextObject_GetTotalMargin(*args, **kwargs)
def RichTextObject_AdjustAvailableSpace(*args, **kwargs):
"""
RichTextObject_AdjustAvailableSpace(DC dc, RichTextBuffer buffer, RichTextAttr parentAttr,
RichTextAttr childAttr, Rect availableParentSpace,
Rect availableContainerSpace) -> Rect
"""
return _richtext.RichTextObject_AdjustAvailableSpace(*args, **kwargs)
class RichTextObjectList_iterator(object):
"""This class serves as an iterator for a wxRichTextObjectList object."""
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__ = _richtext.delete_RichTextObjectList_iterator
__del__ = lambda self : None;
def next(*args, **kwargs):
"""next(self) -> RichTextObject"""
return _richtext.RichTextObjectList_iterator_next(*args, **kwargs)
_richtext.RichTextObjectList_iterator_swigregister(RichTextObjectList_iterator)
class RichTextObjectList(object):
"""
This class wraps a wxList-based class and gives it a Python
sequence-like interface. Sequence operations supported are length,
index access and iteration.
"""
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__ = _richtext.delete_RichTextObjectList
__del__ = lambda self : None;
def __len__(*args, **kwargs):
"""__len__(self) -> size_t"""
return _richtext.RichTextObjectList___len__(*args, **kwargs)
def __getitem__(*args, **kwargs):
"""__getitem__(self, size_t index) -> RichTextObject"""
return _richtext.RichTextObjectList___getitem__(*args, **kwargs)
def __contains__(*args, **kwargs):
"""__contains__(self, RichTextObject obj) -> bool"""
return _richtext.RichTextObjectList___contains__(*args, **kwargs)
def __iter__(*args, **kwargs):
"""__iter__(self) -> RichTextObjectList_iterator"""
return _richtext.RichTextObjectList___iter__(*args, **kwargs)
def index(*args, **kwargs):
"""index(self, RichTextObject obj) -> int"""
return _richtext.RichTextObjectList_index(*args, **kwargs)
def __repr__(self):
return "wxRichTextObjectList: " + repr(list(self))
_richtext.RichTextObjectList_swigregister(RichTextObjectList)
class RichTextCompositeObject(RichTextObject):
"""Objects of this class can contain other rich text objects."""
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__ = _richtext.delete_RichTextCompositeObject
__del__ = lambda self : None;
def GetChildren(*args, **kwargs):
"""GetChildren(self) -> RichTextObjectList"""
return _richtext.RichTextCompositeObject_GetChildren(*args, **kwargs)
def GetChildCount(*args, **kwargs):
"""GetChildCount(self) -> size_t"""
return _richtext.RichTextCompositeObject_GetChildCount(*args, **kwargs)
def GetChild(*args, **kwargs):
"""GetChild(self, size_t n) -> RichTextObject"""
return _richtext.RichTextCompositeObject_GetChild(*args, **kwargs)
def Copy(*args, **kwargs):
"""Copy(self, RichTextCompositeObject obj)"""
return _richtext.RichTextCompositeObject_Copy(*args, **kwargs)
def AppendChild(*args, **kwargs):
"""AppendChild(self, RichTextObject child) -> size_t"""
return _richtext.RichTextCompositeObject_AppendChild(*args, **kwargs)
def InsertChild(*args, **kwargs):
"""InsertChild(self, RichTextObject child, RichTextObject inFrontOf) -> bool"""
return _richtext.RichTextCompositeObject_InsertChild(*args, **kwargs)
def RemoveChild(self, child, deleteChild=False):
val = _richtext.RichTextCompositeObject_RemoveChild(self, child, deleteChild)
self.this.own(not deleteChild)
return val
def DeleteChildren(*args, **kwargs):
"""DeleteChildren(self) -> bool"""
return _richtext.RichTextCompositeObject_DeleteChildren(*args, **kwargs)
def Defragment(*args, **kwargs):
"""Defragment(self, RichTextDrawingContext context, RichTextRange range=wxRICHTEXT_ALL) -> bool"""
return _richtext.RichTextCompositeObject_Defragment(*args, **kwargs)
_richtext.RichTextCompositeObject_swigregister(RichTextCompositeObject)
class RichTextParagraphLayoutBox(RichTextCompositeObject):
"""This box knows how to lay out paragraphs."""
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, RichTextObject parent=None) -> RichTextParagraphLayoutBox
__init__(self, RichTextParagraphLayoutBox obj) -> RichTextParagraphLayoutBox
This box knows how to lay out paragraphs.
"""
_richtext.RichTextParagraphLayoutBox_swiginit(self,_richtext.new_RichTextParagraphLayoutBox(*args))
__swig_destroy__ = _richtext.delete_RichTextParagraphLayoutBox
__del__ = lambda self : None;
def SetRichTextCtrl(*args, **kwargs):
"""SetRichTextCtrl(self, RichTextCtrl ctrl)"""
return _richtext.RichTextParagraphLayoutBox_SetRichTextCtrl(*args, **kwargs)
def GetRichTextCtrl(*args, **kwargs):
"""GetRichTextCtrl(self) -> RichTextCtrl"""
return _richtext.RichTextParagraphLayoutBox_GetRichTextCtrl(*args, **kwargs)
def SetPartialParagraph(*args, **kwargs):
"""SetPartialParagraph(self, bool partialPara)"""
return _richtext.RichTextParagraphLayoutBox_SetPartialParagraph(*args, **kwargs)
def GetPartialParagraph(*args, **kwargs):
"""GetPartialParagraph(self) -> bool"""
return _richtext.RichTextParagraphLayoutBox_GetPartialParagraph(*args, **kwargs)
def GetStyleSheet(*args, **kwargs):
"""GetStyleSheet(self) -> wxRichTextStyleSheet"""
return _richtext.RichTextParagraphLayoutBox_GetStyleSheet(*args, **kwargs)
def DrawFloats(*args, **kwargs):
"""
DrawFloats(self, DC dc, RichTextDrawingContext context, RichTextRange range,
wxRichTextSelection selection, Rect rect,
int descent, int style)
"""
return _richtext.RichTextParagraphLayoutBox_DrawFloats(*args, **kwargs)
def MoveAnchoredObjectToParagraph(*args, **kwargs):
"""MoveAnchoredObjectToParagraph(self, RichTextParagraph from, RichTextParagraph to, RichTextObject obj)"""
return _richtext.RichTextParagraphLayoutBox_MoveAnchoredObjectToParagraph(*args, **kwargs)
def Init(*args, **kwargs):
"""Init(self)"""
return _richtext.RichTextParagraphLayoutBox_Init(*args, **kwargs)
def Clear(*args, **kwargs):
"""Clear(self)"""
return _richtext.RichTextParagraphLayoutBox_Clear(*args, **kwargs)
def Reset(*args, **kwargs):
"""Reset(self)"""
return _richtext.RichTextParagraphLayoutBox_Reset(*args, **kwargs)
def AddParagraph(*args, **kwargs):
"""AddParagraph(self, String text, RichTextAttr paraStyle=None) -> RichTextRange"""
return _richtext.RichTextParagraphLayoutBox_AddParagraph(*args, **kwargs)
def AddImage(*args, **kwargs):
"""AddImage(self, Image image, RichTextAttr paraStyle=None) -> RichTextRange"""
return _richtext.RichTextParagraphLayoutBox_AddImage(*args, **kwargs)
def AddParagraphs(*args, **kwargs):
"""AddParagraphs(self, String text, RichTextAttr paraStyle=None) -> RichTextRange"""
return _richtext.RichTextParagraphLayoutBox_AddParagraphs(*args, **kwargs)
def GetLineAtPosition(*args, **kwargs):
"""GetLineAtPosition(self, long pos, bool caretPosition=False) -> RichTextLine"""
return _richtext.RichTextParagraphLayoutBox_GetLineAtPosition(*args, **kwargs)
def GetLineAtYPosition(*args, **kwargs):
"""GetLineAtYPosition(self, int y) -> RichTextLine"""
return _richtext.RichTextParagraphLayoutBox_GetLineAtYPosition(*args, **kwargs)
def GetParagraphAtPosition(*args, **kwargs):
"""GetParagraphAtPosition(self, long pos, bool caretPosition=False) -> RichTextParagraph"""
return _richtext.RichTextParagraphLayoutBox_GetParagraphAtPosition(*args, **kwargs)
def GetLineSizeAtPosition(*args, **kwargs):
"""GetLineSizeAtPosition(self, long pos, bool caretPosition=False) -> Size"""
return _richtext.RichTextParagraphLayoutBox_GetLineSizeAtPosition(*args, **kwargs)
def GetVisibleLineNumber(*args, **kwargs):
"""GetVisibleLineNumber(self, long pos, bool caretPosition=False, bool startOfLine=False) -> long"""
return _richtext.RichTextParagraphLayoutBox_GetVisibleLineNumber(*args, **kwargs)
def GetLineForVisibleLineNumber(*args, **kwargs):
"""GetLineForVisibleLineNumber(self, long lineNumber) -> RichTextLine"""
return _richtext.RichTextParagraphLayoutBox_GetLineForVisibleLineNumber(*args, **kwargs)
def GetLeafObjectAtPosition(*args, **kwargs):
"""GetLeafObjectAtPosition(self, long position) -> RichTextObject"""
return _richtext.RichTextParagraphLayoutBox_GetLeafObjectAtPosition(*args, **kwargs)
def GetParagraphAtLine(*args, **kwargs):
"""GetParagraphAtLine(self, long paragraphNumber) -> RichTextParagraph"""
return _richtext.RichTextParagraphLayoutBox_GetParagraphAtLine(*args, **kwargs)
def GetParagraphForLine(*args, **kwargs):
"""GetParagraphForLine(self, RichTextLine line) -> RichTextParagraph"""
return _richtext.RichTextParagraphLayoutBox_GetParagraphForLine(*args, **kwargs)
def GetParagraphLength(*args, **kwargs):
"""GetParagraphLength(self, long paragraphNumber) -> int"""
return _richtext.RichTextParagraphLayoutBox_GetParagraphLength(*args, **kwargs)
def GetParagraphCount(*args, **kwargs):
"""GetParagraphCount(self) -> int"""
return _richtext.RichTextParagraphLayoutBox_GetParagraphCount(*args, **kwargs)
def GetLineCount(*args, **kwargs):
"""GetLineCount(self) -> int"""
return _richtext.RichTextParagraphLayoutBox_GetLineCount(*args, **kwargs)
def GetParagraphText(*args, **kwargs):
"""GetParagraphText(self, long paragraphNumber) -> String"""
return _richtext.RichTextParagraphLayoutBox_GetParagraphText(*args, **kwargs)
def XYToPosition(*args, **kwargs):
"""XYToPosition(self, long x, long y) -> long"""
return _richtext.RichTextParagraphLayoutBox_XYToPosition(*args, **kwargs)
def PositionToXY(*args, **kwargs):
"""PositionToXY(self, long pos, long x, long y) -> bool"""
return _richtext.RichTextParagraphLayoutBox_PositionToXY(*args, **kwargs)
def SetStyle(*args, **kwargs):
"""SetStyle(self, RichTextRange range, RichTextAttr style, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool"""
return _richtext.RichTextParagraphLayoutBox_SetStyle(*args, **kwargs)
def GetStyle(*args, **kwargs):
"""GetStyle(self, long position, RichTextAttr style) -> bool"""
return _richtext.RichTextParagraphLayoutBox_GetStyle(*args, **kwargs)
def GetUncombinedStyle(*args, **kwargs):
"""GetUncombinedStyle(self, long position, RichTextAttr style) -> bool"""
return _richtext.RichTextParagraphLayoutBox_GetUncombinedStyle(*args, **kwargs)
def DoGetStyle(*args, **kwargs):
"""DoGetStyle(self, long position, RichTextAttr style, bool combineStyles=True) -> bool"""
return _richtext.RichTextParagraphLayoutBox_DoGetStyle(*args, **kwargs)
def GetStyleForRange(*args, **kwargs):
"""GetStyleForRange(self, RichTextRange range, RichTextAttr style) -> bool"""
return _richtext.RichTextParagraphLayoutBox_GetStyleForRange(*args, **kwargs)
def CollectStyle(*args, **kwargs):
"""
CollectStyle(self, RichTextAttr currentStyle, RichTextAttr style, RichTextAttr clashingAttr,
RichTextAttr absentAttr) -> bool
"""
return _richtext.RichTextParagraphLayoutBox_CollectStyle(*args, **kwargs)
def SetListStyle(*args):
"""
SetListStyle(self, RichTextRange range, wxRichTextListStyleDefinition def,
int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int startFrom=1,
int specifiedLevel=-1) -> bool
SetListStyle(self, RichTextRange range, String defName, int flags=RICHTEXT_SETSTYLE_WITH_UNDO,
int startFrom=1, int specifiedLevel=-1) -> bool
"""
return _richtext.RichTextParagraphLayoutBox_SetListStyle(*args)
def ClearListStyle(*args, **kwargs):
"""ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool"""
return _richtext.RichTextParagraphLayoutBox_ClearListStyle(*args, **kwargs)
def NumberList(*args):
"""
NumberList(self, RichTextRange range, wxRichTextListStyleDefinition def=None,
int flags=RICHTEXT_SETSTYLE_WITH_UNDO,
int startFrom=1, int specifiedLevel=-1) -> bool
NumberList(self, RichTextRange range, String defName, int flags=RICHTEXT_SETSTYLE_WITH_UNDO,
int startFrom=1, int specifiedLevel=-1) -> bool
"""
return _richtext.RichTextParagraphLayoutBox_NumberList(*args)
def PromoteList(*args):
"""
PromoteList(self, int promoteBy, RichTextRange range, wxRichTextListStyleDefinition def=None,
int flags=RICHTEXT_SETSTYLE_WITH_UNDO,
int specifiedLevel=-1) -> bool
PromoteList(self, int promoteBy, RichTextRange range, String defName,
int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int specifiedLevel=-1) -> bool
"""
return _richtext.RichTextParagraphLayoutBox_PromoteList(*args)
def DoNumberList(*args, **kwargs):
"""
DoNumberList(self, RichTextRange range, RichTextRange promotionRange,
int promoteBy, wxRichTextListStyleDefinition def,
int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int startFrom=1,
int specifiedLevel=-1) -> bool
"""
return _richtext.RichTextParagraphLayoutBox_DoNumberList(*args, **kwargs)
def FindNextParagraphNumber(*args, **kwargs):
"""FindNextParagraphNumber(self, RichTextParagraph previousParagraph, RichTextAttr attr) -> bool"""
return _richtext.RichTextParagraphLayoutBox_FindNextParagraphNumber(*args, **kwargs)
def HasCharacterAttributes(*args, **kwargs):
"""HasCharacterAttributes(self, RichTextRange range, RichTextAttr style) -> bool"""
return _richtext.RichTextParagraphLayoutBox_HasCharacterAttributes(*args, **kwargs)
def HasParagraphAttributes(*args, **kwargs):
"""HasParagraphAttributes(self, RichTextRange range, RichTextAttr style) -> bool"""
return _richtext.RichTextParagraphLayoutBox_HasParagraphAttributes(*args, **kwargs)
def InsertFragment(*args, **kwargs):
"""InsertFragment(self, long position, RichTextParagraphLayoutBox fragment) -> bool"""
return _richtext.RichTextParagraphLayoutBox_InsertFragment(*args, **kwargs)
def CopyFragment(*args, **kwargs):
"""CopyFragment(self, RichTextRange range, RichTextParagraphLayoutBox fragment) -> bool"""
return _richtext.RichTextParagraphLayoutBox_CopyFragment(*args, **kwargs)
def ApplyStyleSheet(*args, **kwargs):
"""ApplyStyleSheet(self, wxRichTextStyleSheet styleSheet) -> bool"""
return _richtext.RichTextParagraphLayoutBox_ApplyStyleSheet(*args, **kwargs)
def Copy(*args, **kwargs):
"""Copy(self, RichTextParagraphLayoutBox obj)"""
return _richtext.RichTextParagraphLayoutBox_Copy(*args, **kwargs)
def UpdateRanges(*args, **kwargs):
"""UpdateRanges(self)"""
return _richtext.RichTextParagraphLayoutBox_UpdateRanges(*args, **kwargs)
def GetText(*args, **kwargs):
"""GetText(self) -> String"""
return _richtext.RichTextParagraphLayoutBox_GetText(*args, **kwargs)
def SetDefaultStyle(*args, **kwargs):
"""SetDefaultStyle(self, RichTextAttr style) -> bool"""
return _richtext.RichTextParagraphLayoutBox_SetDefaultStyle(*args, **kwargs)
def GetDefaultStyle(*args, **kwargs):
"""GetDefaultStyle(self) -> RichTextAttr"""
return _richtext.RichTextParagraphLayoutBox_GetDefaultStyle(*args, **kwargs)
def SetBasicStyle(*args, **kwargs):
"""SetBasicStyle(self, RichTextAttr style)"""
return _richtext.RichTextParagraphLayoutBox_SetBasicStyle(*args, **kwargs)
def GetBasicStyle(*args, **kwargs):
"""GetBasicStyle(self) -> RichTextAttr"""
return _richtext.RichTextParagraphLayoutBox_GetBasicStyle(*args, **kwargs)
def Invalidate(*args, **kwargs):
"""Invalidate(self, RichTextRange invalidRange=wxRICHTEXT_ALL)"""
return _richtext.RichTextParagraphLayoutBox_Invalidate(*args, **kwargs)
def UpdateFloatingObjects(*args, **kwargs):
"""UpdateFloatingObjects(self, Rect availableRect, RichTextObject untilObj=None) -> bool"""
return _richtext.RichTextParagraphLayoutBox_UpdateFloatingObjects(*args, **kwargs)
def GetInvalidRange(*args, **kwargs):
"""GetInvalidRange(self, bool wholeParagraphs=False) -> RichTextRange"""
return _richtext.RichTextParagraphLayoutBox_GetInvalidRange(*args, **kwargs)
def GetFloatCollector(*args, **kwargs):
"""GetFloatCollector(self) -> wxRichTextFloatCollector"""
return _richtext.RichTextParagraphLayoutBox_GetFloatCollector(*args, **kwargs)
_richtext.RichTextParagraphLayoutBox_swigregister(RichTextParagraphLayoutBox)
class RichTextBox(RichTextCompositeObject):
"""Proxy of C++ RichTextBox 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, RichTextObject parent=None) -> RichTextBox
__init__(self, RichTextBox obj) -> RichTextBox
"""
_richtext.RichTextBox_swiginit(self,_richtext.new_RichTextBox(*args))
def Copy(*args, **kwargs):
"""Copy(self, RichTextBox obj)"""
return _richtext.RichTextBox_Copy(*args, **kwargs)
_richtext.RichTextBox_swigregister(RichTextBox)
class RichTextLine(object):
"""
This object represents a line in a paragraph, and stores offsets from
the start of the paragraph representing the start and end positions of
the line.
"""
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, RichTextParagraph parent) -> RichTextLine
This object represents a line in a paragraph, and stores offsets from
the start of the paragraph representing the start and end positions of
the line.
"""
_richtext.RichTextLine_swiginit(self,_richtext.new_RichTextLine(*args, **kwargs))
__swig_destroy__ = _richtext.delete_RichTextLine
__del__ = lambda self : None;
def SetRange(*args, **kwargs):
"""SetRange(self, RichTextRange range)"""
return _richtext.RichTextLine_SetRange(*args, **kwargs)
def GetParent(*args, **kwargs):
"""GetParent(self) -> RichTextParagraph"""
return _richtext.RichTextLine_GetParent(*args, **kwargs)
def GetRange(*args, **kwargs):
"""GetRange(self) -> RichTextRange"""
return _richtext.RichTextLine_GetRange(*args, **kwargs)
def GetAbsoluteRange(*args, **kwargs):
"""GetAbsoluteRange(self) -> RichTextRange"""
return _richtext.RichTextLine_GetAbsoluteRange(*args, **kwargs)
def GetSize(*args, **kwargs):
"""GetSize(self) -> Size"""
return _richtext.RichTextLine_GetSize(*args, **kwargs)
def SetSize(*args, **kwargs):
"""SetSize(self, Size sz)"""
return _richtext.RichTextLine_SetSize(*args, **kwargs)
def GetPosition(*args, **kwargs):
"""GetPosition(self) -> Point"""
return _richtext.RichTextLine_GetPosition(*args, **kwargs)
def SetPosition(*args, **kwargs):
"""SetPosition(self, Point pos)"""
return _richtext.RichTextLine_SetPosition(*args, **kwargs)
def GetAbsolutePosition(*args, **kwargs):
"""GetAbsolutePosition(self) -> Point"""
return _richtext.RichTextLine_GetAbsolutePosition(*args, **kwargs)
def GetRect(*args, **kwargs):
"""GetRect(self) -> Rect"""
return _richtext.RichTextLine_GetRect(*args, **kwargs)
def SetDescent(*args, **kwargs):
"""SetDescent(self, int descent)"""
return _richtext.RichTextLine_SetDescent(*args, **kwargs)
def GetDescent(*args, **kwargs):
"""GetDescent(self) -> int"""
return _richtext.RichTextLine_GetDescent(*args, **kwargs)
def Init(*args, **kwargs):
"""Init(self, RichTextParagraph parent)"""
return _richtext.RichTextLine_Init(*args, **kwargs)
def Copy(*args, **kwargs):
"""Copy(self, RichTextLine obj)"""
return _richtext.RichTextLine_Copy(*args, **kwargs)
def Clone(*args, **kwargs):
"""Clone(self) -> RichTextLine"""
return _richtext.RichTextLine_Clone(*args, **kwargs)
_richtext.RichTextLine_swigregister(RichTextLine)
class RichTextParagraph(RichTextBox):
"""
This object represents a single paragraph (or in a straight text
editor, a line).
"""
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, String text, RichTextObject parent=None, RichTextAttr paraStyle=None,
RichTextAttr charStyle=None) -> RichTextParagraph
This object represents a single paragraph (or in a straight text
editor, a line).
"""
_richtext.RichTextParagraph_swiginit(self,_richtext.new_RichTextParagraph(*args, **kwargs))
__swig_destroy__ = _richtext.delete_RichTextParagraph
__del__ = lambda self : None;
def GetLines(*args, **kwargs):
"""GetLines(self) -> wxRichTextLineList"""
return _richtext.RichTextParagraph_GetLines(*args, **kwargs)
def Copy(*args, **kwargs):
"""Copy(self, RichTextParagraph obj)"""
return _richtext.RichTextParagraph_Copy(*args, **kwargs)
def ClearLines(*args, **kwargs):
"""ClearLines(self)"""
return _richtext.RichTextParagraph_ClearLines(*args, **kwargs)
def ApplyParagraphStyle(*args, **kwargs):
"""ApplyParagraphStyle(self, RichTextLine line, RichTextAttr attr, Rect rect, DC dc)"""
return _richtext.RichTextParagraph_ApplyParagraphStyle(*args, **kwargs)
def InsertText(*args, **kwargs):
"""InsertText(self, long pos, String text) -> bool"""
return _richtext.RichTextParagraph_InsertText(*args, **kwargs)
def SplitAt(*args, **kwargs):
"""SplitAt(self, long pos, RichTextObject previousObject=None) -> RichTextObject"""
return _richtext.RichTextParagraph_SplitAt(*args, **kwargs)
def MoveToList(*args, **kwargs):
"""MoveToList(self, RichTextObject obj, wxList list)"""
return _richtext.RichTextParagraph_MoveToList(*args, **kwargs)
def MoveFromList(*args, **kwargs):
"""MoveFromList(self, wxList list)"""
return _richtext.RichTextParagraph_MoveFromList(*args, **kwargs)
def GetContiguousPlainText(*args, **kwargs):
"""GetContiguousPlainText(self, String text, RichTextRange range, bool fromStart=True) -> bool"""
return _richtext.RichTextParagraph_GetContiguousPlainText(*args, **kwargs)
def FindWrapPosition(*args, **kwargs):
"""
FindWrapPosition(self, RichTextRange range, DC dc, RichTextDrawingContext context,
int availableSpace, long wrapPosition,
wxArrayInt partialExtents) -> bool
"""
return _richtext.RichTextParagraph_FindWrapPosition(*args, **kwargs)
def FindObjectAtPosition(*args, **kwargs):
"""FindObjectAtPosition(self, long position) -> RichTextObject"""
return _richtext.RichTextParagraph_FindObjectAtPosition(*args, **kwargs)
def GetBulletText(*args, **kwargs):
"""GetBulletText(self) -> String"""
return _richtext.RichTextParagraph_GetBulletText(*args, **kwargs)
def AllocateLine(*args, **kwargs):
"""AllocateLine(self, int pos) -> RichTextLine"""
return _richtext.RichTextParagraph_AllocateLine(*args, **kwargs)
def ClearUnusedLines(*args, **kwargs):
"""ClearUnusedLines(self, int lineCount) -> bool"""
return _richtext.RichTextParagraph_ClearUnusedLines(*args, **kwargs)
def GetCombinedAttributes(*args, **kwargs):
"""GetCombinedAttributes(self, RichTextAttr contentStyle=None) -> RichTextAttr"""
return _richtext.RichTextParagraph_GetCombinedAttributes(*args, **kwargs)
def GetFirstLineBreakPosition(*args, **kwargs):
"""GetFirstLineBreakPosition(self, long pos) -> long"""
return _richtext.RichTextParagraph_GetFirstLineBreakPosition(*args, **kwargs)
def InitDefaultTabs(*args, **kwargs):
"""InitDefaultTabs()"""
return _richtext.RichTextParagraph_InitDefaultTabs(*args, **kwargs)
InitDefaultTabs = staticmethod(InitDefaultTabs)
def ClearDefaultTabs(*args, **kwargs):
"""ClearDefaultTabs()"""
return _richtext.RichTextParagraph_ClearDefaultTabs(*args, **kwargs)
ClearDefaultTabs = staticmethod(ClearDefaultTabs)
def GetDefaultTabs(*args, **kwargs):
"""GetDefaultTabs() -> wxArrayInt"""
return _richtext.RichTextParagraph_GetDefaultTabs(*args, **kwargs)
GetDefaultTabs = staticmethod(GetDefaultTabs)
_richtext.RichTextParagraph_swigregister(RichTextParagraph)
def RichTextParagraph_InitDefaultTabs(*args):
"""RichTextParagraph_InitDefaultTabs()"""
return _richtext.RichTextParagraph_InitDefaultTabs(*args)
def RichTextParagraph_ClearDefaultTabs(*args):
"""RichTextParagraph_ClearDefaultTabs()"""
return _richtext.RichTextParagraph_ClearDefaultTabs(*args)
def RichTextParagraph_GetDefaultTabs(*args):
"""RichTextParagraph_GetDefaultTabs() -> wxArrayInt"""
return _richtext.RichTextParagraph_GetDefaultTabs(*args)
class RichTextPlainText(RichTextObject):
"""This object represents a single piece of text."""
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, String text=wxEmptyString, RichTextObject parent=None,
RichTextAttr style=None) -> RichTextPlainText
This object represents a single piece of text.
"""
_richtext.RichTextPlainText_swiginit(self,_richtext.new_RichTextPlainText(*args, **kwargs))
def GetFirstLineBreakPosition(*args, **kwargs):
"""GetFirstLineBreakPosition(self, long pos) -> long"""
return _richtext.RichTextPlainText_GetFirstLineBreakPosition(*args, **kwargs)
def GetText(*args, **kwargs):
"""GetText(self) -> String"""
return _richtext.RichTextPlainText_GetText(*args, **kwargs)
def SetText(*args, **kwargs):
"""SetText(self, String text)"""
return _richtext.RichTextPlainText_SetText(*args, **kwargs)
def Copy(*args, **kwargs):
"""Copy(self, RichTextPlainText obj)"""
return _richtext.RichTextPlainText_Copy(*args, **kwargs)
_richtext.RichTextPlainText_swigregister(RichTextPlainText)
class RichTextImage(RichTextObject):
"""This object represents an image."""
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, RichTextObject parent=None) -> RichTextImage
__init__(self, Image image, RichTextObject parent=None, RichTextAttr charStyle=None) -> RichTextImage
__init__(self, wxRichTextImageBlock imageBlock, RichTextObject parent=None,
RichTextAttr charStyle=None) -> RichTextImage
__init__(self, RichTextImage obj) -> RichTextImage
This object represents an image.
"""
_richtext.RichTextImage_swiginit(self,_richtext.new_RichTextImage(*args))
def GetImageCache(*args, **kwargs):
"""GetImageCache(self) -> Bitmap"""
return _richtext.RichTextImage_GetImageCache(*args, **kwargs)
def SetImageCache(*args, **kwargs):
"""SetImageCache(self, Bitmap bitmap)"""
return _richtext.RichTextImage_SetImageCache(*args, **kwargs)
def ResetImageCache(*args, **kwargs):
"""ResetImageCache(self)"""
return _richtext.RichTextImage_ResetImageCache(*args, **kwargs)
def GetImageBlock(*args, **kwargs):
"""GetImageBlock(self) -> wxRichTextImageBlock"""
return _richtext.RichTextImage_GetImageBlock(*args, **kwargs)
def Copy(*args, **kwargs):
"""Copy(self, RichTextImage obj)"""
return _richtext.RichTextImage_Copy(*args, **kwargs)
def LoadImageCache(*args, **kwargs):
"""LoadImageCache(self, DC dc, bool resetCache=False) -> bool"""
return _richtext.RichTextImage_LoadImageCache(*args, **kwargs)
_richtext.RichTextImage_swigregister(RichTextImage)
class RichTextFileHandlerList_iterator(object):
"""This class serves as an iterator for a wxRichTextFileHandlerList object."""
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__ = _richtext.delete_RichTextFileHandlerList_iterator
__del__ = lambda self : None;
def next(*args, **kwargs):
"""next(self) -> RichTextFileHandler"""
return _richtext.RichTextFileHandlerList_iterator_next(*args, **kwargs)
_richtext.RichTextFileHandlerList_iterator_swigregister(RichTextFileHandlerList_iterator)
class RichTextFileHandlerList(object):
"""
This class wraps a wxList-based class and gives it a Python
sequence-like interface. Sequence operations supported are length,
index access and iteration.
"""
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__ = _richtext.delete_RichTextFileHandlerList
__del__ = lambda self : None;
def __len__(*args, **kwargs):
"""__len__(self) -> size_t"""
return _richtext.RichTextFileHandlerList___len__(*args, **kwargs)
def __getitem__(*args, **kwargs):
"""__getitem__(self, size_t index) -> RichTextFileHandler"""
return _richtext.RichTextFileHandlerList___getitem__(*args, **kwargs)
def __contains__(*args, **kwargs):
"""__contains__(self, RichTextFileHandler obj) -> bool"""
return _richtext.RichTextFileHandlerList___contains__(*args, **kwargs)
def __iter__(*args, **kwargs):
"""__iter__(self) -> RichTextFileHandlerList_iterator"""
return _richtext.RichTextFileHandlerList___iter__(*args, **kwargs)
def __repr__(self):
return "wxRichTextFileHandlerList: " + repr(list(self))
_richtext.RichTextFileHandlerList_swigregister(RichTextFileHandlerList)
class RichTextBuffer(RichTextParagraphLayoutBox):
"""This is a kind of box, used to represent the whole buffer."""
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) -> RichTextBuffer
This is a kind of box, used to represent the whole buffer.
"""
_richtext.RichTextBuffer_swiginit(self,_richtext.new_RichTextBuffer(*args, **kwargs))
__swig_destroy__ = _richtext.delete_RichTextBuffer
__del__ = lambda self : None;
def GetCommandProcessor(*args, **kwargs):
"""GetCommandProcessor(self) -> wxCommandProcessor"""
return _richtext.RichTextBuffer_GetCommandProcessor(*args, **kwargs)
def SetStyleSheet(*args, **kwargs):
"""SetStyleSheet(self, wxRichTextStyleSheet styleSheet)"""
return _richtext.RichTextBuffer_SetStyleSheet(*args, **kwargs)
def SetStyleSheetAndNotify(*args, **kwargs):
"""SetStyleSheetAndNotify(self, wxRichTextStyleSheet sheet) -> bool"""
return _richtext.RichTextBuffer_SetStyleSheetAndNotify(*args, **kwargs)
def PushStyleSheet(*args, **kwargs):
"""PushStyleSheet(self, wxRichTextStyleSheet styleSheet) -> bool"""
return _richtext.RichTextBuffer_PushStyleSheet(*args, **kwargs)
def PopStyleSheet(*args, **kwargs):
"""PopStyleSheet(self) -> wxRichTextStyleSheet"""
return _richtext.RichTextBuffer_PopStyleSheet(*args, **kwargs)
def GetFontTable(*args, **kwargs):
"""GetFontTable(self) -> RichTextFontTable"""
return _richtext.RichTextBuffer_GetFontTable(*args, **kwargs)
def SetFontTable(*args, **kwargs):
"""SetFontTable(self, RichTextFontTable table)"""
return _richtext.RichTextBuffer_SetFontTable(*args, **kwargs)
def Init(*args, **kwargs):
"""Init(self)"""
return _richtext.RichTextBuffer_Init(*args, **kwargs)
def ResetAndClearCommands(*args, **kwargs):
"""ResetAndClearCommands(self)"""
return _richtext.RichTextBuffer_ResetAndClearCommands(*args, **kwargs)
def LoadFile(*args, **kwargs):
"""LoadFile(self, String filename, int type=RICHTEXT_TYPE_ANY) -> bool"""
return _richtext.RichTextBuffer_LoadFile(*args, **kwargs)
def SaveFile(*args, **kwargs):
"""SaveFile(self, String filename, int type=RICHTEXT_TYPE_ANY) -> bool"""
return _richtext.RichTextBuffer_SaveFile(*args, **kwargs)
def LoadStream(*args, **kwargs):
"""LoadStream(self, InputStream stream, int type=RICHTEXT_TYPE_ANY) -> bool"""
return _richtext.RichTextBuffer_LoadStream(*args, **kwargs)
def SaveStream(*args, **kwargs):
"""SaveStream(self, wxOutputStream stream, int type=RICHTEXT_TYPE_ANY) -> bool"""
return _richtext.RichTextBuffer_SaveStream(*args, **kwargs)
def SetHandlerFlags(*args, **kwargs):
"""SetHandlerFlags(self, int flags)"""
return _richtext.RichTextBuffer_SetHandlerFlags(*args, **kwargs)
def GetHandlerFlags(*args, **kwargs):
"""GetHandlerFlags(self) -> int"""
return _richtext.RichTextBuffer_GetHandlerFlags(*args, **kwargs)
def BeginBatchUndo(*args, **kwargs):
"""BeginBatchUndo(self, String cmdName) -> bool"""
return _richtext.RichTextBuffer_BeginBatchUndo(*args, **kwargs)
def EndBatchUndo(*args, **kwargs):
"""EndBatchUndo(self) -> bool"""
return _richtext.RichTextBuffer_EndBatchUndo(*args, **kwargs)
def BatchingUndo(*args, **kwargs):
"""BatchingUndo(self) -> bool"""
return _richtext.RichTextBuffer_BatchingUndo(*args, **kwargs)
def SubmitAction(*args, **kwargs):
"""SubmitAction(self, RichTextAction action) -> bool"""
return _richtext.RichTextBuffer_SubmitAction(*args, **kwargs)
def GetBatchedCommand(*args, **kwargs):
"""GetBatchedCommand(self) -> RichTextCommand"""
return _richtext.RichTextBuffer_GetBatchedCommand(*args, **kwargs)
def BeginSuppressUndo(*args, **kwargs):
"""BeginSuppressUndo(self) -> bool"""
return _richtext.RichTextBuffer_BeginSuppressUndo(*args, **kwargs)
def EndSuppressUndo(*args, **kwargs):
"""EndSuppressUndo(self) -> bool"""
return _richtext.RichTextBuffer_EndSuppressUndo(*args, **kwargs)
def SuppressingUndo(*args, **kwargs):
"""SuppressingUndo(self) -> bool"""
return _richtext.RichTextBuffer_SuppressingUndo(*args, **kwargs)
def CopyToClipboard(*args, **kwargs):
"""CopyToClipboard(self, RichTextRange range) -> bool"""
return _richtext.RichTextBuffer_CopyToClipboard(*args, **kwargs)
def PasteFromClipboard(*args, **kwargs):
"""PasteFromClipboard(self, long position) -> bool"""
return _richtext.RichTextBuffer_PasteFromClipboard(*args, **kwargs)
def CanPasteFromClipboard(*args, **kwargs):
"""CanPasteFromClipboard(self) -> bool"""
return _richtext.RichTextBuffer_CanPasteFromClipboard(*args, **kwargs)
def BeginStyle(*args, **kwargs):
"""BeginStyle(self, RichTextAttr style) -> bool"""
return _richtext.RichTextBuffer_BeginStyle(*args, **kwargs)
def EndStyle(*args, **kwargs):
"""EndStyle(self) -> bool"""
return _richtext.RichTextBuffer_EndStyle(*args, **kwargs)
def EndAllStyles(*args, **kwargs):
"""EndAllStyles(self) -> bool"""
return _richtext.RichTextBuffer_EndAllStyles(*args, **kwargs)
def ClearStyleStack(*args, **kwargs):
"""ClearStyleStack(self)"""
return _richtext.RichTextBuffer_ClearStyleStack(*args, **kwargs)
def GetStyleStackSize(*args, **kwargs):
"""GetStyleStackSize(self) -> size_t"""
return _richtext.RichTextBuffer_GetStyleStackSize(*args, **kwargs)
def BeginBold(*args, **kwargs):
"""BeginBold(self) -> bool"""
return _richtext.RichTextBuffer_BeginBold(*args, **kwargs)
def EndBold(*args, **kwargs):
"""EndBold(self) -> bool"""
return _richtext.RichTextBuffer_EndBold(*args, **kwargs)
def BeginItalic(*args, **kwargs):
"""BeginItalic(self) -> bool"""
return _richtext.RichTextBuffer_BeginItalic(*args, **kwargs)
def EndItalic(*args, **kwargs):
"""EndItalic(self) -> bool"""
return _richtext.RichTextBuffer_EndItalic(*args, **kwargs)
def BeginUnderline(*args, **kwargs):
"""BeginUnderline(self) -> bool"""
return _richtext.RichTextBuffer_BeginUnderline(*args, **kwargs)
def EndUnderline(*args, **kwargs):
"""EndUnderline(self) -> bool"""
return _richtext.RichTextBuffer_EndUnderline(*args, **kwargs)
def BeginFontSize(*args, **kwargs):
"""BeginFontSize(self, int pointSize) -> bool"""
return _richtext.RichTextBuffer_BeginFontSize(*args, **kwargs)
def EndFontSize(*args, **kwargs):
"""EndFontSize(self) -> bool"""
return _richtext.RichTextBuffer_EndFontSize(*args, **kwargs)
def BeginFont(*args, **kwargs):
"""BeginFont(self, Font font) -> bool"""
return _richtext.RichTextBuffer_BeginFont(*args, **kwargs)
def EndFont(*args, **kwargs):
"""EndFont(self) -> bool"""
return _richtext.RichTextBuffer_EndFont(*args, **kwargs)
def BeginTextColour(*args, **kwargs):
"""BeginTextColour(self, Colour colour) -> bool"""
return _richtext.RichTextBuffer_BeginTextColour(*args, **kwargs)
def EndTextColour(*args, **kwargs):
"""EndTextColour(self) -> bool"""
return _richtext.RichTextBuffer_EndTextColour(*args, **kwargs)
def BeginAlignment(*args, **kwargs):
"""BeginAlignment(self, int alignment) -> bool"""
return _richtext.RichTextBuffer_BeginAlignment(*args, **kwargs)
def EndAlignment(*args, **kwargs):
"""EndAlignment(self) -> bool"""
return _richtext.RichTextBuffer_EndAlignment(*args, **kwargs)
def BeginLeftIndent(*args, **kwargs):
"""BeginLeftIndent(self, int leftIndent, int leftSubIndent=0) -> bool"""
return _richtext.RichTextBuffer_BeginLeftIndent(*args, **kwargs)
def EndLeftIndent(*args, **kwargs):
"""EndLeftIndent(self) -> bool"""
return _richtext.RichTextBuffer_EndLeftIndent(*args, **kwargs)
def BeginRightIndent(*args, **kwargs):
"""BeginRightIndent(self, int rightIndent) -> bool"""
return _richtext.RichTextBuffer_BeginRightIndent(*args, **kwargs)
def EndRightIndent(*args, **kwargs):
"""EndRightIndent(self) -> bool"""
return _richtext.RichTextBuffer_EndRightIndent(*args, **kwargs)
def BeginParagraphSpacing(*args, **kwargs):
"""BeginParagraphSpacing(self, int before, int after) -> bool"""
return _richtext.RichTextBuffer_BeginParagraphSpacing(*args, **kwargs)
def EndParagraphSpacing(*args, **kwargs):
"""EndParagraphSpacing(self) -> bool"""
return _richtext.RichTextBuffer_EndParagraphSpacing(*args, **kwargs)
def BeginLineSpacing(*args, **kwargs):
"""BeginLineSpacing(self, int lineSpacing) -> bool"""
return _richtext.RichTextBuffer_BeginLineSpacing(*args, **kwargs)
def EndLineSpacing(*args, **kwargs):
"""EndLineSpacing(self) -> bool"""
return _richtext.RichTextBuffer_EndLineSpacing(*args, **kwargs)
def BeginNumberedBullet(*args, **kwargs):
"""
BeginNumberedBullet(self, int bulletNumber, int leftIndent, int leftSubIndent,
int bulletStyle=wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD) -> bool
"""
return _richtext.RichTextBuffer_BeginNumberedBullet(*args, **kwargs)
def EndNumberedBullet(*args, **kwargs):
"""EndNumberedBullet(self) -> bool"""
return _richtext.RichTextBuffer_EndNumberedBullet(*args, **kwargs)
def BeginSymbolBullet(*args, **kwargs):
"""BeginSymbolBullet(self, String symbol, int leftIndent, int leftSubIndent, int bulletStyle=TEXT_ATTR_BULLET_STYLE_SYMBOL) -> bool"""
return _richtext.RichTextBuffer_BeginSymbolBullet(*args, **kwargs)
def EndSymbolBullet(*args, **kwargs):
"""EndSymbolBullet(self) -> bool"""
return _richtext.RichTextBuffer_EndSymbolBullet(*args, **kwargs)
def BeginStandardBullet(*args, **kwargs):
"""
BeginStandardBullet(self, String bulletName, int leftIndent, int leftSubIndent,
int bulletStyle=TEXT_ATTR_BULLET_STYLE_STANDARD) -> bool
"""
return _richtext.RichTextBuffer_BeginStandardBullet(*args, **kwargs)
def EndStandardBullet(*args, **kwargs):
"""EndStandardBullet(self) -> bool"""
return _richtext.RichTextBuffer_EndStandardBullet(*args, **kwargs)
def BeginCharacterStyle(*args, **kwargs):
"""BeginCharacterStyle(self, String characterStyle) -> bool"""
return _richtext.RichTextBuffer_BeginCharacterStyle(*args, **kwargs)
def EndCharacterStyle(*args, **kwargs):
"""EndCharacterStyle(self) -> bool"""
return _richtext.RichTextBuffer_EndCharacterStyle(*args, **kwargs)
def BeginParagraphStyle(*args, **kwargs):
"""BeginParagraphStyle(self, String paragraphStyle) -> bool"""
return _richtext.RichTextBuffer_BeginParagraphStyle(*args, **kwargs)
def EndParagraphStyle(*args, **kwargs):
"""EndParagraphStyle(self) -> bool"""
return _richtext.RichTextBuffer_EndParagraphStyle(*args, **kwargs)
def BeginListStyle(*args, **kwargs):
"""BeginListStyle(self, String listStyle, int level=1, int number=1) -> bool"""
return _richtext.RichTextBuffer_BeginListStyle(*args, **kwargs)
def EndListStyle(*args, **kwargs):
"""EndListStyle(self) -> bool"""
return _richtext.RichTextBuffer_EndListStyle(*args, **kwargs)
def BeginURL(*args, **kwargs):
"""BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool"""
return _richtext.RichTextBuffer_BeginURL(*args, **kwargs)
def EndURL(*args, **kwargs):
"""EndURL(self) -> bool"""
return _richtext.RichTextBuffer_EndURL(*args, **kwargs)
def AddEventHandler(*args, **kwargs):
"""AddEventHandler(self, EvtHandler handler) -> bool"""
return _richtext.RichTextBuffer_AddEventHandler(*args, **kwargs)
def RemoveEventHandler(*args, **kwargs):
"""RemoveEventHandler(self, EvtHandler handler, bool deleteHandler=False) -> bool"""
return _richtext.RichTextBuffer_RemoveEventHandler(*args, **kwargs)
def ClearEventHandlers(*args, **kwargs):
"""ClearEventHandlers(self)"""
return _richtext.RichTextBuffer_ClearEventHandlers(*args, **kwargs)
def SendEvent(*args, **kwargs):
"""SendEvent(self, Event event, bool sendToAll=True) -> bool"""
return _richtext.RichTextBuffer_SendEvent(*args, **kwargs)
def Copy(*args, **kwargs):
"""Copy(self, RichTextBuffer obj)"""
return _richtext.RichTextBuffer_Copy(*args, **kwargs)
def InsertParagraphsWithUndo(*args, **kwargs):
"""
InsertParagraphsWithUndo(self, long pos, RichTextParagraphLayoutBox paragraphs, RichTextCtrl ctrl,
int flags=0) -> bool
"""
return _richtext.RichTextBuffer_InsertParagraphsWithUndo(*args, **kwargs)
def InsertTextWithUndo(*args, **kwargs):
"""InsertTextWithUndo(self, long pos, String text, RichTextCtrl ctrl, int flags=0) -> bool"""
return _richtext.RichTextBuffer_InsertTextWithUndo(*args, **kwargs)
def InsertNewlineWithUndo(*args, **kwargs):
"""InsertNewlineWithUndo(self, long pos, RichTextCtrl ctrl, int flags=0) -> bool"""
return _richtext.RichTextBuffer_InsertNewlineWithUndo(*args, **kwargs)
def InsertImageWithUndo(*args, **kwargs):
"""
InsertImageWithUndo(self, long pos, wxRichTextImageBlock imageBlock, RichTextCtrl ctrl,
int flags=0) -> bool
"""
return _richtext.RichTextBuffer_InsertImageWithUndo(*args, **kwargs)
def DeleteRangeWithUndo(*args, **kwargs):
"""DeleteRangeWithUndo(self, RichTextRange range, RichTextCtrl ctrl) -> bool"""
return _richtext.RichTextBuffer_DeleteRangeWithUndo(*args, **kwargs)
def Modify(*args, **kwargs):
"""Modify(self, bool modify=True)"""
return _richtext.RichTextBuffer_Modify(*args, **kwargs)
def IsModified(*args, **kwargs):
"""IsModified(self) -> bool"""
return _richtext.RichTextBuffer_IsModified(*args, **kwargs)
def GetStyleForNewParagraph(*args, **kwargs):
"""
GetStyleForNewParagraph(self, RichTextBuffer buffer, long pos, bool caretPosition=False,
bool lookUpNewParaStyle=False) -> RichTextAttr
"""
return _richtext.RichTextBuffer_GetStyleForNewParagraph(*args, **kwargs)
def GetHandlers(*args, **kwargs):
"""GetHandlers() -> wxRichTextFileHandlerList_t"""
return _richtext.RichTextBuffer_GetHandlers(*args, **kwargs)
GetHandlers = staticmethod(GetHandlers)
def AddHandler(*args, **kwargs):
"""AddHandler(RichTextFileHandler handler)"""
return _richtext.RichTextBuffer_AddHandler(*args, **kwargs)
AddHandler = staticmethod(AddHandler)
def InsertHandler(*args, **kwargs):
"""InsertHandler(RichTextFileHandler handler)"""
return _richtext.RichTextBuffer_InsertHandler(*args, **kwargs)
InsertHandler = staticmethod(InsertHandler)
def RemoveHandler(*args, **kwargs):
"""RemoveHandler(String name) -> bool"""
return _richtext.RichTextBuffer_RemoveHandler(*args, **kwargs)
RemoveHandler = staticmethod(RemoveHandler)
def FindHandlerByName(*args, **kwargs):
"""FindHandlerByName(String name) -> RichTextFileHandler"""
return _richtext.RichTextBuffer_FindHandlerByName(*args, **kwargs)
FindHandlerByName = staticmethod(FindHandlerByName)
def FindHandlerByExtension(*args, **kwargs):
"""FindHandlerByExtension(String extension, int imageType) -> RichTextFileHandler"""
return _richtext.RichTextBuffer_FindHandlerByExtension(*args, **kwargs)
FindHandlerByExtension = staticmethod(FindHandlerByExtension)
def FindHandlerByFilename(*args, **kwargs):
"""FindHandlerByFilename(String filename, int imageType) -> RichTextFileHandler"""
return _richtext.RichTextBuffer_FindHandlerByFilename(*args, **kwargs)
FindHandlerByFilename = staticmethod(FindHandlerByFilename)
def FindHandlerByType(*args, **kwargs):
"""FindHandlerByType(int imageType) -> RichTextFileHandler"""
return _richtext.RichTextBuffer_FindHandlerByType(*args, **kwargs)
FindHandlerByType = staticmethod(FindHandlerByType)
def GetExtWildcard(*args, **kwargs):
"""
GetExtWildcard(self, bool combine=False, bool save=False) --> (wildcards, types)
Gets a wildcard string for the file dialog based on all the currently
loaded richtext file handlers, and a list that can be used to map
those filter types to the file handler type.
"""
return _richtext.RichTextBuffer_GetExtWildcard(*args, **kwargs)
GetExtWildcard = staticmethod(GetExtWildcard)
def CleanUpHandlers(*args, **kwargs):
"""CleanUpHandlers()"""
return _richtext.RichTextBuffer_CleanUpHandlers(*args, **kwargs)
CleanUpHandlers = staticmethod(CleanUpHandlers)
def InitStandardHandlers(*args, **kwargs):
"""InitStandardHandlers()"""
return _richtext.RichTextBuffer_InitStandardHandlers(*args, **kwargs)
InitStandardHandlers = staticmethod(InitStandardHandlers)
def GetRenderer(*args, **kwargs):
"""GetRenderer() -> RichTextRenderer"""
return _richtext.RichTextBuffer_GetRenderer(*args, **kwargs)
GetRenderer = staticmethod(GetRenderer)
def SetRenderer(*args, **kwargs):
"""SetRenderer(RichTextRenderer renderer)"""
return _richtext.RichTextBuffer_SetRenderer(*args, **kwargs)
SetRenderer = staticmethod(SetRenderer)
def GetBulletRightMargin(*args, **kwargs):
"""GetBulletRightMargin() -> int"""
return _richtext.RichTextBuffer_GetBulletRightMargin(*args, **kwargs)
GetBulletRightMargin = staticmethod(GetBulletRightMargin)
def SetBulletRightMargin(*args, **kwargs):
"""SetBulletRightMargin(int margin)"""
return _richtext.RichTextBuffer_SetBulletRightMargin(*args, **kwargs)
SetBulletRightMargin = staticmethod(SetBulletRightMargin)
def GetBulletProportion(*args, **kwargs):
"""GetBulletProportion() -> float"""
return _richtext.RichTextBuffer_GetBulletProportion(*args, **kwargs)
GetBulletProportion = staticmethod(GetBulletProportion)
def SetBulletProportion(*args, **kwargs):
"""SetBulletProportion(float prop)"""
return _richtext.RichTextBuffer_SetBulletProportion(*args, **kwargs)
SetBulletProportion = staticmethod(SetBulletProportion)
def GetScale(*args, **kwargs):
"""GetScale(self) -> double"""
return _richtext.RichTextBuffer_GetScale(*args, **kwargs)
def SetScale(*args, **kwargs):
"""SetScale(self, double scale)"""
return _richtext.RichTextBuffer_SetScale(*args, **kwargs)
_richtext.RichTextBuffer_swigregister(RichTextBuffer)
def RichTextBuffer_GetHandlers(*args):
"""RichTextBuffer_GetHandlers() -> wxRichTextFileHandlerList_t"""
return _richtext.RichTextBuffer_GetHandlers(*args)
def RichTextBuffer_AddHandler(*args, **kwargs):
"""RichTextBuffer_AddHandler(RichTextFileHandler handler)"""
return _richtext.RichTextBuffer_AddHandler(*args, **kwargs)
def RichTextBuffer_InsertHandler(*args, **kwargs):
"""RichTextBuffer_InsertHandler(RichTextFileHandler handler)"""
return _richtext.RichTextBuffer_InsertHandler(*args, **kwargs)
def RichTextBuffer_RemoveHandler(*args, **kwargs):
"""RichTextBuffer_RemoveHandler(String name) -> bool"""
return _richtext.RichTextBuffer_RemoveHandler(*args, **kwargs)
def RichTextBuffer_FindHandlerByName(*args, **kwargs):
"""RichTextBuffer_FindHandlerByName(String name) -> RichTextFileHandler"""
return _richtext.RichTextBuffer_FindHandlerByName(*args, **kwargs)
def RichTextBuffer_FindHandlerByExtension(*args, **kwargs):
"""RichTextBuffer_FindHandlerByExtension(String extension, int imageType) -> RichTextFileHandler"""
return _richtext.RichTextBuffer_FindHandlerByExtension(*args, **kwargs)
def RichTextBuffer_FindHandlerByFilename(*args, **kwargs):
"""RichTextBuffer_FindHandlerByFilename(String filename, int imageType) -> RichTextFileHandler"""
return _richtext.RichTextBuffer_FindHandlerByFilename(*args, **kwargs)
def RichTextBuffer_FindHandlerByType(*args, **kwargs):
"""RichTextBuffer_FindHandlerByType(int imageType) -> RichTextFileHandler"""
return _richtext.RichTextBuffer_FindHandlerByType(*args, **kwargs)
def RichTextBuffer_GetExtWildcard(*args, **kwargs):
"""
GetExtWildcard(self, bool combine=False, bool save=False) --> (wildcards, types)
Gets a wildcard string for the file dialog based on all the currently
loaded richtext file handlers, and a list that can be used to map
those filter types to the file handler type.
"""
return _richtext.RichTextBuffer_GetExtWildcard(*args, **kwargs)
def RichTextBuffer_CleanUpHandlers(*args):
"""RichTextBuffer_CleanUpHandlers()"""
return _richtext.RichTextBuffer_CleanUpHandlers(*args)
def RichTextBuffer_InitStandardHandlers(*args):
"""RichTextBuffer_InitStandardHandlers()"""
return _richtext.RichTextBuffer_InitStandardHandlers(*args)
def RichTextBuffer_GetRenderer(*args):
"""RichTextBuffer_GetRenderer() -> RichTextRenderer"""
return _richtext.RichTextBuffer_GetRenderer(*args)
def RichTextBuffer_SetRenderer(*args, **kwargs):
"""RichTextBuffer_SetRenderer(RichTextRenderer renderer)"""
return _richtext.RichTextBuffer_SetRenderer(*args, **kwargs)
def RichTextBuffer_GetBulletRightMargin(*args):
"""RichTextBuffer_GetBulletRightMargin() -> int"""
return _richtext.RichTextBuffer_GetBulletRightMargin(*args)
def RichTextBuffer_SetBulletRightMargin(*args, **kwargs):
"""RichTextBuffer_SetBulletRightMargin(int margin)"""
return _richtext.RichTextBuffer_SetBulletRightMargin(*args, **kwargs)
def RichTextBuffer_GetBulletProportion(*args):
"""RichTextBuffer_GetBulletProportion() -> float"""
return _richtext.RichTextBuffer_GetBulletProportion(*args)
def RichTextBuffer_SetBulletProportion(*args, **kwargs):
"""RichTextBuffer_SetBulletProportion(float prop)"""
return _richtext.RichTextBuffer_SetBulletProportion(*args, **kwargs)
#---------------------------------------------------------------------------
RICHTEXT_HANDLER_INCLUDE_STYLESHEET = _richtext.RICHTEXT_HANDLER_INCLUDE_STYLESHEET
RICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY = _richtext.RICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY
RICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES = _richtext.RICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES
RICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64 = _richtext.RICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64
RICHTEXT_HANDLER_NO_HEADER_FOOTER = _richtext.RICHTEXT_HANDLER_NO_HEADER_FOOTER
RICHTEXT_HANDLER_CONVERT_FACENAMES = _richtext.RICHTEXT_HANDLER_CONVERT_FACENAMES
class RichTextFileHandler(_core.Object):
"""Base class for file handlers"""
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__ = _richtext.delete_RichTextFileHandler
__del__ = lambda self : None;
def LoadStream(*args, **kwargs):
"""LoadStream(self, RichTextBuffer buffer, InputStream stream) -> bool"""
return _richtext.RichTextFileHandler_LoadStream(*args, **kwargs)
def SaveStream(*args, **kwargs):
"""SaveStream(self, RichTextBuffer buffer, wxOutputStream stream) -> bool"""
return _richtext.RichTextFileHandler_SaveStream(*args, **kwargs)
def LoadFile(*args, **kwargs):
"""LoadFile(self, RichTextBuffer buffer, String filename) -> bool"""
return _richtext.RichTextFileHandler_LoadFile(*args, **kwargs)
def SaveFile(*args, **kwargs):
"""SaveFile(self, RichTextBuffer buffer, String filename) -> bool"""
return _richtext.RichTextFileHandler_SaveFile(*args, **kwargs)
def CanHandle(*args, **kwargs):
"""CanHandle(self, String filename) -> bool"""
return _richtext.RichTextFileHandler_CanHandle(*args, **kwargs)
def CanSave(*args, **kwargs):
"""CanSave(self) -> bool"""
return _richtext.RichTextFileHandler_CanSave(*args, **kwargs)
def CanLoad(*args, **kwargs):
"""CanLoad(self) -> bool"""
return _richtext.RichTextFileHandler_CanLoad(*args, **kwargs)
def IsVisible(*args, **kwargs):
"""IsVisible(self) -> bool"""
return _richtext.RichTextFileHandler_IsVisible(*args, **kwargs)
def SetVisible(*args, **kwargs):
"""SetVisible(self, bool visible)"""
return _richtext.RichTextFileHandler_SetVisible(*args, **kwargs)
def SetName(*args, **kwargs):
"""SetName(self, String name)"""
return _richtext.RichTextFileHandler_SetName(*args, **kwargs)
def GetName(*args, **kwargs):
"""GetName(self) -> String"""
return _richtext.RichTextFileHandler_GetName(*args, **kwargs)
Name = property(GetName,SetName)
def SetExtension(*args, **kwargs):
"""SetExtension(self, String ext)"""
return _richtext.RichTextFileHandler_SetExtension(*args, **kwargs)
def GetExtension(*args, **kwargs):
"""GetExtension(self) -> String"""
return _richtext.RichTextFileHandler_GetExtension(*args, **kwargs)
Extension = property(GetExtension,SetExtension)
def SetType(*args, **kwargs):
"""SetType(self, int type)"""
return _richtext.RichTextFileHandler_SetType(*args, **kwargs)
def GetType(*args, **kwargs):
"""GetType(self) -> int"""
return _richtext.RichTextFileHandler_GetType(*args, **kwargs)
Type = property(GetType,SetType)
def SetFlags(*args, **kwargs):
"""SetFlags(self, int flags)"""
return _richtext.RichTextFileHandler_SetFlags(*args, **kwargs)
def GetFlags(*args, **kwargs):
"""GetFlags(self) -> int"""
return _richtext.RichTextFileHandler_GetFlags(*args, **kwargs)
Flags = property(GetFlags,SetFlags)
def SetEncoding(*args, **kwargs):
"""SetEncoding(self, String encoding)"""
return _richtext.RichTextFileHandler_SetEncoding(*args, **kwargs)
def GetEncoding(*args, **kwargs):
"""GetEncoding(self) -> String"""
return _richtext.RichTextFileHandler_GetEncoding(*args, **kwargs)
Encoding = property(GetEncoding,SetEncoding)
_richtext.RichTextFileHandler_swigregister(RichTextFileHandler)
class RichTextPlainTextHandler(RichTextFileHandler):
"""Proxy of C++ RichTextPlainTextHandler 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, String name=TextName, String ext=TextExt, int type=RICHTEXT_TYPE_TEXT) -> RichTextPlainTextHandler"""
_richtext.RichTextPlainTextHandler_swiginit(self,_richtext.new_RichTextPlainTextHandler(*args, **kwargs))
_richtext.RichTextPlainTextHandler_swigregister(RichTextPlainTextHandler)
TextName = cvar.TextName
TextExt = cvar.TextExt
#---------------------------------------------------------------------------
class RichTextRenderer(_core.Object):
"""Proxy of C++ RichTextRenderer 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
__swig_destroy__ = _richtext.delete_RichTextRenderer
__del__ = lambda self : None;
def DrawStandardBullet(*args, **kwargs):
"""
DrawStandardBullet(self, RichTextParagraph paragraph, DC dc, RichTextAttr attr,
Rect rect) -> bool
"""
return _richtext.RichTextRenderer_DrawStandardBullet(*args, **kwargs)
def DrawTextBullet(*args, **kwargs):
"""
DrawTextBullet(self, RichTextParagraph paragraph, DC dc, RichTextAttr attr,
Rect rect, String text) -> bool
"""
return _richtext.RichTextRenderer_DrawTextBullet(*args, **kwargs)
def DrawBitmapBullet(*args, **kwargs):
"""
DrawBitmapBullet(self, RichTextParagraph paragraph, DC dc, RichTextAttr attr,
Rect rect) -> bool
"""
return _richtext.RichTextRenderer_DrawBitmapBullet(*args, **kwargs)
def EnumerateStandardBulletNames(*args, **kwargs):
"""EnumerateStandardBulletNames(self, wxArrayString bulletNames) -> bool"""
return _richtext.RichTextRenderer_EnumerateStandardBulletNames(*args, **kwargs)
_richtext.RichTextRenderer_swigregister(RichTextRenderer)
class RichTextStdRenderer(RichTextRenderer):
"""Proxy of C++ RichTextStdRenderer 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) -> RichTextStdRenderer"""
_richtext.RichTextStdRenderer_swiginit(self,_richtext.new_RichTextStdRenderer(*args, **kwargs))
_richtext.RichTextStdRenderer_swigregister(RichTextStdRenderer)
#---------------------------------------------------------------------------
RE_READONLY = _richtext.RE_READONLY
RE_MULTILINE = _richtext.RE_MULTILINE
RE_CENTER_CARET = _richtext.RE_CENTER_CARET
RE_CENTRE_CARET = _richtext.RE_CENTRE_CARET
RICHTEXT_SHIFT_DOWN = _richtext.RICHTEXT_SHIFT_DOWN
RICHTEXT_CTRL_DOWN = _richtext.RICHTEXT_CTRL_DOWN
RICHTEXT_ALT_DOWN = _richtext.RICHTEXT_ALT_DOWN
class RichTextCtrl(_core.Control,_core.TextCtrlIface,_windows.ScrollHelper):
"""Proxy of C++ RichTextCtrl 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=RE_MULTILINE, Validator validator=DefaultValidator,
String name=RichTextCtrlNameStr) -> RichTextCtrl
"""
_richtext.RichTextCtrl_swiginit(self,_richtext.new_RichTextCtrl(*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=RE_MULTILINE, Validator validator=DefaultValidator,
String name=RichTextCtrlNameStr) -> bool
"""
return _richtext.RichTextCtrl_Create(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> String"""
return _richtext.RichTextCtrl_GetValue(*args, **kwargs)
def IsSingleLine(*args, **kwargs):
"""IsSingleLine(self) -> bool"""
return _richtext.RichTextCtrl_IsSingleLine(*args, **kwargs)
def IsMultiLine(*args, **kwargs):
"""IsMultiLine(self) -> bool"""
return _richtext.RichTextCtrl_IsMultiLine(*args, **kwargs)
def GetFilename(*args, **kwargs):
"""GetFilename(self) -> String"""
return _richtext.RichTextCtrl_GetFilename(*args, **kwargs)
def SetFilename(*args, **kwargs):
"""SetFilename(self, String filename)"""
return _richtext.RichTextCtrl_SetFilename(*args, **kwargs)
def SetDelayedLayoutThreshold(*args, **kwargs):
"""
SetDelayedLayoutThreshold(self, long threshold)
Set the threshold in character positions for doing layout optimization
during sizing.
"""
return _richtext.RichTextCtrl_SetDelayedLayoutThreshold(*args, **kwargs)
def GetDelayedLayoutThreshold(*args, **kwargs):
"""
GetDelayedLayoutThreshold(self) -> long
Get the threshold in character positions for doing layout optimization
during sizing.
"""
return _richtext.RichTextCtrl_GetDelayedLayoutThreshold(*args, **kwargs)
def GetFullLayoutRequired(*args, **kwargs):
"""GetFullLayoutRequired(self) -> bool"""
return _richtext.RichTextCtrl_GetFullLayoutRequired(*args, **kwargs)
def SetFullLayoutRequired(*args, **kwargs):
"""SetFullLayoutRequired(self, bool b)"""
return _richtext.RichTextCtrl_SetFullLayoutRequired(*args, **kwargs)
def GetFullLayoutTime(*args, **kwargs):
"""GetFullLayoutTime(self) -> wxLongLong"""
return _richtext.RichTextCtrl_GetFullLayoutTime(*args, **kwargs)
def SetFullLayoutTime(*args, **kwargs):
"""SetFullLayoutTime(self, wxLongLong t)"""
return _richtext.RichTextCtrl_SetFullLayoutTime(*args, **kwargs)
def GetFullLayoutSavedPosition(*args, **kwargs):
"""GetFullLayoutSavedPosition(self) -> long"""
return _richtext.RichTextCtrl_GetFullLayoutSavedPosition(*args, **kwargs)
def SetFullLayoutSavedPosition(*args, **kwargs):
"""SetFullLayoutSavedPosition(self, long p)"""
return _richtext.RichTextCtrl_SetFullLayoutSavedPosition(*args, **kwargs)
def ForceDelayedLayout(*args, **kwargs):
"""ForceDelayedLayout(self)"""
return _richtext.RichTextCtrl_ForceDelayedLayout(*args, **kwargs)
def SetTextCursor(*args, **kwargs):
"""
SetTextCursor(self, Cursor cursor)
Set text cursor
"""
return _richtext.RichTextCtrl_SetTextCursor(*args, **kwargs)
def GetTextCursor(*args, **kwargs):
"""
GetTextCursor(self) -> Cursor
Get text cursor
"""
return _richtext.RichTextCtrl_GetTextCursor(*args, **kwargs)
def SetURLCursor(*args, **kwargs):
"""
SetURLCursor(self, Cursor cursor)
Set URL cursor
"""
return _richtext.RichTextCtrl_SetURLCursor(*args, **kwargs)
def GetURLCursor(*args, **kwargs):
"""
GetURLCursor(self) -> Cursor
Get URL cursor
"""
return _richtext.RichTextCtrl_GetURLCursor(*args, **kwargs)
def GetCaretAtLineStart(*args, **kwargs):
"""GetCaretAtLineStart(self) -> bool"""
return _richtext.RichTextCtrl_GetCaretAtLineStart(*args, **kwargs)
def SetCaretAtLineStart(*args, **kwargs):
"""SetCaretAtLineStart(self, bool atStart)"""
return _richtext.RichTextCtrl_SetCaretAtLineStart(*args, **kwargs)
def GetDragging(*args, **kwargs):
"""GetDragging(self) -> bool"""
return _richtext.RichTextCtrl_GetDragging(*args, **kwargs)
def SetDragging(*args, **kwargs):
"""SetDragging(self, bool dragging)"""
return _richtext.RichTextCtrl_SetDragging(*args, **kwargs)
def GetPreDrag(*args, **kwargs):
"""GetPreDrag(self) -> bool"""
return _richtext.RichTextCtrl_GetPreDrag(*args, **kwargs)
def SetPreDrag(*args, **kwargs):
"""SetPreDrag(self, bool pd)"""
return _richtext.RichTextCtrl_SetPreDrag(*args, **kwargs)
def GetDragStartPoint(*args, **kwargs):
"""GetDragStartPoint(self) -> Point"""
return _richtext.RichTextCtrl_GetDragStartPoint(*args, **kwargs)
def SetDragStartPoint(*args, **kwargs):
"""SetDragStartPoint(self, Point sp)"""
return _richtext.RichTextCtrl_SetDragStartPoint(*args, **kwargs)
def GetDragStartTime(*args, **kwargs):
"""GetDragStartTime(self) -> DateTime"""
return _richtext.RichTextCtrl_GetDragStartTime(*args, **kwargs)
def SetDragStartTime(*args, **kwargs):
"""SetDragStartTime(self, DateTime st)"""
return _richtext.RichTextCtrl_SetDragStartTime(*args, **kwargs)
def GetBufferBitmap(*args, **kwargs):
"""GetBufferBitmap(self) -> Bitmap"""
return _richtext.RichTextCtrl_GetBufferBitmap(*args, **kwargs)
def GetContextMenu(*args, **kwargs):
"""GetContextMenu(self) -> Menu"""
return _richtext.RichTextCtrl_GetContextMenu(*args, **kwargs)
def SetContextMenu(*args, **kwargs):
"""SetContextMenu(self, Menu menu)"""
return _richtext.RichTextCtrl_SetContextMenu(*args, **kwargs)
def GetSelectionAnchor(*args, **kwargs):
"""GetSelectionAnchor(self) -> long"""
return _richtext.RichTextCtrl_GetSelectionAnchor(*args, **kwargs)
def SetSelectionAnchor(*args, **kwargs):
"""SetSelectionAnchor(self, long anchor)"""
return _richtext.RichTextCtrl_SetSelectionAnchor(*args, **kwargs)
def LoadFile(*args, **kwargs):
"""
LoadFile(self, String file, int type=RICHTEXT_TYPE_ANY) -> bool
Load the contents of the document from the given filename.
"""
return _richtext.RichTextCtrl_LoadFile(*args, **kwargs)
def SaveFile(*args, **kwargs):
"""
SaveFile(self, String file=EmptyString, int type=RICHTEXT_TYPE_ANY) -> bool
Save the contents of the document to the given filename, or if the
empty string is passed then to the filename set with `SetFilename`.
"""
return _richtext.RichTextCtrl_SaveFile(*args, **kwargs)
def SetHandlerFlags(*args, **kwargs):
"""
SetHandlerFlags(self, int flags)
Set the handler flags, controlling loading and saving.
"""
return _richtext.RichTextCtrl_SetHandlerFlags(*args, **kwargs)
def GetHandlerFlags(*args, **kwargs):
"""
GetHandlerFlags(self) -> int
Get the handler flags, controlling loading and saving.
"""
return _richtext.RichTextCtrl_GetHandlerFlags(*args, **kwargs)
def SetMaxLength(*args, **kwargs):
"""
SetMaxLength(self, unsigned long len)
Set the max number of characters which may be entered in a single line
text control.
"""
return _richtext.RichTextCtrl_SetMaxLength(*args, **kwargs)
def SetStyle(*args, **kwargs):
"""
SetStyle(self, RichTextRange range, RichTextAttr style) -> bool
Set the style for the text in ``range`` to ``style``
"""
return _richtext.RichTextCtrl_SetStyle(*args, **kwargs)
def GetStyle(*args, **kwargs):
"""
GetStyle(self, long position, RichTextAttr style) -> bool
Retrieve the style used at the given position. Copies the style
values at ``position`` into the ``style`` parameter and returns ``True``
if successful. Returns ``False`` otherwise.
"""
return _richtext.RichTextCtrl_GetStyle(*args, **kwargs)
def GetStyleForRange(*args, **kwargs):
"""
GetStyleForRange(self, RichTextRange range, RichTextAttr style) -> bool
Get the common set of styles for the range
"""
return _richtext.RichTextCtrl_GetStyleForRange(*args, **kwargs)
def SetStyleEx(*args, **kwargs):
"""
SetStyleEx(self, RichTextRange range, RichTextAttr style, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool
Extended style setting operation with flags including:
RICHTEXT_SETSTYLE_WITH_UNDO, RICHTEXT_SETSTYLE_OPTIMIZE,
RICHTEXT_SETSTYLE_PARAGRAPHS_ONLY, RICHTEXT_SETSTYLE_CHARACTERS_ONLY
"""
return _richtext.RichTextCtrl_SetStyleEx(*args, **kwargs)
def GetUncombinedStyle(*args, **kwargs):
"""
GetUncombinedStyle(self, long position, RichTextAttr style) -> bool
Get the content (uncombined) attributes for this position. Copies the
style values at ``position`` into the ``style`` parameter and returns
``True`` if successful. Returns ``False`` otherwise.
"""
return _richtext.RichTextCtrl_GetUncombinedStyle(*args, **kwargs)
def SetDefaultStyle(*args, **kwargs):
"""
SetDefaultStyle(self, RichTextAttr style) -> bool
Set the style used by default for the rich text document.
"""
return _richtext.RichTextCtrl_SetDefaultStyle(*args, **kwargs)
def GetDefaultStyle(*args, **kwargs):
"""
GetDefaultStyle(self) -> RichTextAttr
Retrieves a copy of the default style object.
"""
return _richtext.RichTextCtrl_GetDefaultStyle(*args, **kwargs)
def SetListStyle(*args, **kwargs):
"""
SetListStyle(self, RichTextRange range, String defName, int flags=RICHTEXT_SETSTYLE_WITH_UNDO,
int startFrom=1, int specifiedLevel=-1) -> bool
"""
return _richtext.RichTextCtrl_SetListStyle(*args, **kwargs)
def ClearListStyle(*args, **kwargs):
"""ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool"""
return _richtext.RichTextCtrl_ClearListStyle(*args, **kwargs)
def NumberList(*args, **kwargs):
"""
NumberList(self, RichTextRange range, String defName, int flags=RICHTEXT_SETSTYLE_WITH_UNDO,
int startFrom=1, int specifiedLevel=-1) -> bool
"""
return _richtext.RichTextCtrl_NumberList(*args, **kwargs)
def PromoteList(*args, **kwargs):
"""
PromoteList(self, int promoteBy, RichTextRange range, String defName,
int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int specifiedLevel=-1) -> bool
"""
return _richtext.RichTextCtrl_PromoteList(*args, **kwargs)
def Delete(*args, **kwargs):
"""Delete(self, RichTextRange range) -> bool"""
return _richtext.RichTextCtrl_Delete(*args, **kwargs)
def HitTestXY(*args, **kwargs):
"""
HitTestRC(self, Point pt) --> (result, col, row)
Returns the column and row of the given point in pixels. Note that
``pt`` should be given in device coordinates, and not be adjusted for
the client area origin nor for scrolling. The return value is a tuple
of the hit test result and the column and row values.
"""
return _richtext.RichTextCtrl_HitTestXY(*args, **kwargs)
def FindContainerAtPoint(*args, **kwargs):
"""
FindContainerAtPoint(self, Point pt, long position, int hit, RichTextObject hitObj,
int flags=0) -> RichTextParagraphLayoutBox
"""
return _richtext.RichTextCtrl_FindContainerAtPoint(*args, **kwargs)
def DeleteSelection(*args, **kwargs):
"""
DeleteSelection(self)
Remove the current selection.
"""
return _richtext.RichTextCtrl_DeleteSelection(*args, **kwargs)
def CanDeleteSelection(*args, **kwargs):
"""
CanDeleteSelection(self) -> bool
Returns ``True`` if the selection can be removed from the document.
"""
return _richtext.RichTextCtrl_CanDeleteSelection(*args, **kwargs)
def HasSelection(*args, **kwargs):
"""HasSelection(self) -> bool"""
return _richtext.RichTextCtrl_HasSelection(*args, **kwargs)
def WriteImage(*args, **kwargs):
"""
WriteImage(self, Image image, int bitmapType=BITMAP_TYPE_PNG) -> bool
Write an image at the current insertion point. Supply optional type to
use for internal and file storage of the raw data.
"""
return _richtext.RichTextCtrl_WriteImage(*args, **kwargs)
def WriteBitmap(*args, **kwargs):
"""
WriteBitmap(self, Bitmap bitmap, int bitmapType=BITMAP_TYPE_PNG) -> bool
Write a bitmap at the current insertion point. Supply optional type to
use for internal and file storage of the raw data.
"""
return _richtext.RichTextCtrl_WriteBitmap(*args, **kwargs)
def WriteImageFile(*args, **kwargs):
"""
WriteImageFile(self, String filename, int bitmapType) -> bool
Load an image from file and write at the current insertion point.
"""
return _richtext.RichTextCtrl_WriteImageFile(*args, **kwargs)
def WriteImageBlock(*args, **kwargs):
"""
WriteImageBlock(self, wxRichTextImageBlock imageBlock) -> bool
Write an image block at the current insertion point.
"""
return _richtext.RichTextCtrl_WriteImageBlock(*args, **kwargs)
def Newline(*args, **kwargs):
"""
Newline(self) -> bool
Insert a newline (actually paragraph) at the current insertion point.
"""
return _richtext.RichTextCtrl_Newline(*args, **kwargs)
def LineBreak(*args, **kwargs):
"""
LineBreak(self) -> bool
Insert a line break at the current insertion point.
"""
return _richtext.RichTextCtrl_LineBreak(*args, **kwargs)
def SetBasicStyle(*args, **kwargs):
"""SetBasicStyle(self, RichTextAttr style)"""
return _richtext.RichTextCtrl_SetBasicStyle(*args, **kwargs)
def GetBasicStyle(*args, **kwargs):
"""
GetBasicStyle(self) -> RichTextAttr
Get basic (overall) style
"""
return _richtext.RichTextCtrl_GetBasicStyle(*args, **kwargs)
def BeginStyle(*args, **kwargs):
"""
BeginStyle(self, RichTextAttr style) -> bool
Begin using a style
"""
return _richtext.RichTextCtrl_BeginStyle(*args, **kwargs)
def EndStyle(*args, **kwargs):
"""
EndStyle(self) -> bool
End the style
"""
return _richtext.RichTextCtrl_EndStyle(*args, **kwargs)
def EndAllStyles(*args, **kwargs):
"""
EndAllStyles(self) -> bool
End all styles
"""
return _richtext.RichTextCtrl_EndAllStyles(*args, **kwargs)
def BeginBold(*args, **kwargs):
"""
BeginBold(self) -> bool
Begin using bold
"""
return _richtext.RichTextCtrl_BeginBold(*args, **kwargs)
def EndBold(*args, **kwargs):
"""
EndBold(self) -> bool
End using bold
"""
return _richtext.RichTextCtrl_EndBold(*args, **kwargs)
def BeginItalic(*args, **kwargs):
"""
BeginItalic(self) -> bool
Begin using italic
"""
return _richtext.RichTextCtrl_BeginItalic(*args, **kwargs)
def EndItalic(*args, **kwargs):
"""
EndItalic(self) -> bool
End using italic
"""
return _richtext.RichTextCtrl_EndItalic(*args, **kwargs)
def BeginUnderline(*args, **kwargs):
"""
BeginUnderline(self) -> bool
Begin using underline
"""
return _richtext.RichTextCtrl_BeginUnderline(*args, **kwargs)
def EndUnderline(*args, **kwargs):
"""
EndUnderline(self) -> bool
End using underline
"""
return _richtext.RichTextCtrl_EndUnderline(*args, **kwargs)
def BeginFontSize(*args, **kwargs):
"""
BeginFontSize(self, int pointSize) -> bool
Begin using point size
"""
return _richtext.RichTextCtrl_BeginFontSize(*args, **kwargs)
def EndFontSize(*args, **kwargs):
"""
EndFontSize(self) -> bool
End using point size
"""
return _richtext.RichTextCtrl_EndFontSize(*args, **kwargs)
def BeginFont(*args, **kwargs):
"""
BeginFont(self, Font font) -> bool
Begin using this font
"""
return _richtext.RichTextCtrl_BeginFont(*args, **kwargs)
def EndFont(*args, **kwargs):
"""
EndFont(self) -> bool
End using a font
"""
return _richtext.RichTextCtrl_EndFont(*args, **kwargs)
def BeginTextColour(*args, **kwargs):
"""
BeginTextColour(self, Colour colour) -> bool
Begin using this colour
"""
return _richtext.RichTextCtrl_BeginTextColour(*args, **kwargs)
def EndTextColour(*args, **kwargs):
"""
EndTextColour(self) -> bool
End using a colour
"""
return _richtext.RichTextCtrl_EndTextColour(*args, **kwargs)
def BeginAlignment(*args, **kwargs):
"""
BeginAlignment(self, int alignment) -> bool
Begin using alignment
"""
return _richtext.RichTextCtrl_BeginAlignment(*args, **kwargs)
def EndAlignment(*args, **kwargs):
"""
EndAlignment(self) -> bool
End alignment
"""
return _richtext.RichTextCtrl_EndAlignment(*args, **kwargs)
def BeginLeftIndent(*args, **kwargs):
"""
BeginLeftIndent(self, int leftIndent, int leftSubIndent=0) -> bool
Begin left indent
"""
return _richtext.RichTextCtrl_BeginLeftIndent(*args, **kwargs)
def EndLeftIndent(*args, **kwargs):
"""
EndLeftIndent(self) -> bool
End left indent
"""
return _richtext.RichTextCtrl_EndLeftIndent(*args, **kwargs)
def BeginRightIndent(*args, **kwargs):
"""
BeginRightIndent(self, int rightIndent) -> bool
Begin right indent
"""
return _richtext.RichTextCtrl_BeginRightIndent(*args, **kwargs)
def EndRightIndent(*args, **kwargs):
"""
EndRightIndent(self) -> bool
End right indent
"""
return _richtext.RichTextCtrl_EndRightIndent(*args, **kwargs)
def BeginParagraphSpacing(*args, **kwargs):
"""
BeginParagraphSpacing(self, int before, int after) -> bool
Begin paragraph spacing
"""
return _richtext.RichTextCtrl_BeginParagraphSpacing(*args, **kwargs)
def EndParagraphSpacing(*args, **kwargs):
"""
EndParagraphSpacing(self) -> bool
End paragraph spacing
"""
return _richtext.RichTextCtrl_EndParagraphSpacing(*args, **kwargs)
def BeginLineSpacing(*args, **kwargs):
"""
BeginLineSpacing(self, int lineSpacing) -> bool
Begin line spacing
"""
return _richtext.RichTextCtrl_BeginLineSpacing(*args, **kwargs)
def EndLineSpacing(*args, **kwargs):
"""
EndLineSpacing(self) -> bool
End line spacing
"""
return _richtext.RichTextCtrl_EndLineSpacing(*args, **kwargs)
def BeginNumberedBullet(*args, **kwargs):
"""
BeginNumberedBullet(self, int bulletNumber, int leftIndent, int leftSubIndent,
int bulletStyle=wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD) -> bool
Begin numbered bullet
"""
return _richtext.RichTextCtrl_BeginNumberedBullet(*args, **kwargs)
def EndNumberedBullet(*args, **kwargs):
"""
EndNumberedBullet(self) -> bool
End numbered bullet
"""
return _richtext.RichTextCtrl_EndNumberedBullet(*args, **kwargs)
def BeginSymbolBullet(*args, **kwargs):
"""
BeginSymbolBullet(self, String symbol, int leftIndent, int leftSubIndent, int bulletStyle=TEXT_ATTR_BULLET_STYLE_SYMBOL) -> bool
Begin symbol bullet
"""
return _richtext.RichTextCtrl_BeginSymbolBullet(*args, **kwargs)
def EndSymbolBullet(*args, **kwargs):
"""
EndSymbolBullet(self) -> bool
End symbol bullet
"""
return _richtext.RichTextCtrl_EndSymbolBullet(*args, **kwargs)
def BeginStandardBullet(*args, **kwargs):
"""
BeginStandardBullet(self, String bulletName, int leftIndent, int leftSubIndent,
int bulletStyle=TEXT_ATTR_BULLET_STYLE_STANDARD) -> bool
Begin standard bullet
"""
return _richtext.RichTextCtrl_BeginStandardBullet(*args, **kwargs)
def EndStandardBullet(*args, **kwargs):
"""
EndStandardBullet(self) -> bool
End standard bullet
"""
return _richtext.RichTextCtrl_EndStandardBullet(*args, **kwargs)
def BeginCharacterStyle(*args, **kwargs):
"""
BeginCharacterStyle(self, String characterStyle) -> bool
Begin named character style
"""
return _richtext.RichTextCtrl_BeginCharacterStyle(*args, **kwargs)
def EndCharacterStyle(*args, **kwargs):
"""
EndCharacterStyle(self) -> bool
End named character style
"""
return _richtext.RichTextCtrl_EndCharacterStyle(*args, **kwargs)
def BeginParagraphStyle(*args, **kwargs):
"""
BeginParagraphStyle(self, String paragraphStyle) -> bool
Begin named paragraph style
"""
return _richtext.RichTextCtrl_BeginParagraphStyle(*args, **kwargs)
def EndParagraphStyle(*args, **kwargs):
"""
EndParagraphStyle(self) -> bool
End named character style
"""
return _richtext.RichTextCtrl_EndParagraphStyle(*args, **kwargs)
def BeginListStyle(*args, **kwargs):
"""
BeginListStyle(self, String listStyle, int level=1, int number=1) -> bool
Begin named list style.
"""
return _richtext.RichTextCtrl_BeginListStyle(*args, **kwargs)
def EndListStyle(*args, **kwargs):
"""
EndListStyle(self) -> bool
End named list style.
"""
return _richtext.RichTextCtrl_EndListStyle(*args, **kwargs)
def BeginURL(*args, **kwargs):
"""
BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool
Begin URL.
"""
return _richtext.RichTextCtrl_BeginURL(*args, **kwargs)
def EndURL(*args, **kwargs):
"""
EndURL(self) -> bool
End URL.
"""
return _richtext.RichTextCtrl_EndURL(*args, **kwargs)
def SetDefaultStyleToCursorStyle(*args, **kwargs):
"""
SetDefaultStyleToCursorStyle(self) -> bool
Sets the default style to the style under the cursor
"""
return _richtext.RichTextCtrl_SetDefaultStyleToCursorStyle(*args, **kwargs)
def SelectNone(*args, **kwargs):
"""
SelectNone(self)
Clear the selection
"""
return _richtext.RichTextCtrl_SelectNone(*args, **kwargs)
def SelectWord(*args, **kwargs):
"""
SelectWord(self, long position) -> bool
Select the word at the given character position
"""
return _richtext.RichTextCtrl_SelectWord(*args, **kwargs)
def GetSelectionRange(*args, **kwargs):
"""
GetSelectionRange(self) -> RichTextRange
Get the selection range in character positions.
"""
return _richtext.RichTextCtrl_GetSelectionRange(*args, **kwargs)
def SetSelectionRange(*args, **kwargs):
"""
SetSelectionRange(self, RichTextRange range)
Set the selection range in character positions. The end point of range
is specified as the last character position of the span of text, plus
one. So, for example, to set the selection for a character at position
5, use the range (5,6).
"""
return _richtext.RichTextCtrl_SetSelectionRange(*args, **kwargs)
def GetInternalSelectionRange(*args, **kwargs):
"""
GetInternalSelectionRange(self) -> RichTextRange
Get the selection range in character positions. The range is in
internal format, i.e. a single character selection is denoted by (n,n).
"""
return _richtext.RichTextCtrl_GetInternalSelectionRange(*args, **kwargs)
def SetInternalSelectionRange(*args, **kwargs):
"""
SetInternalSelectionRange(self, RichTextRange range)
Set the selection range in character positions. The range is in
internal format, i.e. a single character selection is denoted by (n,n).
"""
return _richtext.RichTextCtrl_SetInternalSelectionRange(*args, **kwargs)
def AddParagraph(*args, **kwargs):
"""
AddParagraph(self, String text) -> RichTextRange
Add a new paragraph of text to the end of the buffer
"""
return _richtext.RichTextCtrl_AddParagraph(*args, **kwargs)
def AddImage(*args, **kwargs):
"""
AddImage(self, Image image) -> RichTextRange
Add an image
"""
return _richtext.RichTextCtrl_AddImage(*args, **kwargs)
def LayoutContent(*args, **kwargs):
"""
LayoutContent(self, bool onlyVisibleRect=False) -> bool
Layout the buffer: which we must do before certain operations, such as
setting the caret position.
"""
return _richtext.RichTextCtrl_LayoutContent(*args, **kwargs)
def MoveCaret(*args, **kwargs):
"""
MoveCaret(self, long pos, bool showAtLineStart=False) -> bool
Move the caret to the given character position
"""
return _richtext.RichTextCtrl_MoveCaret(*args, **kwargs)
def MoveRight(*args, **kwargs):
"""
MoveRight(self, int noPositions=1, int flags=0) -> bool
Move right
"""
return _richtext.RichTextCtrl_MoveRight(*args, **kwargs)
def MoveLeft(*args, **kwargs):
"""
MoveLeft(self, int noPositions=1, int flags=0) -> bool
Move left
"""
return _richtext.RichTextCtrl_MoveLeft(*args, **kwargs)
def MoveUp(*args, **kwargs):
"""
MoveUp(self, int noLines=1, int flags=0) -> bool
Move up
"""
return _richtext.RichTextCtrl_MoveUp(*args, **kwargs)
def MoveDown(*args, **kwargs):
"""
MoveDown(self, int noLines=1, int flags=0) -> bool
Move down
"""
return _richtext.RichTextCtrl_MoveDown(*args, **kwargs)
def MoveToLineEnd(*args, **kwargs):
"""
MoveToLineEnd(self, int flags=0) -> bool
Move to the end of the line
"""
return _richtext.RichTextCtrl_MoveToLineEnd(*args, **kwargs)
def MoveToLineStart(*args, **kwargs):
"""
MoveToLineStart(self, int flags=0) -> bool
Move to the start of the line
"""
return _richtext.RichTextCtrl_MoveToLineStart(*args, **kwargs)
def MoveToParagraphEnd(*args, **kwargs):
"""
MoveToParagraphEnd(self, int flags=0) -> bool
Move to the end of the paragraph
"""
return _richtext.RichTextCtrl_MoveToParagraphEnd(*args, **kwargs)
def MoveToParagraphStart(*args, **kwargs):
"""
MoveToParagraphStart(self, int flags=0) -> bool
Move to the start of the paragraph
"""
return _richtext.RichTextCtrl_MoveToParagraphStart(*args, **kwargs)
def MoveHome(*args, **kwargs):
"""
MoveHome(self, int flags=0) -> bool
Move to the start of the buffer
"""
return _richtext.RichTextCtrl_MoveHome(*args, **kwargs)
def MoveEnd(*args, **kwargs):
"""
MoveEnd(self, int flags=0) -> bool
Move to the end of the buffer
"""
return _richtext.RichTextCtrl_MoveEnd(*args, **kwargs)
def PageUp(*args, **kwargs):
"""
PageUp(self, int noPages=1, int flags=0) -> bool
Move n pages up
"""
return _richtext.RichTextCtrl_PageUp(*args, **kwargs)
def PageDown(*args, **kwargs):
"""
PageDown(self, int noPages=1, int flags=0) -> bool
Move n pages down
"""
return _richtext.RichTextCtrl_PageDown(*args, **kwargs)
def WordLeft(*args, **kwargs):
"""
WordLeft(self, int noPages=1, int flags=0) -> bool
Move n words left
"""
return _richtext.RichTextCtrl_WordLeft(*args, **kwargs)
def WordRight(*args, **kwargs):
"""
WordRight(self, int noPages=1, int flags=0) -> bool
Move n words right
"""
return _richtext.RichTextCtrl_WordRight(*args, **kwargs)
def GetBuffer(*args, **kwargs):
"""
GetBuffer(self) -> RichTextBuffer
Returns the buffer associated with the control.
"""
return _richtext.RichTextCtrl_GetBuffer(*args, **kwargs)
def BeginBatchUndo(*args, **kwargs):
"""
BeginBatchUndo(self, String cmdName) -> bool
Start batching undo history for commands
"""
return _richtext.RichTextCtrl_BeginBatchUndo(*args, **kwargs)
def EndBatchUndo(*args, **kwargs):
"""
EndBatchUndo(self) -> bool
End batching undo history for commands.
"""
return _richtext.RichTextCtrl_EndBatchUndo(*args, **kwargs)
def BatchingUndo(*args, **kwargs):
"""
BatchingUndo(self) -> bool
Are we batching undo history for commands?
"""
return _richtext.RichTextCtrl_BatchingUndo(*args, **kwargs)
def BeginSuppressUndo(*args, **kwargs):
"""
BeginSuppressUndo(self) -> bool
Start suppressing undo history for commands.
"""
return _richtext.RichTextCtrl_BeginSuppressUndo(*args, **kwargs)
def EndSuppressUndo(*args, **kwargs):
"""
EndSuppressUndo(self) -> bool
End suppressing undo history for commands.
"""
return _richtext.RichTextCtrl_EndSuppressUndo(*args, **kwargs)
def SuppressingUndo(*args, **kwargs):
"""
SuppressingUndo(self) -> bool
Are we suppressing undo history for commands?
"""
return _richtext.RichTextCtrl_SuppressingUndo(*args, **kwargs)
def HasCharacterAttributes(*args, **kwargs):
"""
HasCharacterAttributes(self, RichTextRange range, RichTextAttr style) -> bool
Test if this whole range has character attributes of the specified
kind. If any of the attributes are different within the range, the
test fails. You can use this to implement, for example, bold button
updating. ``style`` must have flags indicating which attributes are of
interest.
"""
return _richtext.RichTextCtrl_HasCharacterAttributes(*args, **kwargs)
def HasParagraphAttributes(*args, **kwargs):
"""
HasParagraphAttributes(self, RichTextRange range, RichTextAttr style) -> bool
Test if this whole range has paragraph attributes of the specified
kind. If any of the attributes are different within the range, the
test fails. You can use this to implement, for example, centering
button updating. style must have flags indicating which attributes are
of interest.
"""
return _richtext.RichTextCtrl_HasParagraphAttributes(*args, **kwargs)
def IsSelectionBold(*args, **kwargs):
"""
IsSelectionBold(self) -> bool
Is all of the selection bold?
"""
return _richtext.RichTextCtrl_IsSelectionBold(*args, **kwargs)
def IsSelectionItalics(*args, **kwargs):
"""
IsSelectionItalics(self) -> bool
Is all of the selection italics?
"""
return _richtext.RichTextCtrl_IsSelectionItalics(*args, **kwargs)
def IsSelectionUnderlined(*args, **kwargs):
"""
IsSelectionUnderlined(self) -> bool
Is all of the selection underlined?
"""
return _richtext.RichTextCtrl_IsSelectionUnderlined(*args, **kwargs)
def DoesSelectionHaveTextEffectFlag(*args, **kwargs):
"""DoesSelectionHaveTextEffectFlag(self, int flag) -> bool"""
return _richtext.RichTextCtrl_DoesSelectionHaveTextEffectFlag(*args, **kwargs)
def IsSelectionAligned(*args, **kwargs):
"""
IsSelectionAligned(self, int alignment) -> bool
Is all of the selection aligned according to the specified flag?
"""
return _richtext.RichTextCtrl_IsSelectionAligned(*args, **kwargs)
def ApplyBoldToSelection(*args, **kwargs):
"""
ApplyBoldToSelection(self) -> bool
Apply bold to the selection
"""
return _richtext.RichTextCtrl_ApplyBoldToSelection(*args, **kwargs)
def ApplyItalicToSelection(*args, **kwargs):
"""
ApplyItalicToSelection(self) -> bool
Apply italic to the selection
"""
return _richtext.RichTextCtrl_ApplyItalicToSelection(*args, **kwargs)
def ApplyUnderlineToSelection(*args, **kwargs):
"""
ApplyUnderlineToSelection(self) -> bool
Apply underline to the selection
"""
return _richtext.RichTextCtrl_ApplyUnderlineToSelection(*args, **kwargs)
def ApplyTextEffectToSelection(*args, **kwargs):
"""ApplyTextEffectToSelection(self, int flags) -> bool"""
return _richtext.RichTextCtrl_ApplyTextEffectToSelection(*args, **kwargs)
def ApplyAlignmentToSelection(*args, **kwargs):
"""
ApplyAlignmentToSelection(self, int alignment) -> bool
Apply alignment to the selection
"""
return _richtext.RichTextCtrl_ApplyAlignmentToSelection(*args, **kwargs)
def ApplyStyle(*args, **kwargs):
"""
ApplyStyle(self, wxRichTextStyleDefinition def) -> bool
Apply a named style to the selection
"""
return _richtext.RichTextCtrl_ApplyStyle(*args, **kwargs)
def SetStyleSheet(*args, **kwargs):
"""
SetStyleSheet(self, wxRichTextStyleSheet styleSheet)
Set style sheet, if any.
"""
return _richtext.RichTextCtrl_SetStyleSheet(*args, **kwargs)
def GetStyleSheet(*args, **kwargs):
"""GetStyleSheet(self) -> wxRichTextStyleSheet"""
return _richtext.RichTextCtrl_GetStyleSheet(*args, **kwargs)
def PushStyleSheet(*args, **kwargs):
"""
PushStyleSheet(self, wxRichTextStyleSheet styleSheet) -> bool
Push style sheet to top of stack
"""
return _richtext.RichTextCtrl_PushStyleSheet(*args, **kwargs)
def PopStyleSheet(*args, **kwargs):
"""
PopStyleSheet(self) -> wxRichTextStyleSheet
Pop style sheet from top of stack
"""
return _richtext.RichTextCtrl_PopStyleSheet(*args, **kwargs)
def ApplyStyleSheet(*args, **kwargs):
"""
ApplyStyleSheet(self, wxRichTextStyleSheet styleSheet=None) -> bool
Apply the style sheet to the buffer, for example if the styles have
changed.
"""
return _richtext.RichTextCtrl_ApplyStyleSheet(*args, **kwargs)
def ShowContextMenu(*args, **kwargs):
"""ShowContextMenu(self, Menu menu, Point pt, bool addPropertyCommands=True) -> bool"""
return _richtext.RichTextCtrl_ShowContextMenu(*args, **kwargs)
def PrepareContextMenu(*args, **kwargs):
"""PrepareContextMenu(self, Menu menu, Point pt, bool addPropertyCommands=True) -> int"""
return _richtext.RichTextCtrl_PrepareContextMenu(*args, **kwargs)
Buffer = property(GetBuffer)
DelayedLayoutThreshold = property(GetDelayedLayoutThreshold,SetDelayedLayoutThreshold)
Filename = property(GetFilename,SetFilename)
InternalSelectionRange = property(GetInternalSelectionRange,SetInternalSelectionRange)
SelectionRange = property(GetSelectionRange,SetSelectionRange)
StyleSheet = property(GetStyleSheet,SetStyleSheet)
TextCursor = property(GetTextCursor,SetTextCursor)
URLCursor = property(GetURLCursor,SetURLCursor)
def SetupScrollbars(*args, **kwargs):
"""SetupScrollbars(self, bool atTop=False)"""
return _richtext.RichTextCtrl_SetupScrollbars(*args, **kwargs)
def KeyboardNavigate(*args, **kwargs):
"""KeyboardNavigate(self, int keyCode, int flags) -> bool"""
return _richtext.RichTextCtrl_KeyboardNavigate(*args, **kwargs)
def PositionCaret(*args, **kwargs):
"""PositionCaret(self)"""
return _richtext.RichTextCtrl_PositionCaret(*args, **kwargs)
def ExtendSelection(*args, **kwargs):
"""ExtendSelection(self, long oldPosition, long newPosition, int flags) -> bool"""
return _richtext.RichTextCtrl_ExtendSelection(*args, **kwargs)
def ScrollIntoView(*args, **kwargs):
"""ScrollIntoView(self, long position, int keyCode) -> bool"""
return _richtext.RichTextCtrl_ScrollIntoView(*args, **kwargs)
def SetCaretPosition(*args, **kwargs):
"""SetCaretPosition(self, long position, bool showAtLineStart=False)"""
return _richtext.RichTextCtrl_SetCaretPosition(*args, **kwargs)
def GetCaretPosition(*args, **kwargs):
"""GetCaretPosition(self) -> long"""
return _richtext.RichTextCtrl_GetCaretPosition(*args, **kwargs)
def GetAdjustedCaretPosition(*args, **kwargs):
"""GetAdjustedCaretPosition(self, long caretPos) -> long"""
return _richtext.RichTextCtrl_GetAdjustedCaretPosition(*args, **kwargs)
def MoveCaretForward(*args, **kwargs):
"""MoveCaretForward(self, long oldPosition)"""
return _richtext.RichTextCtrl_MoveCaretForward(*args, **kwargs)
def MoveCaretBack(*args, **kwargs):
"""MoveCaretBack(self, long oldPosition)"""
return _richtext.RichTextCtrl_MoveCaretBack(*args, **kwargs)
def GetCaretPositionForIndex(*args, **kwargs):
"""GetCaretPositionForIndex(self, long position, Rect rect) -> bool"""
return _richtext.RichTextCtrl_GetCaretPositionForIndex(*args, **kwargs)
def GetVisibleLineForCaretPosition(*args, **kwargs):
"""GetVisibleLineForCaretPosition(self, long caretPosition) -> RichTextLine"""
return _richtext.RichTextCtrl_GetVisibleLineForCaretPosition(*args, **kwargs)
def GetCommandProcessor(*args, **kwargs):
"""GetCommandProcessor(self) -> wxCommandProcessor"""
return _richtext.RichTextCtrl_GetCommandProcessor(*args, **kwargs)
def DeleteSelectedContent(*args, **kwargs):
"""DeleteSelectedContent(self, long OUTPUT) -> bool"""
return _richtext.RichTextCtrl_DeleteSelectedContent(*args, **kwargs)
def GetPhysicalPoint(*args, **kwargs):
"""GetPhysicalPoint(self, Point ptLogical) -> Point"""
return _richtext.RichTextCtrl_GetPhysicalPoint(*args, **kwargs)
def GetLogicalPoint(*args, **kwargs):
"""GetLogicalPoint(self, Point ptPhysical) -> Point"""
return _richtext.RichTextCtrl_GetLogicalPoint(*args, **kwargs)
def FindNextWordPosition(*args, **kwargs):
"""FindNextWordPosition(self, int direction=1) -> long"""
return _richtext.RichTextCtrl_FindNextWordPosition(*args, **kwargs)
def IsPositionVisible(*args, **kwargs):
"""IsPositionVisible(self, long pos) -> bool"""
return _richtext.RichTextCtrl_IsPositionVisible(*args, **kwargs)
def GetFirstVisiblePosition(*args, **kwargs):
"""GetFirstVisiblePosition(self) -> long"""
return _richtext.RichTextCtrl_GetFirstVisiblePosition(*args, **kwargs)
def GetCaretPositionForDefaultStyle(*args, **kwargs):
"""GetCaretPositionForDefaultStyle(self) -> long"""
return _richtext.RichTextCtrl_GetCaretPositionForDefaultStyle(*args, **kwargs)
def SetCaretPositionForDefaultStyle(*args, **kwargs):
"""SetCaretPositionForDefaultStyle(self, long pos)"""
return _richtext.RichTextCtrl_SetCaretPositionForDefaultStyle(*args, **kwargs)
def IsDefaultStyleShowing(*args, **kwargs):
"""IsDefaultStyleShowing(self) -> bool"""
return _richtext.RichTextCtrl_IsDefaultStyleShowing(*args, **kwargs)
def SetAndShowDefaultStyle(*args, **kwargs):
"""SetAndShowDefaultStyle(self, RichTextAttr attr)"""
return _richtext.RichTextCtrl_SetAndShowDefaultStyle(*args, **kwargs)
def GetFirstVisiblePoint(*args, **kwargs):
"""GetFirstVisiblePoint(self) -> Point"""
return _richtext.RichTextCtrl_GetFirstVisiblePoint(*args, **kwargs)
def GetScrollPageSize(*args, **kwargs):
"""GetScrollPageSize(self, int orient) -> int"""
return _richtext.RichTextCtrl_GetScrollPageSize(*args, **kwargs)
def SetScrollPageSize(*args, **kwargs):
"""SetScrollPageSize(self, int orient, int pageSize)"""
return _richtext.RichTextCtrl_SetScrollPageSize(*args, **kwargs)
def SetScrollRate(*args, **kwargs):
"""SetScrollRate(self, int xstep, int ystep)"""
return _richtext.RichTextCtrl_SetScrollRate(*args, **kwargs)
def GetViewStart(*args, **kwargs):
"""
GetViewStart() -> (x,y)
Get the view start
"""
return _richtext.RichTextCtrl_GetViewStart(*args, **kwargs)
def SetScale(*args, **kwargs):
"""SetScale(self, double xs, double ys)"""
return _richtext.RichTextCtrl_SetScale(*args, **kwargs)
def GetScaleX(*args, **kwargs):
"""GetScaleX(self) -> double"""
return _richtext.RichTextCtrl_GetScaleX(*args, **kwargs)
def GetScaleY(*args, **kwargs):
"""GetScaleY(self) -> double"""
return _richtext.RichTextCtrl_GetScaleY(*args, **kwargs)
def CalcScrolledPosition(*args):
"""
CalcScrolledPosition(self, Point pt) -> Point
CalcScrolledPosition(int x, int y) -> (sx, sy)
Translate between scrolled and unscrolled coordinates.
"""
return _richtext.RichTextCtrl_CalcScrolledPosition(*args)
def CalcUnscrolledPosition(*args):
"""
CalcUnscrolledPosition(self, Point pt) -> Point
CalcUnscrolledPosition(int x, int y) -> (ux, uy)
Translate between scrolled and unscrolled coordinates.
"""
return _richtext.RichTextCtrl_CalcUnscrolledPosition(*args)
def SetTargetRect(*args, **kwargs):
"""SetTargetRect(self, Rect rect)"""
return _richtext.RichTextCtrl_SetTargetRect(*args, **kwargs)
def GetTargetRect(*args, **kwargs):
"""GetTargetRect(self) -> Rect"""
return _richtext.RichTextCtrl_GetTargetRect(*args, **kwargs)
def IsEmpty(*args, **kwargs):
"""
IsEmpty(self) -> bool
Returns True if the value in the text field is empty.
"""
return _richtext.RichTextCtrl_IsEmpty(*args, **kwargs)
def SetModified(*args, **kwargs):
"""SetModified(self, bool modified)"""
return _richtext.RichTextCtrl_SetModified(*args, **kwargs)
_richtext.RichTextCtrl_swigregister(RichTextCtrl)
RichTextCtrlNameStr = cvar.RichTextCtrlNameStr
def PreRichTextCtrl(*args, **kwargs):
"""PreRichTextCtrl() -> RichTextCtrl"""
val = _richtext.new_PreRichTextCtrl(*args, **kwargs)
return val
#---------------------------------------------------------------------------
wxEVT_COMMAND_RICHTEXT_LEFT_CLICK = _richtext.wxEVT_COMMAND_RICHTEXT_LEFT_CLICK
wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK = _richtext.wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK
wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK = _richtext.wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK
wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK = _richtext.wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK
wxEVT_COMMAND_RICHTEXT_RETURN = _richtext.wxEVT_COMMAND_RICHTEXT_RETURN
wxEVT_COMMAND_RICHTEXT_CHARACTER = _richtext.wxEVT_COMMAND_RICHTEXT_CHARACTER
wxEVT_COMMAND_RICHTEXT_DELETE = _richtext.wxEVT_COMMAND_RICHTEXT_DELETE
wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING = _richtext.wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING
wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED = _richtext.wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED
wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING = _richtext.wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING
wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED = _richtext.wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED
wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED = _richtext.wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED
wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED = _richtext.wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED
wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED = _richtext.wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED
wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED = _richtext.wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED
wxEVT_COMMAND_RICHTEXT_BUFFER_RESET = _richtext.wxEVT_COMMAND_RICHTEXT_BUFFER_RESET
EVT_RICHTEXT_LEFT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_RICHTEXT_LEFT_CLICK, 1)
EVT_RICHTEXT_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK, 1)
EVT_RICHTEXT_MIDDLE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK, 1)
EVT_RICHTEXT_LEFT_DCLICK = wx.PyEventBinder(wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK, 1)
EVT_RICHTEXT_RETURN = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_RETURN, 1)
EVT_RICHTEXT_CHARACTER = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_CHARACTER, 1)
EVT_RICHTEXT_DELETE = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_DELETE, 1)
EVT_RICHTEXT_STYLESHEET_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING, 1)
EVT_RICHTEXT_STYLESHEET_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED, 1)
EVT_RICHTEXT_STYLESHEET_REPLACING = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, 1)
EVT_RICHTEXT_STYLESHEET_REPLACED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED, 1)
EVT_RICHTEXT_CONTENT_INSERTED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED, 1)
EVT_RICHTEXT_CONTENT_DELETED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED, 1)
EVT_RICHTEXT_STYLE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED, 1)
EVT_RICHTEXT_SELECTION_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED, 1)
EVT_RICHTEXT_BUFFER_RESET = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_BUFFER_RESET, 1)
class RichTextEvent(_core.NotifyEvent):
"""Proxy of C++ RichTextEvent 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) -> RichTextEvent"""
_richtext.RichTextEvent_swiginit(self,_richtext.new_RichTextEvent(*args, **kwargs))
def GetPosition(*args, **kwargs):
"""GetPosition(self) -> int"""
return _richtext.RichTextEvent_GetPosition(*args, **kwargs)
def SetPosition(*args, **kwargs):
"""SetPosition(self, int n)"""
return _richtext.RichTextEvent_SetPosition(*args, **kwargs)
def GetFlags(*args, **kwargs):
"""GetFlags(self) -> int"""
return _richtext.RichTextEvent_GetFlags(*args, **kwargs)
def SetFlags(*args, **kwargs):
"""SetFlags(self, int flags)"""
return _richtext.RichTextEvent_SetFlags(*args, **kwargs)
def GetOldStyleSheet(*args, **kwargs):
"""GetOldStyleSheet(self) -> wxRichTextStyleSheet"""
return _richtext.RichTextEvent_GetOldStyleSheet(*args, **kwargs)
def SetOldStyleSheet(*args, **kwargs):
"""SetOldStyleSheet(self, wxRichTextStyleSheet sheet)"""
return _richtext.RichTextEvent_SetOldStyleSheet(*args, **kwargs)
def GetNewStyleSheet(*args, **kwargs):
"""GetNewStyleSheet(self) -> wxRichTextStyleSheet"""
return _richtext.RichTextEvent_GetNewStyleSheet(*args, **kwargs)
def SetNewStyleSheet(*args, **kwargs):
"""SetNewStyleSheet(self, wxRichTextStyleSheet sheet)"""
return _richtext.RichTextEvent_SetNewStyleSheet(*args, **kwargs)
def GetRange(*args, **kwargs):
"""GetRange(self) -> RichTextRange"""
return _richtext.RichTextEvent_GetRange(*args, **kwargs)
def SetRange(*args, **kwargs):
"""SetRange(self, RichTextRange range)"""
return _richtext.RichTextEvent_SetRange(*args, **kwargs)
def GetCharacter(*args, **kwargs):
"""GetCharacter(self) -> wxChar"""
return _richtext.RichTextEvent_GetCharacter(*args, **kwargs)
def SetCharacter(*args, **kwargs):
"""SetCharacter(self, wxChar ch)"""
return _richtext.RichTextEvent_SetCharacter(*args, **kwargs)
Flags = property(GetFlags,SetFlags)
Index = property(GetPosition,SetPosition)
OldStyleSheet = property(GetOldStyleSheet,SetOldStyleSheet)
NewStyleSheet = property(GetNewStyleSheet,SetNewStyleSheet)
Range = property(GetRange,SetRange)
Character = property(GetCharacter,SetCharacter)
_richtext.RichTextEvent_swigregister(RichTextEvent)
#---------------------------------------------------------------------------
class RichTextHTMLHandler(RichTextFileHandler):
"""Proxy of C++ RichTextHTMLHandler 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, String name=HtmlName, String ext=HtmlExt, int type=RICHTEXT_TYPE_HTML) -> RichTextHTMLHandler"""
_richtext.RichTextHTMLHandler_swiginit(self,_richtext.new_RichTextHTMLHandler(*args, **kwargs))
def SetTemporaryImageLocations(*args, **kwargs):
"""
SetTemporaryImageLocations(self, wxArrayString locations)
Set the list of image locations generated by the last operation
"""
return _richtext.RichTextHTMLHandler_SetTemporaryImageLocations(*args, **kwargs)
def GetTemporaryImageLocations(*args, **kwargs):
"""
GetTemporaryImageLocations(self) -> wxArrayString
Get the list of image locations generated by the last operation
"""
return _richtext.RichTextHTMLHandler_GetTemporaryImageLocations(*args, **kwargs)
TemporaryImageLocations = property(GetTemporaryImageLocations,SetTemporaryImageLocations)
def ClearTemporaryImageLocations(*args, **kwargs):
"""
ClearTemporaryImageLocations(self)
Clear the image locations generated by the last operation
"""
return _richtext.RichTextHTMLHandler_ClearTemporaryImageLocations(*args, **kwargs)
def DeleteTemporaryImages(*args, **kwargs):
"""
DeleteTemporaryImages(self) -> bool
Delete the in-memory or temporary files generated by the last operation
"""
return _richtext.RichTextHTMLHandler_DeleteTemporaryImages(*args, **kwargs)
def SetFileCounter(*args, **kwargs):
"""
SetFileCounter(int counter)
Reset the file counter, in case, for example, the same names are required each
time
"""
return _richtext.RichTextHTMLHandler_SetFileCounter(*args, **kwargs)
SetFileCounter = staticmethod(SetFileCounter)
def SetTempDir(*args, **kwargs):
"""
SetTempDir(self, String tempDir)
Set the directory for storing temporary files. If empty, the system temporary
directory will be used.
"""
return _richtext.RichTextHTMLHandler_SetTempDir(*args, **kwargs)
def GetTempDir(*args, **kwargs):
"""
GetTempDir(self) -> String
Get the directory for storing temporary files. If empty, the system temporary
directory will be used.
"""
return _richtext.RichTextHTMLHandler_GetTempDir(*args, **kwargs)
TempDir = property(GetTempDir,SetTempDir)
def SetFontSizeMapping(*args, **kwargs):
"""
SetFontSizeMapping(self, wxArrayInt fontSizeMapping)
Set mapping from point size to HTML font size. There should be 7 elements, one
for each HTML font size, each element specifying the maximum point size for
that HTML font size. E.g. 8, 10, 13, 17, 22, 29, 100
"""
return _richtext.RichTextHTMLHandler_SetFontSizeMapping(*args, **kwargs)
def GetFontSizeMapping(*args, **kwargs):
"""
GetFontSizeMapping(self) -> wxArrayInt
Get mapping deom point size to HTML font size.
"""
return _richtext.RichTextHTMLHandler_GetFontSizeMapping(*args, **kwargs)
FontSizeMapping = property(GetFontSizeMapping,SetFontSizeMapping)
_richtext.RichTextHTMLHandler_swigregister(RichTextHTMLHandler)
HtmlName = cvar.HtmlName
HtmlExt = cvar.HtmlExt
def RichTextHTMLHandler_SetFileCounter(*args, **kwargs):
"""
RichTextHTMLHandler_SetFileCounter(int counter)
Reset the file counter, in case, for example, the same names are required each
time
"""
return _richtext.RichTextHTMLHandler_SetFileCounter(*args, **kwargs)
#---------------------------------------------------------------------------
class RichTextXMLHandler(RichTextFileHandler):
"""Proxy of C++ RichTextXMLHandler 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, String name=XmlName, String ext=XmlExt, int type=RICHTEXT_TYPE_XML) -> RichTextXMLHandler"""
_richtext.RichTextXMLHandler_swiginit(self,_richtext.new_RichTextXMLHandler(*args, **kwargs))
_richtext.RichTextXMLHandler_swigregister(RichTextXMLHandler)
XmlName = cvar.XmlName
XmlExt = cvar.XmlExt
#---------------------------------------------------------------------------
RICHTEXT_PRINT_MAX_PAGES = _richtext.RICHTEXT_PRINT_MAX_PAGES
RICHTEXT_PAGE_ODD = _richtext.RICHTEXT_PAGE_ODD
RICHTEXT_PAGE_EVEN = _richtext.RICHTEXT_PAGE_EVEN
RICHTEXT_PAGE_ALL = _richtext.RICHTEXT_PAGE_ALL
RICHTEXT_PAGE_LEFT = _richtext.RICHTEXT_PAGE_LEFT
RICHTEXT_PAGE_CENTRE = _richtext.RICHTEXT_PAGE_CENTRE
RICHTEXT_PAGE_RIGHT = _richtext.RICHTEXT_PAGE_RIGHT
class RichTextPrintout(_windows.Printout):
"""Proxy of C++ RichTextPrintout 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, String title=wxT("Printout")) -> RichTextPrintout"""
_richtext.RichTextPrintout_swiginit(self,_richtext.new_RichTextPrintout(*args, **kwargs))
__swig_destroy__ = _richtext.delete_RichTextPrintout
__del__ = lambda self : None;
def SetRichTextBuffer(*args, **kwargs):
"""SetRichTextBuffer(self, RichTextBuffer buffer)"""
return _richtext.RichTextPrintout_SetRichTextBuffer(*args, **kwargs)
def GetRichTextBuffer(*args, **kwargs):
"""GetRichTextBuffer(self) -> RichTextBuffer"""
return _richtext.RichTextPrintout_GetRichTextBuffer(*args, **kwargs)
def SetHeaderFooterData(*args, **kwargs):
"""SetHeaderFooterData(self, wxRichTextHeaderFooterData data)"""
return _richtext.RichTextPrintout_SetHeaderFooterData(*args, **kwargs)
def GetHeaderFooterData(*args, **kwargs):
"""GetHeaderFooterData(self) -> wxRichTextHeaderFooterData"""
return _richtext.RichTextPrintout_GetHeaderFooterData(*args, **kwargs)
def SetMargins(*args, **kwargs):
"""SetMargins(self, int top=254, int bottom=254, int left=254, int right=254)"""
return _richtext.RichTextPrintout_SetMargins(*args, **kwargs)
def CalculateScaling(*args, **kwargs):
"""CalculateScaling(self, DC dc, Rect textRect, Rect headerRect, Rect footerRect)"""
return _richtext.RichTextPrintout_CalculateScaling(*args, **kwargs)
_richtext.RichTextPrintout_swigregister(RichTextPrintout)
class RichTextPrinting(_core.Object):
"""Proxy of C++ RichTextPrinting 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, String name=wxT("Printing"), Window parentWindow=None) -> RichTextPrinting"""
_richtext.RichTextPrinting_swiginit(self,_richtext.new_RichTextPrinting(*args, **kwargs))
__swig_destroy__ = _richtext.delete_RichTextPrinting
__del__ = lambda self : None;
def PreviewFile(*args, **kwargs):
"""PreviewFile(self, String richTextFile) -> bool"""
return _richtext.RichTextPrinting_PreviewFile(*args, **kwargs)
def PreviewBuffer(*args, **kwargs):
"""PreviewBuffer(self, RichTextBuffer buffer) -> bool"""
return _richtext.RichTextPrinting_PreviewBuffer(*args, **kwargs)
def PrintFile(*args, **kwargs):
"""PrintFile(self, String richTextFile) -> bool"""
return _richtext.RichTextPrinting_PrintFile(*args, **kwargs)
def PrintBuffer(*args, **kwargs):
"""PrintBuffer(self, RichTextBuffer buffer) -> bool"""
return _richtext.RichTextPrinting_PrintBuffer(*args, **kwargs)
def PageSetup(*args, **kwargs):
"""PageSetup(self)"""
return _richtext.RichTextPrinting_PageSetup(*args, **kwargs)
def SetHeaderFooterData(*args, **kwargs):
"""SetHeaderFooterData(self, wxRichTextHeaderFooterData data)"""
return _richtext.RichTextPrinting_SetHeaderFooterData(*args, **kwargs)
def GetHeaderFooterData(*args, **kwargs):
"""GetHeaderFooterData(self) -> wxRichTextHeaderFooterData"""
return _richtext.RichTextPrinting_GetHeaderFooterData(*args, **kwargs)
def SetHeaderText(*args, **kwargs):
"""SetHeaderText(self, String text, int page=RICHTEXT_PAGE_ALL, int location=RICHTEXT_PAGE_CENTRE)"""
return _richtext.RichTextPrinting_SetHeaderText(*args, **kwargs)
def GetHeaderText(*args, **kwargs):
"""GetHeaderText(self, int page=RICHTEXT_PAGE_EVEN, int location=RICHTEXT_PAGE_CENTRE) -> String"""
return _richtext.RichTextPrinting_GetHeaderText(*args, **kwargs)
def SetFooterText(*args, **kwargs):
"""SetFooterText(self, String text, int page=RICHTEXT_PAGE_ALL, int location=RICHTEXT_PAGE_CENTRE)"""
return _richtext.RichTextPrinting_SetFooterText(*args, **kwargs)
def GetFooterText(*args, **kwargs):
"""GetFooterText(self, int page=RICHTEXT_PAGE_EVEN, int location=RICHTEXT_PAGE_CENTRE) -> String"""
return _richtext.RichTextPrinting_GetFooterText(*args, **kwargs)
def SetShowOnFirstPage(*args, **kwargs):
"""SetShowOnFirstPage(self, bool show)"""
return _richtext.RichTextPrinting_SetShowOnFirstPage(*args, **kwargs)
def SetHeaderFooterFont(*args, **kwargs):
"""SetHeaderFooterFont(self, Font font)"""
return _richtext.RichTextPrinting_SetHeaderFooterFont(*args, **kwargs)
def SetHeaderFooterTextColour(*args, **kwargs):
"""SetHeaderFooterTextColour(self, Colour font)"""
return _richtext.RichTextPrinting_SetHeaderFooterTextColour(*args, **kwargs)
def GetPrintData(*args, **kwargs):
"""GetPrintData(self) -> PrintData"""
return _richtext.RichTextPrinting_GetPrintData(*args, **kwargs)
def GetPageSetupData(*args, **kwargs):
"""GetPageSetupData(self) -> PageSetupDialogData"""
return _richtext.RichTextPrinting_GetPageSetupData(*args, **kwargs)
def SetPrintData(*args, **kwargs):
"""SetPrintData(self, PrintData printData)"""
return _richtext.RichTextPrinting_SetPrintData(*args, **kwargs)
def SetPageSetupData(*args, **kwargs):
"""SetPageSetupData(self, wxPageSetupData pageSetupData)"""
return _richtext.RichTextPrinting_SetPageSetupData(*args, **kwargs)
def SetRichTextBufferPreview(*args, **kwargs):
"""SetRichTextBufferPreview(self, RichTextBuffer buf)"""
return _richtext.RichTextPrinting_SetRichTextBufferPreview(*args, **kwargs)
def GetRichTextBufferPreview(*args, **kwargs):
"""GetRichTextBufferPreview(self) -> RichTextBuffer"""
return _richtext.RichTextPrinting_GetRichTextBufferPreview(*args, **kwargs)
def SetRichTextBufferPrinting(*args, **kwargs):
"""SetRichTextBufferPrinting(self, RichTextBuffer buf)"""
return _richtext.RichTextPrinting_SetRichTextBufferPrinting(*args, **kwargs)
def GetRichTextBufferPrinting(*args, **kwargs):
"""GetRichTextBufferPrinting(self) -> RichTextBuffer"""
return _richtext.RichTextPrinting_GetRichTextBufferPrinting(*args, **kwargs)
def SetParentWindow(*args, **kwargs):
"""SetParentWindow(self, Window parent)"""
return _richtext.RichTextPrinting_SetParentWindow(*args, **kwargs)
def GetParentWindow(*args, **kwargs):
"""GetParentWindow(self) -> Window"""
return _richtext.RichTextPrinting_GetParentWindow(*args, **kwargs)
def SetTitle(*args, **kwargs):
"""SetTitle(self, String title)"""
return _richtext.RichTextPrinting_SetTitle(*args, **kwargs)
def GetTitle(*args, **kwargs):
"""GetTitle(self) -> String"""
return _richtext.RichTextPrinting_GetTitle(*args, **kwargs)
def SetPreviewRect(*args, **kwargs):
"""SetPreviewRect(self, Rect rect)"""
return _richtext.RichTextPrinting_SetPreviewRect(*args, **kwargs)
def GetPreviewRect(*args, **kwargs):
"""GetPreviewRect(self) -> Rect"""
return _richtext.RichTextPrinting_GetPreviewRect(*args, **kwargs)
_richtext.RichTextPrinting_swigregister(RichTextPrinting)
|
pongem/python-bot-project
|
refs/heads/master
|
appengine/standard/botapp/lib/django/utils/autoreload.py
|
295
|
# Autoreloading launcher.
# Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org).
# Some taken from Ian Bicking's Paste (http://pythonpaste.org/).
#
# Portions copyright (c) 2004, CherryPy Team (team@cherrypy.org)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the CherryPy Team 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 os
import signal
import sys
import time
import traceback
from django.apps import apps
from django.conf import settings
from django.core.signals import request_finished
from django.utils import six
from django.utils._os import npath
from django.utils.six.moves import _thread as thread
# This import does nothing, but it's necessary to avoid some race conditions
# in the threading module. See http://code.djangoproject.com/ticket/2330 .
try:
import threading # NOQA
except ImportError:
pass
try:
import termios
except ImportError:
termios = None
USE_INOTIFY = False
try:
# Test whether inotify is enabled and likely to work
import pyinotify
fd = pyinotify.INotifyWrapper.create().inotify_init()
if fd >= 0:
USE_INOTIFY = True
os.close(fd)
except ImportError:
pass
RUN_RELOADER = True
FILE_MODIFIED = 1
I18N_MODIFIED = 2
_mtimes = {}
_win = (sys.platform == "win32")
_exception = None
_error_files = []
_cached_modules = set()
_cached_filenames = []
def gen_filenames(only_new=False):
"""
Returns a list of filenames referenced in sys.modules and translation
files.
"""
# N.B. ``list(...)`` is needed, because this runs in parallel with
# application code which might be mutating ``sys.modules``, and this will
# fail with RuntimeError: cannot mutate dictionary while iterating
global _cached_modules, _cached_filenames
module_values = set(sys.modules.values())
_cached_filenames = clean_files(_cached_filenames)
if _cached_modules == module_values:
# No changes in module list, short-circuit the function
if only_new:
return []
else:
return _cached_filenames + clean_files(_error_files)
new_modules = module_values - _cached_modules
new_filenames = clean_files(
[filename.__file__ for filename in new_modules
if hasattr(filename, '__file__')])
if not _cached_filenames and settings.USE_I18N:
# Add the names of the .mo files that can be generated
# by compilemessages management command to the list of files watched.
basedirs = [os.path.join(os.path.dirname(os.path.dirname(__file__)),
'conf', 'locale'),
'locale']
for app_config in reversed(list(apps.get_app_configs())):
basedirs.append(os.path.join(npath(app_config.path), 'locale'))
basedirs.extend(settings.LOCALE_PATHS)
basedirs = [os.path.abspath(basedir) for basedir in basedirs
if os.path.isdir(basedir)]
for basedir in basedirs:
for dirpath, dirnames, locale_filenames in os.walk(basedir):
for filename in locale_filenames:
if filename.endswith('.mo'):
new_filenames.append(os.path.join(dirpath, filename))
_cached_modules = _cached_modules.union(new_modules)
_cached_filenames += new_filenames
if only_new:
return new_filenames + clean_files(_error_files)
else:
return _cached_filenames + clean_files(_error_files)
def clean_files(filelist):
filenames = []
for filename in filelist:
if not filename:
continue
if filename.endswith(".pyc") or filename.endswith(".pyo"):
filename = filename[:-1]
if filename.endswith("$py.class"):
filename = filename[:-9] + ".py"
if os.path.exists(filename):
filenames.append(filename)
return filenames
def reset_translations():
import gettext
from django.utils.translation import trans_real
gettext._translations = {}
trans_real._translations = {}
trans_real._default = None
trans_real._active = threading.local()
def inotify_code_changed():
"""
Checks for changed code using inotify. After being called
it blocks until a change event has been fired.
"""
class EventHandler(pyinotify.ProcessEvent):
modified_code = None
def process_default(self, event):
if event.path.endswith('.mo'):
EventHandler.modified_code = I18N_MODIFIED
else:
EventHandler.modified_code = FILE_MODIFIED
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm, EventHandler())
def update_watch(sender=None, **kwargs):
if sender and getattr(sender, 'handles_files', False):
# No need to update watches when request serves files.
# (sender is supposed to be a django.core.handlers.BaseHandler subclass)
return
mask = (
pyinotify.IN_MODIFY |
pyinotify.IN_DELETE |
pyinotify.IN_ATTRIB |
pyinotify.IN_MOVED_FROM |
pyinotify.IN_MOVED_TO |
pyinotify.IN_CREATE |
pyinotify.IN_DELETE_SELF |
pyinotify.IN_MOVE_SELF
)
for path in gen_filenames(only_new=True):
wm.add_watch(path, mask)
# New modules may get imported when a request is processed.
request_finished.connect(update_watch)
# Block until an event happens.
update_watch()
notifier.check_events(timeout=None)
notifier.read_events()
notifier.process_events()
notifier.stop()
# If we are here the code must have changed.
return EventHandler.modified_code
def code_changed():
global _mtimes, _win
for filename in gen_filenames():
stat = os.stat(filename)
mtime = stat.st_mtime
if _win:
mtime -= stat.st_ctime
if filename not in _mtimes:
_mtimes[filename] = mtime
continue
if mtime != _mtimes[filename]:
_mtimes = {}
try:
del _error_files[_error_files.index(filename)]
except ValueError:
pass
return I18N_MODIFIED if filename.endswith('.mo') else FILE_MODIFIED
return False
def check_errors(fn):
def wrapper(*args, **kwargs):
global _exception
try:
fn(*args, **kwargs)
except Exception:
_exception = sys.exc_info()
et, ev, tb = _exception
if getattr(ev, 'filename', None) is None:
# get the filename from the last item in the stack
filename = traceback.extract_tb(tb)[-1][0]
else:
filename = ev.filename
if filename not in _error_files:
_error_files.append(filename)
raise
return wrapper
def raise_last_exception():
global _exception
if _exception is not None:
six.reraise(*_exception)
def ensure_echo_on():
if termios:
fd = sys.stdin
if fd.isatty():
attr_list = termios.tcgetattr(fd)
if not attr_list[3] & termios.ECHO:
attr_list[3] |= termios.ECHO
if hasattr(signal, 'SIGTTOU'):
old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
else:
old_handler = None
termios.tcsetattr(fd, termios.TCSANOW, attr_list)
if old_handler is not None:
signal.signal(signal.SIGTTOU, old_handler)
def reloader_thread():
ensure_echo_on()
if USE_INOTIFY:
fn = inotify_code_changed
else:
fn = code_changed
while RUN_RELOADER:
change = fn()
if change == FILE_MODIFIED:
sys.exit(3) # force reload
elif change == I18N_MODIFIED:
reset_translations()
time.sleep(1)
def restart_with_reloader():
while True:
args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv
if sys.platform == "win32":
args = ['"%s"' % arg for arg in args]
new_environ = os.environ.copy()
new_environ["RUN_MAIN"] = 'true'
exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ)
if exit_code != 3:
return exit_code
def python_reloader(main_func, args, kwargs):
if os.environ.get("RUN_MAIN") == "true":
thread.start_new_thread(main_func, args, kwargs)
try:
reloader_thread()
except KeyboardInterrupt:
pass
else:
try:
exit_code = restart_with_reloader()
if exit_code < 0:
os.kill(os.getpid(), -exit_code)
else:
sys.exit(exit_code)
except KeyboardInterrupt:
pass
def jython_reloader(main_func, args, kwargs):
from _systemrestart import SystemRestart
thread.start_new_thread(main_func, args)
while True:
if code_changed():
raise SystemRestart
time.sleep(1)
def main(main_func, args=None, kwargs=None):
if args is None:
args = ()
if kwargs is None:
kwargs = {}
if sys.platform.startswith('java'):
reloader = jython_reloader
else:
reloader = python_reloader
wrapped_main_func = check_errors(main_func)
reloader(wrapped_main_func, args, kwargs)
|
peak3d/kodi-agile
|
refs/heads/master
|
tools/EventClients/lib/python/xbmcclient.py
|
26
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2013 Team XBMC
#
# 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.
"""
Implementation of XBMC's UDP based input system.
A set of classes that abstract the various packets that the event server
currently supports. In addition, there's also a class, XBMCClient, that
provides functions that sends the various packets. Use XBMCClient if you
don't need complete control over packet structure.
The basic workflow involves:
1. Send a HELO packet
2. Send x number of valid packets
3. Send a BYE packet
IMPORTANT NOTE ABOUT TIMEOUTS:
A client is considered to be timed out if XBMC doesn't received a packet
at least once every 60 seconds. To "ping" XBMC with an empty packet use
PacketPING or XBMCClient.ping(). See the documentation for details.
"""
__author__ = "d4rk@xbmc.org"
__version__ = "0.0.3"
from struct import pack
from socket import *
import time
MAX_PACKET_SIZE = 1024
HEADER_SIZE = 32
MAX_PAYLOAD_SIZE = MAX_PACKET_SIZE - HEADER_SIZE
UNIQUE_IDENTIFICATION = (int)(time.time())
PT_HELO = 0x01
PT_BYE = 0x02
PT_BUTTON = 0x03
PT_MOUSE = 0x04
PT_PING = 0x05
PT_BROADCAST = 0x06
PT_NOTIFICATION = 0x07
PT_BLOB = 0x08
PT_LOG = 0x09
PT_ACTION = 0x0A
PT_DEBUG = 0xFF
ICON_NONE = 0x00
ICON_JPEG = 0x01
ICON_PNG = 0x02
ICON_GIF = 0x03
BT_USE_NAME = 0x01
BT_DOWN = 0x02
BT_UP = 0x04
BT_USE_AMOUNT = 0x08
BT_QUEUE = 0x10
BT_NO_REPEAT = 0x20
BT_VKEY = 0x40
BT_AXIS = 0x80
BT_AXISSINGLE = 0x100
MS_ABSOLUTE = 0x01
LOGDEBUG = 0x00
LOGINFO = 0x01
LOGNOTICE = 0x02
LOGWARNING = 0x03
LOGERROR = 0x04
LOGSEVERE = 0x05
LOGFATAL = 0x06
LOGNONE = 0x07
ACTION_EXECBUILTIN = 0x01
ACTION_BUTTON = 0x02
######################################################################
# Helper Functions
######################################################################
def format_string(msg):
""" """
return msg + "\0"
def format_uint32(num):
""" """
return pack ("!I", num)
def format_uint16(num):
""" """
if num<0:
num = 0
elif num>65535:
num = 65535
return pack ("!H", num)
######################################################################
# Packet Classes
######################################################################
class Packet:
"""Base class that implements a single event packet.
- Generic packet structure (maximum 1024 bytes per packet)
- Header is 32 bytes long, so 992 bytes available for payload
- large payloads can be split into multiple packets using H4 and H5
H5 should contain total no. of packets in such a case
- H6 contains length of P1, which is limited to 992 bytes
- if H5 is 0 or 1, then H4 will be ignored (single packet msg)
- H7 must be set to zeros for now
-----------------------------
| -H1 Signature ("XBMC") | - 4 x CHAR 4B
| -H2 Version (eg. 2.0) | - 2 x UNSIGNED CHAR 2B
| -H3 PacketType | - 1 x UNSIGNED SHORT 2B
| -H4 Sequence number | - 1 x UNSIGNED LONG 4B
| -H5 No. of packets in msg | - 1 x UNSIGNED LONG 4B
| -H7 Client's unique token | - 1 x UNSIGNED LONG 4B
| -H8 Reserved | - 10 x UNSIGNED CHAR 10B
|---------------------------|
| -P1 payload | -
-----------------------------
"""
def __init__(self):
self.sig = "XBMC"
self.minver = 0
self.majver = 2
self.seq = 1
self.maxseq = 1
self.payloadsize = 0
self.uid = UNIQUE_IDENTIFICATION
self.reserved = "\0" * 10
self.payload = ""
return
def append_payload(self, blob):
"""Append to existing payload
Arguments:
blob -- binary data to append to the current payload
"""
self.set_payload(self.payload + blob)
def set_payload(self, payload):
"""Set the payload for this packet
Arguments:
payload -- binary data that contains the payload
"""
self.payload = payload
self.payloadsize = len(self.payload)
self.maxseq = int((self.payloadsize + (MAX_PAYLOAD_SIZE - 1)) / MAX_PAYLOAD_SIZE)
def num_packets(self):
""" Return the number of packets required for payload """
return self.maxseq
def get_header(self, packettype=-1, seq=1, maxseq=1, payload_size=0):
"""Construct a header and return as string
Keyword arguments:
packettype -- valid packet types are PT_HELO, PT_BYE, PT_BUTTON,
PT_MOUSE, PT_PING, PT_BORADCAST, PT_NOTIFICATION,
PT_BLOB, PT_DEBUG
seq -- the sequence of this packet for a multi packet message
(default 1)
maxseq -- the total number of packets for a multi packet message
(default 1)
payload_size -- the size of the payload of this packet (default 0)
"""
if packettype < 0:
packettype = self.packettype
header = self.sig
header += chr(self.majver)
header += chr(self.minver)
header += format_uint16(packettype)
header += format_uint32(seq)
header += format_uint32(maxseq)
header += format_uint16(payload_size)
header += format_uint32(self.uid)
header += self.reserved
return header
def get_payload_size(self, seq):
"""Returns the calculated payload size for the particular packet
Arguments:
seq -- the sequence number
"""
if self.maxseq == 1:
return self.payloadsize
if seq < self.maxseq:
return MAX_PAYLOAD_SIZE
return self.payloadsize % MAX_PAYLOAD_SIZE
def get_udp_message(self, packetnum=1):
"""Construct the UDP message for the specified packetnum and return
as string
Keyword arguments:
packetnum -- the packet no. for which to construct the message
(default 1)
"""
if packetnum > self.num_packets() or packetnum < 1:
return ""
header = ""
if packetnum==1:
header = self.get_header(self.packettype, packetnum, self.maxseq,
self.get_payload_size(packetnum))
else:
header = self.get_header(PT_BLOB, packetnum, self.maxseq,
self.get_payload_size(packetnum))
payload = self.payload[ (packetnum-1) * MAX_PAYLOAD_SIZE :
(packetnum-1) * MAX_PAYLOAD_SIZE+
self.get_payload_size(packetnum) ]
return header + payload
def send(self, sock, addr, uid=UNIQUE_IDENTIFICATION):
"""Send the entire message to the specified socket and address.
Arguments:
sock -- datagram socket object (socket.socket)
addr -- address, port pair (eg: ("127.0.0.1", 9777) )
uid -- unique identification
"""
self.uid = uid
for a in range ( 0, self.num_packets() ):
try:
sock.sendto(self.get_udp_message(a+1), addr)
except:
return False
return True
class PacketHELO (Packet):
"""A HELO packet
A HELO packet establishes a valid connection to XBMC. It is the
first packet that should be sent.
"""
def __init__(self, devicename=None, icon_type=ICON_NONE, icon_file=None):
"""
Keyword arguments:
devicename -- the string that identifies the client
icon_type -- one of ICON_NONE, ICON_JPEG, ICON_PNG, ICON_GIF
icon_file -- location of icon file with respect to current working
directory if icon_type is not ICON_NONE
"""
Packet.__init__(self)
self.packettype = PT_HELO
self.icontype = icon_type
self.set_payload ( format_string(devicename)[0:128] )
self.append_payload( chr (icon_type) )
self.append_payload( format_uint16 (0) ) # port no
self.append_payload( format_uint32 (0) ) # reserved1
self.append_payload( format_uint32 (0) ) # reserved2
if icon_type != ICON_NONE and icon_file:
self.append_payload( file(icon_file).read() )
class PacketNOTIFICATION (Packet):
"""A NOTIFICATION packet
This packet displays a notification window in XBMC. It can contain
a caption, a message and an icon.
"""
def __init__(self, title, message, icon_type=ICON_NONE, icon_file=None):
"""
Keyword arguments:
title -- the notification caption / title
message -- the main text of the notification
icon_type -- one of ICON_NONE, ICON_JPEG, ICON_PNG, ICON_GIF
icon_file -- location of icon file with respect to current working
directory if icon_type is not ICON_NONE
"""
Packet.__init__(self)
self.packettype = PT_NOTIFICATION
self.title = title
self.message = message
self.set_payload ( format_string(title) )
self.append_payload( format_string(message) )
self.append_payload( chr (icon_type) )
self.append_payload( format_uint32 (0) ) # reserved
if icon_type != ICON_NONE and icon_file:
self.append_payload( file(icon_file).read() )
class PacketBUTTON (Packet):
"""A BUTTON packet
A button packet send a key press or release event to XBMC
"""
def __init__(self, code=0, repeat=1, down=1, queue=0,
map_name="", button_name="", amount=0, axis=0):
"""
Keyword arguments:
code -- raw button code (default: 0)
repeat -- this key press should repeat until released (default: 1)
Note that queued pressed cannot repeat.
down -- if this is 1, it implies a press event, 0 implies a release
event. (default: 1)
queue -- a queued key press means that the button event is
executed just once after which the next key press is
processed. It can be used for macros. Currently there
is no support for time delays between queued presses.
(default: 0)
map_name -- a combination of map_name and button_name refers to a
mapping in the user's Keymap.xml or Lircmap.xml.
map_name can be one of the following:
"KB" => standard keyboard map ( <keyboard> section )
"XG" => xbox gamepad map ( <gamepad> section )
"R1" => xbox remote map ( <remote> section )
"R2" => xbox universal remote map ( <universalremote>
section )
"LI:devicename" => LIRC remote map where 'devicename' is the
actual device's name
button_name -- a button name defined in the map specified in map_name.
For example, if map_name is "KB" referring to the
<keyboard> section in Keymap.xml then, valid
button_names include "printscreen", "minus", "x", etc.
amount -- unimplemented for now; in the future it will be used for
specifying magnitude of analog key press events
"""
Packet.__init__(self)
self.flags = 0
self.packettype = PT_BUTTON
if type (code ) == str:
code = ord(code)
# assign code only if we don't have a map and button name
if not (map_name and button_name):
self.code = code
else:
self.flags |= BT_USE_NAME
self.code = 0
if (amount != None):
self.flags |= BT_USE_AMOUNT
self.amount = int(amount)
else:
self.amount = 0
if down:
self.flags |= BT_DOWN
else:
self.flags |= BT_UP
if not repeat:
self.flags |= BT_NO_REPEAT
if queue:
self.flags |= BT_QUEUE
if axis == 1:
self.flags |= BT_AXISSINGLE
elif axis == 2:
self.flags |= BT_AXIS
self.set_payload ( format_uint16(self.code) )
self.append_payload( format_uint16(self.flags) )
self.append_payload( format_uint16(self.amount) )
self.append_payload( format_string (map_name) )
self.append_payload( format_string (button_name) )
class PacketMOUSE (Packet):
"""A MOUSE packet
A MOUSE packets sets the mouse position in XBMC
"""
def __init__(self, x, y):
"""
Arguments:
x -- horizontal position ranging from 0 to 65535
y -- vertical position ranging from 0 to 65535
The range will be mapped to the screen width and height in XBMC
"""
Packet.__init__(self)
self.packettype = PT_MOUSE
self.flags = MS_ABSOLUTE
self.append_payload( chr (self.flags) )
self.append_payload( format_uint16(x) )
self.append_payload( format_uint16(y) )
class PacketBYE (Packet):
"""A BYE packet
A BYE packet terminates the connection to XBMC.
"""
def __init__(self):
Packet.__init__(self)
self.packettype = PT_BYE
class PacketPING (Packet):
"""A PING packet
A PING packet tells XBMC that the client is still alive. All valid
packets act as ping (not just this one). A client needs to ping
XBMC at least once in 60 seconds or it will time out.
"""
def __init__(self):
Packet.__init__(self)
self.packettype = PT_PING
class PacketLOG (Packet):
"""A LOG packet
A LOG packet tells XBMC to log the message to xbmc.log with the loglevel as specified.
"""
def __init__(self, loglevel=0, logmessage="", autoprint=True):
"""
Keyword arguments:
loglevel -- the loglevel, follows XBMC standard.
logmessage -- the message to log
autoprint -- if the logmessage should automatically be printed to stdout
"""
Packet.__init__(self)
self.packettype = PT_LOG
self.append_payload( chr (loglevel) )
self.append_payload( format_string(logmessage) )
if (autoprint):
print logmessage
class PacketACTION (Packet):
"""An ACTION packet
An ACTION packet tells XBMC to do the action specified, based on the type it knows were it needs to be sent.
The idea is that this will be as in scripting/skining and keymapping, just triggered from afar.
"""
def __init__(self, actionmessage="", actiontype=ACTION_EXECBUILTIN):
"""
Keyword arguments:
loglevel -- the loglevel, follows XBMC standard.
logmessage -- the message to log
autoprint -- if the logmessage should automatically be printed to stdout
"""
Packet.__init__(self)
self.packettype = PT_ACTION
self.append_payload( chr (actiontype) )
self.append_payload( format_string(actionmessage) )
######################################################################
# XBMC Client Class
######################################################################
class XBMCClient:
"""An XBMC event client"""
def __init__(self, name ="", icon_file=None, broadcast=False, uid=UNIQUE_IDENTIFICATION,
ip="127.0.0.1"):
"""
Keyword arguments:
name -- Name of the client
icon_file -- location of an icon file, if any (png, jpg or gif)
uid -- unique identification
"""
self.name = str(name)
self.icon_file = icon_file
self.icon_type = self._get_icon_type(icon_file)
self.ip = ip
self.port = 9777
self.sock = socket(AF_INET,SOCK_DGRAM)
if broadcast:
self.sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
self.uid = uid
def connect(self, ip=None, port=None):
"""Initialize connection to XBMC
ip -- IP Address of XBMC
port -- port that the event server on XBMC is listening on
"""
if ip:
self.ip = ip
if port:
self.port = int(port)
self.addr = (self.ip, self.port)
packet = PacketHELO(self.name, self.icon_type, self.icon_file)
return packet.send(self.sock, self.addr, self.uid)
def close(self):
"""Close the current connection"""
packet = PacketBYE()
return packet.send(self.sock, self.addr, self.uid)
def ping(self):
"""Send a PING packet"""
packet = PacketPING()
return packet.send(self.sock, self.addr, self.uid)
def send_notification(self, title="", message="", icon_file=None):
"""Send a notification to the connected XBMC
Keyword Arguments:
title -- The title/heading for the notification
message -- The message to be displayed
icon_file -- location of an icon file, if any (png, jpg, gif)
"""
self.connect()
packet = PacketNOTIFICATION(title, message,
self._get_icon_type(icon_file),
icon_file)
return packet.send(self.sock, self.addr, self.uid)
def send_keyboard_button(self, button=None):
"""Send a keyboard event to XBMC
Keyword Arguments:
button -- name of the keyboard button to send (same as in Keymap.xml)
"""
if not button:
return
return self.send_button(map="KB", button=button)
def send_remote_button(self, button=None):
"""Send a remote control event to XBMC
Keyword Arguments:
button -- name of the remote control button to send (same as in Keymap.xml)
"""
if not button:
return
return self.send_button(map="R1", button=button)
def release_button(self):
"""Release all buttons"""
packet = PacketBUTTON(code=0x01, down=0)
return packet.send(self.sock, self.addr, self.uid)
def send_button(self, map="", button="", amount=0):
"""Send a button event to XBMC
Keyword arguments:
map -- a combination of map_name and button_name refers to a
mapping in the user's Keymap.xml or Lircmap.xml.
map_name can be one of the following:
"KB" => standard keyboard map ( <keyboard> section )
"XG" => xbox gamepad map ( <gamepad> section )
"R1" => xbox remote map ( <remote> section )
"R2" => xbox universal remote map ( <universalremote>
section )
"LI:devicename" => LIRC remote map where 'devicename' is the
actual device's name
button -- a button name defined in the map specified in map, above.
For example, if map is "KB" referring to the <keyboard>
section in Keymap.xml then, valid buttons include
"printscreen", "minus", "x", etc.
"""
packet = PacketBUTTON(map_name=str(map), button_name=str(button), amount=amount)
return packet.send(self.sock, self.addr, self.uid)
def send_button_state(self, map="", button="", amount=0, down=0, axis=0):
"""Send a button event to XBMC
Keyword arguments:
map -- a combination of map_name and button_name refers to a
mapping in the user's Keymap.xml or Lircmap.xml.
map_name can be one of the following:
"KB" => standard keyboard map ( <keyboard> section )
"XG" => xbox gamepad map ( <gamepad> section )
"R1" => xbox remote map ( <remote> section )
"R2" => xbox universal remote map ( <universalremote>
section )
"LI:devicename" => LIRC remote map where 'devicename' is the
actual device's name
button -- a button name defined in the map specified in map, above.
For example, if map is "KB" referring to the <keyboard>
section in Keymap.xml then, valid buttons include
"printscreen", "minus", "x", etc.
"""
if axis:
if amount == 0:
down = 0
else:
down = 1
packet = PacketBUTTON(map_name=str(map), button_name=str(button), amount=amount, down=down, queue=1, axis=axis)
return packet.send(self.sock, self.addr, self.uid)
def send_mouse_position(self, x=0, y=0):
"""Send a mouse event to XBMC
Keywords Arguments:
x -- absolute x position of mouse ranging from 0 to 65535
which maps to the entire screen width
y -- same a 'x' but relates to the screen height
"""
packet = PacketMOUSE(int(x), int(y))
return packet.send(self.sock, self.addr, self.uid)
def send_log(self, loglevel=0, logmessage="", autoprint=True):
"""
Keyword arguments:
loglevel -- the loglevel, follows XBMC standard.
logmessage -- the message to log
autoprint -- if the logmessage should automatically be printed to stdout
"""
packet = PacketLOG(loglevel, logmessage)
return packet.send(self.sock, self.addr, self.uid)
def send_action(self, actionmessage="", actiontype=ACTION_EXECBUILTIN):
"""
Keyword arguments:
actionmessage -- the ActionString
actiontype -- The ActionType the ActionString should be sent to.
"""
packet = PacketACTION(actionmessage, actiontype)
return packet.send(self.sock, self.addr, self.uid)
def _get_icon_type(self, icon_file):
if icon_file:
if icon_file.lower()[-3:] == "png":
return ICON_PNG
elif icon_file.lower()[-3:] == "gif":
return ICON_GIF
elif icon_file.lower()[-3:] == "jpg":
return ICON_JPEG
return ICON_NONE
|
parkr/Python-CGI
|
refs/heads/master
|
protein.py
|
1
|
#! /usr/bin/python
import cgi
def main():
print "Content-type: text/plain\n"
form = cgi.FieldStorage()
weight = int(form.getvalue("weight"))
print "A person of a normal activity level requires ",
print weight*.4,
print "g of protein per day."
print "If you are more active, try to eat ",
print weight*.6,
print "g of protein per day."
main()
|
klonage/nlt-gcs
|
refs/heads/master
|
Lib/site-packages/numpy/distutils/command/egg_info.py
|
100
|
from setuptools.command.egg_info import egg_info as _egg_info
class egg_info(_egg_info):
def run(self):
# We need to ensure that build_src has been executed in order to give
# setuptools' egg_info command real filenames instead of functions which
# generate files.
self.run_command("build_src")
_egg_info.run(self)
|
kwikteam/global_superclustering
|
refs/heads/master
|
global_code/global_script.py
|
1
|
from phy.io import KwikModel
from phy.cluster.session import Session
import phy
phy.__version__
from klustakwik2 import *
#import hashutils
import numpy as np
import pickle
import sys
import os
import copy
import time
from IPython.parallel import Client
from IPython import embed
def write_mask(mask, filename, fmt="%f"):
fd = open(filename, 'w')
fd.write(str(mask.shape[1])+'\n') # number of features
fd.close()
fd = open(filename, 'ab')
np.savetxt(fd, mask, fmt=fmt)
fd.close()
def write_fet(feats, filepath, fmt = "%f"):
feat_file = open(filepath, 'w')
#feats = np.array(feats, dtype=np.int32)
#header line: number of features
feat_file.write('%i\n' % feats.shape[1])
feat_file.close()
feat_file = open(filepath, 'ab')
#next lines: one feature vector per line
#np.savetxt(feat_file, feats, fmt="%i")
np.savetxt(feat_file, feats, fmt=fmt)
feat_file.close()
def make_KK2script(KKparams, filebase, shanknum, scriptname):
#keylist = KKparams['keylist']
#keylist = ['MaskStarts','MaxPossibleClusters','FullStepEvery','MaxIter','RandomSeed',
# 'Debug','SplitFirst','SplitEvery','PenaltyK','PenaltyKLogN','Subset',
# 'PriorPoint','SaveSorted','SaveCovarianceMeans','UseMaskedInitialConditions',
# 'AssignToFirstClosestMask','UseDistributional']
#KKlocation = '/martinottihome/skadir/GIT_masters/klustakwik/MaskedKlustaKwik'
#KKlocation = KKparams['KKlocation']
#scriptstring = KKlocation + ' '+ filebase + ' %g '%(str(shanknum))
KKlocation = 'kk2_legacy'
scriptstring = KKlocation + ' '+ filebase + ' %g '%(shanknum)
for KKey in KKparams.keys():
#print '-'+KKey +' '+ str(KKparams[KKey])
scriptstring = scriptstring + ' '+ KKey +'='+ str(KKparams[KKey])
print(scriptstring)
scriptfile = open('%s.sh' %(scriptname),'w')
scriptfile.write(scriptstring)
scriptfile.close()
changeperms='chmod 777 %s.sh' %(scriptname)
os.system(changeperms)
return scriptstring
def pca_licate_indices(channel_list, num_pcs):
ordered_chanlist = np.sort(channel_list)
modlist = [(num_pcs*ordered_chanlist + i) for i in np.arange(num_pcs)]
pc_chans = np.sort(np.concatenate(modlist))
#print(pc_chans)
#np.sort(np.concatenate([3*np.sort(list(model.probe.adjacency[6]))+0,
#3*np.sort(list(model.probe.adjacency[6]))+1,
#3*np.sort(list(model.probe.adjacency[6]))+2]))
#nut = pca_licate_indices(list(model.probe.adjacency[6]),3)
#print(nut)
return pc_chans
def make_full_adjacency(adj):
'''Make a full adjacency graph by adding
reference channel to its neighbours
adj = model.probe.adjacency
return full_adjacency'''
full_adjacency = copy.deepcopy(adj)
for channel in full_adjacency.keys():
full_adjacency[channel].add(channel)
return full_adjacency
def make_channel_order_dict(chorder):
'''
chorder is model.channel_order
In [13]: model.channel_order
Out[13]:
array([ 7, 39, 8, 41, 6, 38, 9, 42, 5, 37, 10, 43, 4,
36, 11, 44, 35, 12, 45, 2, 34, 13, 46, 1, 33, 14,
47, 0, 32, 15, 31, 63, 16, 49, 30, 62, 17, 50, 29,
61, 18, 51, 28, 60, 19, 52, 59, 27, 53, 21, 58, 26,
54, 22, 57, 25, 55, 23, 56, 24, 71, 103, 72, 105, 70,
102, 73, 106, 74, 101, 69, 107, 75, 100, 68, 108, 99, 67,
109, 77, 98, 66, 110, 78, 97, 65, 111, 79, 96, 64, 80,
127, 95, 113, 81, 126, 94, 114, 82, 125, 93, 115, 83, 124,
92, 116, 123, 91, 117, 85, 122, 90, 118, 86, 121, 89, 119,
87, 120, 88], dtype=int32)
In [14]: channel_order_dict[38]
Out[14]: 5
'''
channel_order_dict = {}
for j in np.arange(len(chorder)):
#channel_order_dict[j] = chorder[j]
channel_order_dict[chorder[j]] = j
return channel_order_dict
def find_unmasked_points_for_channel(masks,channel_order_dict,fulladj,globalcl_dict):
'''For each channel find the indices of the points
which are unmasked on this channel
fulladj = full_adjacency
masks - array of masks'''
globalcl_dict.update({'unmasked_indices':{}})
for channel in fulladj.keys():
unmasked = np.where(masks[:,channel_order_dict[channel]]!= 0)
globalcl_dict['unmasked_indices'].update({channel:unmasked})
return globalcl_dict
#print(model.probe.adjacency[channel])
def find_unmasked_spikegroup(fulladj,globalcl_dict):
'''compute indices of spike groups by taking the union of the unmasked indices
for each channel belonging to the spike group '''
globalcl_dict.update({'unmasked_spikegroup':{}})
for channel in fulladj.keys():
unmaskedunion = []
for chan in list(fulladj[channel]): # e.g. model.probe.adjacency[5] = {1,2,4,5}
unmaskedunion = np.union1d(unmaskedunion,globalcl_dict['unmasked_indices'][chan][0])
unmaskedunion = np.array(unmaskedunion, dtype = np.int32)
globalcl_dict['unmasked_spikegroup'].update({channel:unmaskedunion})
return globalcl_dict
def make_subset_fetmask(fetmask_dict, fetty, triplemasky, channel_order_dict,fulladj, globalcl_dict, writefetmask = False):
'''No longer necessary with the new subset feature in KK2,
but kept here in case. Make .fet and .fmask files for the
subsets'''
#fetmask_dict = {}
fetmask_dict.update({'group_fet':{}, 'group_fmask':{}, 'pcs_inds':{}})
for channel in fulladj.keys():
ordchans = [channel_order_dict[x] for x in list(full_adjacency[channel])]
pcs_inds = pca_licate_indices(ordchans,3)
#pcs_inds = pca_licate_indices(list(fulladj[channel]),3)
fetmask_dict['pcs_inds'].update({channel:pcs_inds})
fetty_group = fetty[:,pcs_inds]
fetty_little = fetty_group[globalcl_dict['unmasked_spikegroup'][channel],:]
fetmask_dict['group_fet'].update({channel:fetty_little})
masky_group = triplemasky[:,pcs_inds]
masky_little = masky_group[globalcl_dict['unmasked_spikegroup'][channel],:]
fetmask_dict['group_fmask'].update({channel:masky_little})
if writefetmask == True:
fetty_little_name = basename + '.fet.'+ str(channel)
masky_little_name = basename + '.fmask.'+ str(channel)
print('writing file ',fetty_little_name)
write_fet(fetty_little, fetty_little_name)
print('writing file ',masky_little_name)
write_mask(masky_little,masky_little_name)
return fetmask_dict
if __name__ == "__main__":
scriptname = os.path.basename(__file__)
print('Running script: ', os.path.basename(__file__))
#sys.exit()
basefolder = '/mnt/zserver/Data/multichanspikes/M140528_NS1/20141202/'
littlename = '20141202_all'
basename = basefolder + littlename
kwik_path = basename + '.kwik'
model = KwikModel(kwik_path)
#session = Session(kwik_path)
#Make an old-fashioned .fet and .fmask file
numb_spikes_to_use = 40000
if numb_spikes_to_use ==None:
masky = model.masks[:]
fetty = model.features[:]
else:
masky = model.masks[:numb_spikes_to_use+1]
fetty = model.features[:numb_spikes_to_use+1]
triplemasky = np.repeat(masky,3, axis = 1)
print(masky.shape)
print(fetty.shape)
numspikes = masky.shape[0]
#derived_basename = basename
outputpath = '/home/skadir/globalphy/nicktest/'
derived_basename = outputpath + 'nick_global_%g'%(numspikes)
fmaskbase = derived_basename + '.fmask.1'
fetbase = derived_basename + '.fet.1'
write_fet(fetty, fetbase)
write_mask(triplemasky,fmaskbase)
#sys.exit()
#Make a full adjacency graph
print('Making full adjacency graph')
full_adjacency = make_full_adjacency(model.probe.adjacency)
print(full_adjacency)
#active_channels = model.channels
#Channel order dictionary
channel_order_dict = make_channel_order_dict(model.channel_order)
embed()
#For each channel find the indices of the points which are unmasked on this channel
print('Making globalcl_dict')
globalcl_dict = {}
globalcl_dict = find_unmasked_points_for_channel(masky,channel_order_dict,full_adjacency,globalcl_dict)
#compute indices of spike groups by taking the union of the unmasked indices
#for each channel belonging to the spike group
globalcl_dict = find_unmasked_spikegroup(full_adjacency,globalcl_dict)
#Make dictionary of subset features and masks
fetmask_dict = {}
make_subset_fetmask(fetmask_dict, fetty, triplemasky, channel_order_dict, full_adjacency, globalcl_dict)
#Run MKK on each subset with the default value of the parameters
script_params = default_parameters.copy()
script_params.update(
drop_last_n_features=0,
save_clu_every=None,
run_monitoring_server=False,
save_all_clu=False,
debug=True,
start_from_clu=None,
use_noise_cluster=True,
use_mua_cluster=True,
subset_schedule=None,
)
print('Running KK on subsets')
print(script_params)
print(script_params.keys())
# Start timing
start_time = time.time()
shank = 1
drop_last_n_features = script_params.pop('drop_last_n_features')
save_clu_every = script_params.pop('save_clu_every')
run_monitoring_server = script_params.pop('run_monitoring_server')
save_all_clu = script_params.pop('save_all_clu')
debug = script_params.pop('debug')
num_starting_clusters = script_params.pop('num_starting_clusters')
start_from_clu = script_params.pop('start_from_clu')
use_noise_cluster = script_params.pop('use_noise_cluster')
use_mua_cluster = script_params.pop('use_mua_cluster')
subset_schedule = script_params.pop('subset_schedule')
raw_data = load_fet_fmask_to_raw(derived_basename, shank, drop_last_n_features=drop_last_n_features)
log_message('debug', 'Loading data from .fet and .fmask file took %.2f s' % (time.time()-start_time))
data = raw_data.to_sparse_data()
log_message('info', 'Number of spikes in data set: '+str(data.num_spikes))
log_message('info', 'Number of unique masks in data set: '+str(data.num_masks))
kk = KK(data, use_noise_cluster=use_noise_cluster, use_mua_cluster=use_mua_cluster, **script_params)
supercluster_info = {}
supercluster_info.update({'kk_sub':{}, 'sub_spikes':{}})
for channel in full_adjacency.keys():
kk_sub, spikes = kk.subset_features(list(fetmask_dict['pcs_inds'][channel]))
supercluster_info['kk_sub'].update({channel:kk_sub})
supercluster_info['sub_spikes'].update({channel:spikes})
with open('%s_supercluster_info.p'%(derived_basename),'wb') as gg:
pickle.dump(supercluster_info,gg)
#Run KK2 on all the subsets
numKK = len(full_adjacency.keys()) #equal to the number of channels
superclusters = np.zeros((fetty.shape[0],numKK))
start_time2 = time.time()
for channel in full_adjacency.keys():
# supercluster_info['kk_sub'][channel].cluster_mask_starts()
supercluster_info['kk_sub'][channel].cluster_mask_starts()
superclusters[supercluster_info['sub_spikes'][channel],channel] = supercluster_info['kk_sub'][channel].clusters
print('Time taken for parallel clustering %.2f s' %(time.time()-start_time2))
# for channel in full_adjacency.keys():
# scriptname = basename+'%g'%(channel)
# scriptstring = '''import klustakwik2 as *
# '''
# scriptfile = open('%s.sh' %(scriptname),'w')
# scriptfile.write(scriptstring)
# scriptfile.close()
# changeperms='chmod 777 %s.sh' %(scriptname)
# os.system(changeperms)
superinfo = [full_adjacency,globalcl_dict,supercluster_info,superclusters]
with open('%s_supercluster.p'%(derived_basename), 'wb') as g:
pickle.dump(superinfo, g)
|
albertomurillo/ansible
|
refs/heads/devel
|
test/units/modules/storage/netapp/test_na_ontap_broadcast_domain.py
|
38
|
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
''' unit test template for ONTAP Ansible module '''
from __future__ import print_function
import json
import pytest
from units.compat import unittest
from units.compat.mock import patch, Mock
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
import ansible.module_utils.netapp as netapp_utils
from ansible.modules.storage.netapp.na_ontap_broadcast_domain \
import NetAppOntapBroadcastDomain as broadcast_domain_module # module under test
if not netapp_utils.has_netapp_lib():
pytestmark = pytest.mark.skip('skipping as missing required netapp_lib')
def set_module_args(args):
"""prepare arguments so that they will be picked up during module creation"""
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
basic._ANSIBLE_ARGS = to_bytes(args) # pylint: disable=protected-access
class AnsibleExitJson(Exception):
"""Exception class to be raised by module.exit_json and caught by the test case"""
pass
class AnsibleFailJson(Exception):
"""Exception class to be raised by module.fail_json and caught by the test case"""
pass
def exit_json(*args, **kwargs): # pylint: disable=unused-argument
"""function to patch over exit_json; package return data into an exception"""
if 'changed' not in kwargs:
kwargs['changed'] = False
raise AnsibleExitJson(kwargs)
def fail_json(*args, **kwargs): # pylint: disable=unused-argument
"""function to patch over fail_json; package return data into an exception"""
kwargs['failed'] = True
raise AnsibleFailJson(kwargs)
class MockONTAPConnection(object):
''' mock server connection to ONTAP host '''
def __init__(self, kind=None, data=None):
''' save arguments '''
self.type = kind
self.params = data
self.xml_in = None
self.xml_out = None
def invoke_successfully(self, xml, enable_tunneling): # pylint: disable=unused-argument
''' mock invoke_successfully returning xml data '''
self.xml_in = xml
if self.type == 'broadcast_domain':
xml = self.build_broadcast_domain_info(self.params)
self.xml_out = xml
return xml
@staticmethod
def build_broadcast_domain_info(broadcast_domain_details):
''' build xml data for broadcast_domain info '''
xml = netapp_utils.zapi.NaElement('xml')
attributes = {
'num-records': 1,
'attributes-list': {
'net-port-broadcast-domain-info': {
'broadcast-domain': broadcast_domain_details['name'],
'ipspace': broadcast_domain_details['ipspace'],
'mtu': broadcast_domain_details['mtu'],
'ports': {
'port-info': {
'port': 'test_port_1'
}
}
}
}
}
xml.translate_struct(attributes)
return xml
class TestMyModule(unittest.TestCase):
''' a group of related Unit Tests '''
def setUp(self):
self.mock_module_helper = patch.multiple(basic.AnsibleModule,
exit_json=exit_json,
fail_json=fail_json)
self.mock_module_helper.start()
self.addCleanup(self.mock_module_helper.stop)
self.server = MockONTAPConnection()
self.mock_broadcast_domain = {
'name': 'test_broadcast_domain',
'mtu': '1000',
'ipspace': 'Default',
'ports': 'test_port_1'
}
def mock_args(self):
return {
'name': self.mock_broadcast_domain['name'],
'ipspace': self.mock_broadcast_domain['ipspace'],
'mtu': self.mock_broadcast_domain['mtu'],
'ports': self.mock_broadcast_domain['ports'],
'hostname': 'test',
'username': 'test_user',
'password': 'test_pass!'
}
def get_broadcast_domain_mock_object(self, kind=None, data=None):
"""
Helper method to return an na_ontap_volume object
:param kind: passes this param to MockONTAPConnection()
:param data: passes this param to MockONTAPConnection()
:return: na_ontap_volume object
"""
broadcast_domain_obj = broadcast_domain_module()
broadcast_domain_obj.asup_log_for_cserver = Mock(return_value=None)
broadcast_domain_obj.cluster = Mock()
broadcast_domain_obj.cluster.invoke_successfully = Mock()
if kind is None:
broadcast_domain_obj.server = MockONTAPConnection()
else:
if data is None:
broadcast_domain_obj.server = MockONTAPConnection(kind='broadcast_domain', data=self.mock_broadcast_domain)
else:
broadcast_domain_obj.server = MockONTAPConnection(kind='broadcast_domain', data=data)
return broadcast_domain_obj
def test_module_fail_when_required_args_missing(self):
''' required arguments are reported as errors '''
with pytest.raises(AnsibleFailJson) as exc:
set_module_args({})
broadcast_domain_module()
print('Info: %s' % exc.value.args[0]['msg'])
def test_get_nonexistent_net_route(self):
''' Test if get_broadcast_domain returns None for non-existent broadcast_domain '''
set_module_args(self.mock_args())
result = self.get_broadcast_domain_mock_object().get_broadcast_domain()
assert result is None
def test_create_error_missing_broadcast_domain(self):
''' Test if create throws an error if broadcast_domain is not specified'''
data = self.mock_args()
del data['name']
set_module_args(data)
with pytest.raises(AnsibleFailJson) as exc:
self.get_broadcast_domain_mock_object('broadcast_domain').create_broadcast_domain()
msg = 'missing required arguments: name'
assert exc.value.args[0]['msg'] == msg
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.create_broadcast_domain')
def test_successful_create(self, create_broadcast_domain):
''' Test successful create '''
data = self.mock_args()
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_broadcast_domain_mock_object().apply()
assert exc.value.args[0]['changed']
create_broadcast_domain.assert_called_with()
def test_create_idempotency(self):
''' Test create idempotency '''
set_module_args(self.mock_args())
obj = self.get_broadcast_domain_mock_object('broadcast_domain')
with pytest.raises(AnsibleExitJson) as exc:
obj.apply()
assert not exc.value.args[0]['changed']
def test_modify_mtu(self):
''' Test successful modify mtu '''
data = self.mock_args()
data['mtu'] = '1200'
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
assert exc.value.args[0]['changed']
def test_modify_ipspace_idempotency(self):
''' Test modify ipsapce idempotency'''
data = self.mock_args()
data['ipspace'] = 'Cluster'
set_module_args(data)
with pytest.raises(AnsibleFailJson) as exc:
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
msg = 'A domain ipspace can not be modified after the domain has been created.'
assert exc.value.args[0]['msg'] == msg
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.add_broadcast_domain_ports')
def test_add_ports(self, add_broadcast_domain_ports):
''' Test successful modify ports '''
data = self.mock_args()
data['ports'] = 'test_port_1,test_port_2'
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
assert exc.value.args[0]['changed']
add_broadcast_domain_ports.assert_called_with(['test_port_2'])
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.delete_broadcast_domain_ports')
def test_delete_ports(self, delete_broadcast_domain_ports):
''' Test successful modify ports '''
data = self.mock_args()
data['ports'] = ''
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
assert exc.value.args[0]['changed']
delete_broadcast_domain_ports.assert_called_with(['test_port_1'])
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.modify_broadcast_domain')
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.split_broadcast_domain')
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.get_broadcast_domain')
def test_split_broadcast_domain(self, get_broadcast_domain, split_broadcast_domain, modify_broadcast_domain):
''' Test successful split broadcast domain '''
data = self.mock_args()
data['from_name'] = 'test_broadcast_domain'
data['name'] = 'test_broadcast_domain_2'
data['ports'] = 'test_port_2'
set_module_args(data)
current = {
'name': 'test_broadcast_domain',
'mtu': '1000',
'ipspace': 'Default',
'ports': ['test_port_1,test_port2']
}
get_broadcast_domain.side_effect = [
None,
current,
current
]
with pytest.raises(AnsibleExitJson) as exc:
self.get_broadcast_domain_mock_object().apply()
assert exc.value.args[0]['changed']
modify_broadcast_domain.assert_not_called()
split_broadcast_domain.assert_called_with()
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.delete_broadcast_domain')
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.modify_broadcast_domain')
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.get_broadcast_domain')
def test_split_broadcast_domain_modify_delete(self, get_broadcast_domain, modify_broadcast_domain, delete_broadcast_domain):
''' Test successful split broadcast domain '''
data = self.mock_args()
data['from_name'] = 'test_broadcast_domain'
data['name'] = 'test_broadcast_domain_2'
data['ports'] = 'test_port_1,test_port_2'
data['mtu'] = '1200'
set_module_args(data)
current = {
'name': 'test_broadcast_domain',
'mtu': '1000',
'ipspace': 'Default',
'ports': ['test_port_1,test_port2']
}
get_broadcast_domain.side_effect = [
None,
current,
current
]
with pytest.raises(AnsibleExitJson) as exc:
self.get_broadcast_domain_mock_object().apply()
assert exc.value.args[0]['changed']
delete_broadcast_domain.assert_called_with('test_broadcast_domain')
modify_broadcast_domain.assert_called_with()
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.get_broadcast_domain')
def test_split_broadcast_domain_not_exist(self, get_broadcast_domain):
''' Test successful split broadcast domain '''
data = self.mock_args()
data['from_name'] = 'test_broadcast_domain'
data['name'] = 'test_broadcast_domain_2'
data['ports'] = 'test_port_2'
set_module_args(data)
get_broadcast_domain.side_effect = [
None,
None,
]
with pytest.raises(AnsibleFailJson) as exc:
self.get_broadcast_domain_mock_object().apply()
msg = 'A domain can not be split if it does not exist.'
assert exc.value.args[0]['msg'], msg
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.split_broadcast_domain')
def test_split_broadcast_domain_idempotency(self, split_broadcast_domain):
''' Test successful split broadcast domain '''
data = self.mock_args()
data['from_name'] = 'test_broadcast_domain'
data['ports'] = 'test_port_1'
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
assert exc.value.args[0]['changed'] is False
split_broadcast_domain.assert_not_called()
|
noogel/xyzStudyPython
|
refs/heads/master
|
downloadPythontutorial-2.7.11/download.py
|
1
|
# -*- coding:utf-8 -*-
import os
import codecs
import requests
import chardet
root_url = "http://www.pythondoc.com/pythontutorial27/_sources/"
path_list = """index.html
appetite.html
interpreter.html
introduction.html
controlflow.html
datastructures.html
modules.html
inputoutput.html
errors.html
classes.html
stdlib.html
stdlib2.html
whatnow.html
interactive.html
floatingpoint.html
appendix.html"""
path_list = path_list.split("\n")
save_dir = "/data/www/downloadPythontutorial-2.7.11/"
for path in path_list:
url = "{0}{1}.txt".format(root_url, path[:-5])
print url
resp = requests.get(url).content
f = codecs.open("{0}{1}.rst".format(save_dir, path[:-5]), 'w')
f.write(resp)
f.close()
print "--------end---------"
|
bop/hybrid
|
refs/heads/master
|
lib/python2.6/site-packages/django/core/management/commands/sqlsequencereset.py
|
242
|
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import AppCommand
from django.db import connections, models, DEFAULT_DB_ALIAS
class Command(AppCommand):
help = 'Prints the SQL statements for resetting sequences for the given app name(s).'
option_list = AppCommand.option_list + (
make_option('--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS, help='Nominates a database to print the '
'SQL for. Defaults to the "default" database.'),
)
output_transaction = True
def handle_app(self, app, **options):
connection = connections[options.get('database')]
return '\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True)))
|
ringo-framework/ringo
|
refs/heads/master
|
ringo/resources.py
|
3
|
import logging
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import DataError
from pyramid.httpexceptions import HTTPNotFound
from ringo.lib.helpers import get_item_modul
log = logging.getLogger(__name__)
def get_resource_factory(clazz, modul=None):
"""Dynamically create a Resource factory. The modul can be provided
optionally to optimize loading additional data from the database. It
prevents extra loading of the modul later."""
name = clazz.__name__
factory = type(name,
(RessourceFactory, ),
{'__model__': clazz, '__modul__': modul})
return factory
class RessourceFactory(object):
def __init__(self, request, item=None):
# Reset ACL
self.__acl__ = []
self.item = item
item_id = request.matchdict.get('id')
if item_id and not self.item:
self.item = self._load_item(item_id, request)
if not self.__modul__:
self.__modul__ = get_item_modul(request, self.__model__)
self.__acl__ = self._get_item_permissions(request)
def _load_item(self, id, request):
"""Will load an item from the given clazz. The id of the item to
load is taken from the request matchdict. If no item can be found an
Exception is raised.
:id: id of the item to be loaded.
:returns: Loaded item
"""
# TODO: Make loading items more robust in RessourceFactory. This
# is needed in case that a Ressource is build for a clazz which
# is not related to the the current request which has an id. In
# this case loading the item might fail if there is no item with
# the id in the request.
#
# If think this code might cause problems as trying to build a
# build a Ressource with an independet request smells a
# littlebit. Better add a flag to to ignore the id in the
# request in such cases.
try:
factory = self.__model__.get_item_factory()
return factory.load(id, request.db)
except DataError:
raise HTTPNotFound()
except NoResultFound:
raise HTTPNotFound()
def _get_item_permissions(self, request):
return self.__model__._get_permissions(self.__modul__,
self.item, request)
|
jonycgn/scipy
|
refs/heads/master
|
scipy/signal/wavelets.py
|
23
|
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.dual import eig
from scipy.special import comb
from scipy import linspace, pi, exp
from scipy.signal import convolve
__all__ = ['daub', 'qmf', 'cascade', 'morlet', 'ricker', 'cwt']
def daub(p):
"""
The coefficients for the FIR low-pass filter producing Daubechies wavelets.
p>=1 gives the order of the zero at f=1/2.
There are 2p filter coefficients.
Parameters
----------
p : int
Order of the zero at f=1/2, can have values from 1 to 34.
Returns
-------
daub : ndarray
Return
"""
sqrt = np.sqrt
if p < 1:
raise ValueError("p must be at least 1.")
if p == 1:
c = 1 / sqrt(2)
return np.array([c, c])
elif p == 2:
f = sqrt(2) / 8
c = sqrt(3)
return f * np.array([1 + c, 3 + c, 3 - c, 1 - c])
elif p == 3:
tmp = 12 * sqrt(10)
z1 = 1.5 + sqrt(15 + tmp) / 6 - 1j * (sqrt(15) + sqrt(tmp - 15)) / 6
z1c = np.conj(z1)
f = sqrt(2) / 8
d0 = np.real((1 - z1) * (1 - z1c))
a0 = np.real(z1 * z1c)
a1 = 2 * np.real(z1)
return f / d0 * np.array([a0, 3 * a0 - a1, 3 * a0 - 3 * a1 + 1,
a0 - 3 * a1 + 3, 3 - a1, 1])
elif p < 35:
# construct polynomial and factor it
if p < 35:
P = [comb(p - 1 + k, k, exact=1) for k in range(p)][::-1]
yj = np.roots(P)
else: # try different polynomial --- needs work
P = [comb(p - 1 + k, k, exact=1) / 4.0**k
for k in range(p)][::-1]
yj = np.roots(P) / 4
# for each root, compute two z roots, select the one with |z|>1
# Build up final polynomial
c = np.poly1d([1, 1])**p
q = np.poly1d([1])
for k in range(p - 1):
yval = yj[k]
part = 2 * sqrt(yval * (yval - 1))
const = 1 - 2 * yval
z1 = const + part
if (abs(z1)) < 1:
z1 = const - part
q = q * [1, -z1]
q = c * np.real(q)
# Normalize result
q = q / np.sum(q) * sqrt(2)
return q.c[::-1]
else:
raise ValueError("Polynomial factorization does not work "
"well for p too large.")
def qmf(hk):
"""
Return high-pass qmf filter from low-pass
Parameters
----------
hk : array_like
Coefficients of high-pass filter.
"""
N = len(hk) - 1
asgn = [{0: 1, 1: -1}[k % 2] for k in range(N + 1)]
return hk[::-1] * np.array(asgn)
def cascade(hk, J=7):
"""
Return (x, phi, psi) at dyadic points ``K/2**J`` from filter coefficients.
Parameters
----------
hk : array_like
Coefficients of low-pass filter.
J : int, optional
Values will be computed at grid points ``K/2**J``. Default is 7.
Returns
-------
x : ndarray
The dyadic points ``K/2**J`` for ``K=0...N * (2**J)-1`` where
``len(hk) = len(gk) = N+1``.
phi : ndarray
The scaling function ``phi(x)`` at `x`:
``phi(x) = sum(hk * phi(2x-k))``, where k is from 0 to N.
psi : ndarray, optional
The wavelet function ``psi(x)`` at `x`:
``phi(x) = sum(gk * phi(2x-k))``, where k is from 0 to N.
`psi` is only returned if `gk` is not None.
Notes
-----
The algorithm uses the vector cascade algorithm described by Strang and
Nguyen in "Wavelets and Filter Banks". It builds a dictionary of values
and slices for quick reuse. Then inserts vectors into final vector at the
end.
"""
N = len(hk) - 1
if (J > 30 - np.log2(N + 1)):
raise ValueError("Too many levels.")
if (J < 1):
raise ValueError("Too few levels.")
# construct matrices needed
nn, kk = np.ogrid[:N, :N]
s2 = np.sqrt(2)
# append a zero so that take works
thk = np.r_[hk, 0]
gk = qmf(hk)
tgk = np.r_[gk, 0]
indx1 = np.clip(2 * nn - kk, -1, N + 1)
indx2 = np.clip(2 * nn - kk + 1, -1, N + 1)
m = np.zeros((2, 2, N, N), 'd')
m[0, 0] = np.take(thk, indx1, 0)
m[0, 1] = np.take(thk, indx2, 0)
m[1, 0] = np.take(tgk, indx1, 0)
m[1, 1] = np.take(tgk, indx2, 0)
m *= s2
# construct the grid of points
x = np.arange(0, N * (1 << J), dtype=np.float) / (1 << J)
phi = 0 * x
psi = 0 * x
# find phi0, and phi1
lam, v = eig(m[0, 0])
ind = np.argmin(np.absolute(lam - 1))
# a dictionary with a binary representation of the
# evaluation points x < 1 -- i.e. position is 0.xxxx
v = np.real(v[:, ind])
# need scaling function to integrate to 1 so find
# eigenvector normalized to sum(v,axis=0)=1
sm = np.sum(v)
if sm < 0: # need scaling function to integrate to 1
v = -v
sm = -sm
bitdic = {}
bitdic['0'] = v / sm
bitdic['1'] = np.dot(m[0, 1], bitdic['0'])
step = 1 << J
phi[::step] = bitdic['0']
phi[(1 << (J - 1))::step] = bitdic['1']
psi[::step] = np.dot(m[1, 0], bitdic['0'])
psi[(1 << (J - 1))::step] = np.dot(m[1, 1], bitdic['0'])
# descend down the levels inserting more and more values
# into bitdic -- store the values in the correct location once we
# have computed them -- stored in the dictionary
# for quicker use later.
prevkeys = ['1']
for level in range(2, J + 1):
newkeys = ['%d%s' % (xx, yy) for xx in [0, 1] for yy in prevkeys]
fac = 1 << (J - level)
for key in newkeys:
# convert key to number
num = 0
for pos in range(level):
if key[pos] == '1':
num += (1 << (level - 1 - pos))
pastphi = bitdic[key[1:]]
ii = int(key[0])
temp = np.dot(m[0, ii], pastphi)
bitdic[key] = temp
phi[num * fac::step] = temp
psi[num * fac::step] = np.dot(m[1, ii], pastphi)
prevkeys = newkeys
return x, phi, psi
def morlet(M, w=5.0, s=1.0, complete=True):
"""
Complex Morlet wavelet.
Parameters
----------
M : int
Length of the wavelet.
w : float, optional
Omega0. Default is 5
s : float, optional
Scaling factor, windowed from ``-s*2*pi`` to ``+s*2*pi``. Default is 1.
complete : bool, optional
Whether to use the complete or the standard version.
Returns
-------
morlet : (M,) ndarray
See Also
--------
scipy.signal.gausspulse
Notes
-----
The standard version::
pi**-0.25 * exp(1j*w*x) * exp(-0.5*(x**2))
This commonly used wavelet is often referred to simply as the
Morlet wavelet. Note that this simplified version can cause
admissibility problems at low values of w.
The complete version::
pi**-0.25 * (exp(1j*w*x) - exp(-0.5*(w**2))) * exp(-0.5*(x**2))
The complete version of the Morlet wavelet, with a correction
term to improve admissibility. For w greater than 5, the
correction term is negligible.
Note that the energy of the return wavelet is not normalised
according to s.
The fundamental frequency of this wavelet in Hz is given
by ``f = 2*s*w*r / M`` where r is the sampling rate.
"""
x = linspace(-s * 2 * pi, s * 2 * pi, M)
output = exp(1j * w * x)
if complete:
output -= exp(-0.5 * (w**2))
output *= exp(-0.5 * (x**2)) * pi**(-0.25)
return output
def ricker(points, a):
"""
Return a Ricker wavelet, also known as the "Mexican hat wavelet".
It models the function:
``A (1 - x^2/a^2) exp(-x^2/2 a^2)``,
where ``A = 2/sqrt(3a)pi^1/4``.
Parameters
----------
points : int
Number of points in `vector`.
Will be centered around 0.
a : scalar
Width parameter of the wavelet.
Returns
-------
vector : (N,) ndarray
Array of length `points` in shape of ricker curve.
Examples
--------
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> points = 100
>>> a = 4.0
>>> vec2 = signal.ricker(points, a)
>>> print(len(vec2))
100
>>> plt.plot(vec2)
>>> plt.show()
"""
A = 2 / (np.sqrt(3 * a) * (np.pi**0.25))
wsq = a**2
vec = np.arange(0, points) - (points - 1.0) / 2
xsq = vec**2
mod = (1 - xsq / wsq)
gauss = np.exp(-xsq / (2 * wsq))
total = A * mod * gauss
return total
def cwt(data, wavelet, widths):
"""
Continuous wavelet transform.
Performs a continuous wavelet transform on `data`,
using the `wavelet` function. A CWT performs a convolution
with `data` using the `wavelet` function, which is characterized
by a width parameter and length parameter.
Parameters
----------
data : (N,) ndarray
data on which to perform the transform.
wavelet : function
Wavelet function, which should take 2 arguments.
The first argument is the number of points that the returned vector
will have (len(wavelet(width,length)) == length).
The second is a width parameter, defining the size of the wavelet
(e.g. standard deviation of a gaussian). See `ricker`, which
satisfies these requirements.
widths : (M,) sequence
Widths to use for transform.
Returns
-------
cwt: (M, N) ndarray
Will have shape of (len(widths), len(data)).
Notes
-----
>>> length = min(10 * width[ii], len(data))
>>> cwt[ii,:] = scipy.signal.convolve(data, wavelet(length,
... width[ii]), mode='same')
Examples
--------
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(-1, 1, 200, endpoint=False)
>>> sig = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2)
>>> widths = np.arange(1, 31)
>>> cwtmatr = signal.cwt(sig, signal.ricker, widths)
>>> plt.imshow(cwtmatr, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto',
... vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max())
>>> plt.show()
"""
output = np.zeros([len(widths), len(data)])
for ind, width in enumerate(widths):
wavelet_data = wavelet(min(10 * width, len(data)), width)
output[ind, :] = convolve(data, wavelet_data,
mode='same')
return output
|
austinhyde/ansible-modules-core
|
refs/heads/devel
|
cloud/amazon/_ec2_ami_search.py
|
75
|
#!/usr/bin/python
#
# (c) 2013, Nimbis Services
#
# 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/>.
DOCUMENTATION = '''
---
module: ec2_ami_search
short_description: Retrieve AWS AMI information for a given operating system.
deprecated: "in favor of the ec2_ami_find module"
version_added: "1.6"
description:
- Look up the most recent AMI on AWS for a given operating system.
- Returns C(ami), C(aki), C(ari), C(serial), C(tag)
- If there is no AKI or ARI associated with an image, these will be C(null).
- Only supports images from cloud-images.ubuntu.com
- 'Example output: C({"ami": "ami-69f5a900", "changed": false, "aki": "aki-88aa75e1", "tag": "release", "ari": null, "serial": "20131024"})'
version_added: "1.6"
options:
distro:
description: Linux distribution (e.g., C(ubuntu))
required: true
choices: ["ubuntu"]
release:
description: short name of the release (e.g., C(precise))
required: true
stream:
description: Type of release.
required: false
default: "server"
choices: ["server", "desktop"]
store:
description: Back-end store for instance
required: false
default: "ebs"
choices: ["ebs", "ebs-io1", "ebs-ssd", "instance-store"]
arch:
description: CPU architecture
required: false
default: "amd64"
choices: ["i386", "amd64"]
region:
description: EC2 region
required: false
default: us-east-1
choices: ["ap-northeast-1", "ap-southeast-1", "ap-southeast-2",
"eu-central-1", "eu-west-1", "sa-east-1", "us-east-1",
"us-west-1", "us-west-2", "us-gov-west-1"]
virt:
description: virutalization type
required: false
default: paravirtual
choices: ["paravirtual", "hvm"]
author: Lorin Hochstein
'''
EXAMPLES = '''
- name: Launch an Ubuntu 12.04 (Precise Pangolin) EC2 instance
hosts: 127.0.0.1
connection: local
tasks:
- name: Get the Ubuntu precise AMI
ec2_ami_search: distro=ubuntu release=precise region=us-west-1 store=instance-store
register: ubuntu_image
- name: Start the EC2 instance
ec2: image={{ ubuntu_image.ami }} instance_type=m1.small key_name=mykey
'''
import csv
import json
import urlparse
SUPPORTED_DISTROS = ['ubuntu']
AWS_REGIONS = ['ap-northeast-1',
'ap-southeast-1',
'ap-southeast-2',
'eu-central-1',
'eu-west-1',
'sa-east-1',
'us-east-1',
'us-west-1',
'us-west-2',
"us-gov-west-1"]
def get_url(module, url):
""" Get url and return response """
r, info = fetch_url(module, url)
if info['status'] != 200:
# Backwards compat
info['status_code'] = info['status']
module.fail_json(**info)
return r
def ubuntu(module):
""" Get the ami for ubuntu """
release = module.params['release']
stream = module.params['stream']
store = module.params['store']
arch = module.params['arch']
region = module.params['region']
virt = module.params['virt']
url = get_ubuntu_url(release, stream)
req = get_url(module, url)
reader = csv.reader(req, delimiter='\t')
try:
ami, aki, ari, tag, serial = lookup_ubuntu_ami(reader, release, stream,
store, arch, region, virt)
module.exit_json(changed=False, ami=ami, aki=aki, ari=ari, tag=tag,
serial=serial)
except KeyError:
module.fail_json(msg="No matching AMI found")
def lookup_ubuntu_ami(table, release, stream, store, arch, region, virt):
""" Look up the Ubuntu AMI that matches query given a table of AMIs
table: an iterable that returns a row of
(release, stream, tag, serial, region, ami, aki, ari, virt)
release: ubuntu release name
stream: 'server' or 'desktop'
store: 'ebs', 'ebs-io1', 'ebs-ssd' or 'instance-store'
arch: 'i386' or 'amd64'
region: EC2 region
virt: 'paravirtual' or 'hvm'
Returns (ami, aki, ari, tag, serial)"""
expected = (release, stream, store, arch, region, virt)
for row in table:
(actual_release, actual_stream, tag, serial,
actual_store, actual_arch, actual_region, ami, aki, ari,
actual_virt) = row
actual = (actual_release, actual_stream, actual_store, actual_arch,
actual_region, actual_virt)
if actual == expected:
# aki and ari are sometimes blank
if aki == '':
aki = None
if ari == '':
ari = None
return (ami, aki, ari, tag, serial)
raise KeyError()
def get_ubuntu_url(release, stream):
url = "https://cloud-images.ubuntu.com/query/%s/%s/released.current.txt"
return url % (release, stream)
def main():
arg_spec = dict(
distro=dict(required=True, choices=SUPPORTED_DISTROS),
release=dict(required=True),
stream=dict(required=False, default='server',
choices=['desktop', 'server']),
store=dict(required=False, default='ebs',
choices=['ebs', 'ebs-io1', 'ebs-ssd', 'instance-store']),
arch=dict(required=False, default='amd64',
choices=['i386', 'amd64']),
region=dict(required=False, default='us-east-1', choices=AWS_REGIONS),
virt=dict(required=False, default='paravirtual',
choices=['paravirtual', 'hvm']),
)
module = AnsibleModule(argument_spec=arg_spec)
distro = module.params['distro']
if distro == 'ubuntu':
ubuntu(module)
else:
module.fail_json(msg="Unsupported distro: %s" % distro)
# this is magic, see lib/ansible/module_common.py
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.