repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
bensonhsu2013/old_samsung-lt02wifi-kernel
tools/perf/python/twatch.py
7370
1334
#! /usr/bin/python # -*- python -*- # -*- coding: utf-8 -*- # twatch - Experimental use of the perf python interface # Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com> # # This application is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; version 2. # # This application 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. import perf def main(): cpus = perf.cpu_map() threads = perf.thread_map() evsel = perf.evsel(task = 1, comm = 1, mmap = 0, wakeup_events = 1, watermark = 1, sample_id_all = 1, sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU | perf.SAMPLE_TID) evsel.open(cpus = cpus, threads = threads); evlist = perf.evlist(cpus, threads) evlist.add(evsel) evlist.mmap() while True: evlist.poll(timeout = -1) for cpu in cpus: event = evlist.read_on_cpu(cpu) if not event: continue print "cpu: %2d, pid: %4d, tid: %4d" % (event.sample_cpu, event.sample_pid, event.sample_tid), print event if __name__ == '__main__': main()
gpl-2.0
rhinstaller/pykickstart
tests/commands/selinux.py
2
1293
import unittest from tests.baseclass import CommandTest from pykickstart.constants import SELINUX_DISABLED, SELINUX_ENFORCING, SELINUX_PERMISSIVE class FC3_TestCase(CommandTest): command = "selinux" def runTest(self): # pass self.assert_parse("selinux") self.assert_parse("selinux --permissive", "selinux --permissive\n") self.assert_parse("selinux --enforcing", "selinux --enforcing\n") self.assert_parse("selinux --disabled", "selinux --disabled\n") # fail self.assert_parse_error("selinux --cheese") self.assert_parse_error("selinux --crackers=CRUNCHY") # extra test coverage cmd = self.handler().commands[self.command] for mode in [-1, 99999]: cmd.selinux = mode self.assertEqual(cmd.__str__(), "# SELinux configuration\n") cmd.selinux = SELINUX_DISABLED self.assertEqual(cmd.__str__(), "# SELinux configuration\nselinux --disabled\n") cmd.selinux = SELINUX_ENFORCING self.assertEqual(cmd.__str__(), "# SELinux configuration\nselinux --enforcing\n") cmd.selinux = SELINUX_PERMISSIVE self.assertEqual(cmd.__str__(), "# SELinux configuration\nselinux --permissive\n") if __name__ == "__main__": unittest.main()
gpl-2.0
sujeet4github/MyLangUtils
LangPython/oreilly-intro-to-flask-video/venv/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py
327
26955
# -*- coding: utf-8 -*- # # Copyright (C) 2012 The Python Software Foundation. # See LICENSE.txt and CONTRIBUTORS.txt. # """Access to Python's configuration information.""" import codecs import os import re import sys from os.path import pardir, realpath try: import configparser except ImportError: import ConfigParser as configparser __all__ = [ 'get_config_h_filename', 'get_config_var', 'get_config_vars', 'get_makefile_filename', 'get_path', 'get_path_names', 'get_paths', 'get_platform', 'get_python_version', 'get_scheme_names', 'parse_config_h', ] def _safe_realpath(path): try: return realpath(path) except OSError: return path if sys.executable: _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable)) else: # sys.executable can be empty if argv[0] has been changed and Python is # unable to retrieve the real program name _PROJECT_BASE = _safe_realpath(os.getcwd()) if os.name == "nt" and "pcbuild" in _PROJECT_BASE[-8:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir)) # PC/VS7.1 if os.name == "nt" and "\\pc\\v" in _PROJECT_BASE[-10:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) # PC/AMD64 if os.name == "nt" and "\\pcbuild\\amd64" in _PROJECT_BASE[-14:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) def is_python_build(): for fn in ("Setup.dist", "Setup.local"): if os.path.isfile(os.path.join(_PROJECT_BASE, "Modules", fn)): return True return False _PYTHON_BUILD = is_python_build() _cfg_read = False def _ensure_cfg_read(): global _cfg_read if not _cfg_read: from ..resources import finder backport_package = __name__.rsplit('.', 1)[0] _finder = finder(backport_package) _cfgfile = _finder.find('sysconfig.cfg') assert _cfgfile, 'sysconfig.cfg exists' with _cfgfile.as_stream() as s: _SCHEMES.readfp(s) if _PYTHON_BUILD: for scheme in ('posix_prefix', 'posix_home'): _SCHEMES.set(scheme, 'include', '{srcdir}/Include') _SCHEMES.set(scheme, 'platinclude', '{projectbase}/.') _cfg_read = True _SCHEMES = configparser.RawConfigParser() _VAR_REPL = re.compile(r'\{([^{]*?)\}') def _expand_globals(config): _ensure_cfg_read() if config.has_section('globals'): globals = config.items('globals') else: globals = tuple() sections = config.sections() for section in sections: if section == 'globals': continue for option, value in globals: if config.has_option(section, option): continue config.set(section, option, value) config.remove_section('globals') # now expanding local variables defined in the cfg file # for section in config.sections(): variables = dict(config.items(section)) def _replacer(matchobj): name = matchobj.group(1) if name in variables: return variables[name] return matchobj.group(0) for option, value in config.items(section): config.set(section, option, _VAR_REPL.sub(_replacer, value)) #_expand_globals(_SCHEMES) # FIXME don't rely on sys.version here, its format is an implementation detail # of CPython, use sys.version_info or sys.hexversion _PY_VERSION = sys.version.split()[0] _PY_VERSION_SHORT = sys.version[:3] _PY_VERSION_SHORT_NO_DOT = _PY_VERSION[0] + _PY_VERSION[2] _PREFIX = os.path.normpath(sys.prefix) _EXEC_PREFIX = os.path.normpath(sys.exec_prefix) _CONFIG_VARS = None _USER_BASE = None def _subst_vars(path, local_vars): """In the string `path`, replace tokens like {some.thing} with the corresponding value from the map `local_vars`. If there is no corresponding value, leave the token unchanged. """ def _replacer(matchobj): name = matchobj.group(1) if name in local_vars: return local_vars[name] elif name in os.environ: return os.environ[name] return matchobj.group(0) return _VAR_REPL.sub(_replacer, path) def _extend_dict(target_dict, other_dict): target_keys = target_dict.keys() for key, value in other_dict.items(): if key in target_keys: continue target_dict[key] = value def _expand_vars(scheme, vars): res = {} if vars is None: vars = {} _extend_dict(vars, get_config_vars()) for key, value in _SCHEMES.items(scheme): if os.name in ('posix', 'nt'): value = os.path.expanduser(value) res[key] = os.path.normpath(_subst_vars(value, vars)) return res def format_value(value, vars): def _replacer(matchobj): name = matchobj.group(1) if name in vars: return vars[name] return matchobj.group(0) return _VAR_REPL.sub(_replacer, value) def _get_default_scheme(): if os.name == 'posix': # the default scheme for posix is posix_prefix return 'posix_prefix' return os.name def _getuserbase(): env_base = os.environ.get("PYTHONUSERBASE", None) def joinuser(*args): return os.path.expanduser(os.path.join(*args)) # what about 'os2emx', 'riscos' ? if os.name == "nt": base = os.environ.get("APPDATA") or "~" if env_base: return env_base else: return joinuser(base, "Python") if sys.platform == "darwin": framework = get_config_var("PYTHONFRAMEWORK") if framework: if env_base: return env_base else: return joinuser("~", "Library", framework, "%d.%d" % sys.version_info[:2]) if env_base: return env_base else: return joinuser("~", ".local") def _parse_makefile(filename, vars=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ # Regexes needed for parsing Makefile (and similar syntaxes, # like old-style Setup files). _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)") _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") if vars is None: vars = {} done = {} notdone = {} with codecs.open(filename, encoding='utf-8', errors="surrogateescape") as f: lines = f.readlines() for line in lines: if line.startswith('#') or line.strip() == '': continue m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = v.strip() # `$$' is a literal `$' in make tmpv = v.replace('$$', '') if "$" in tmpv: notdone[n] = v else: try: v = int(v) except ValueError: # insert literal `$' done[n] = v.replace('$$', '$') else: done[n] = v # do variable interpolation here variables = list(notdone.keys()) # Variables with a 'PY_' prefix in the makefile. These need to # be made available without that prefix through sysconfig. # Special care is needed to ensure that variable expansion works, even # if the expansion uses the name without a prefix. renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') while len(variables) > 0: for name in tuple(variables): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m is not None: n = m.group(1) found = True if n in done: item = str(done[n]) elif n in notdone: # get it on a subsequent round found = False elif n in os.environ: # do it like make: fall back to environment item = os.environ[n] elif n in renamed_variables: if (name.startswith('PY_') and name[3:] in renamed_variables): item = "" elif 'PY_' + n in notdone: found = False else: item = str(done['PY_' + n]) else: done[n] = item = "" if found: after = value[m.end():] value = value[:m.start()] + item + after if "$" in after: notdone[name] = value else: try: value = int(value) except ValueError: done[name] = value.strip() else: done[name] = value variables.remove(name) if (name.startswith('PY_') and name[3:] in renamed_variables): name = name[3:] if name not in done: done[name] = value else: # bogus variable reference (e.g. "prefix=$/opt/python"); # just drop it since we can't deal done[name] = value variables.remove(name) # strip spurious spaces for k, v in done.items(): if isinstance(v, str): done[k] = v.strip() # save the results in the global dictionary vars.update(done) return vars def get_makefile_filename(): """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") if hasattr(sys, 'abiflags'): config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags) else: config_dir_name = 'config' return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile') def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # load the installed Makefile: makefile = get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % makefile if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED'] def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable)) # # public APIs # def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if vars is None: vars = {} define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") while True: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars def get_config_h_filename(): """Return the path of pyconfig.h.""" if _PYTHON_BUILD: if os.name == "nt": inc_dir = os.path.join(_PROJECT_BASE, "PC") else: inc_dir = _PROJECT_BASE else: inc_dir = get_path('platinclude') return os.path.join(inc_dir, 'pyconfig.h') def get_scheme_names(): """Return a tuple containing the schemes names.""" return tuple(sorted(_SCHEMES.sections())) def get_path_names(): """Return a tuple containing the paths names.""" # xxx see if we want a static list return _SCHEMES.options('posix_prefix') def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ _ensure_cfg_read() if expand: return _expand_vars(scheme, vars) else: return dict(_SCHEMES.items(scheme)) def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name] def get_config_vars(*args): """With no arguments, return a dictionary of all configuration variables relevant for the current platform. On Unix, this means every variable defined in Python's installed Makefile; On Windows and Mac OS it's a much smaller set. With arguments, return a list of values that result from looking up each argument in the configuration variable dictionary. """ global _CONFIG_VARS if _CONFIG_VARS is None: _CONFIG_VARS = {} # Normalized versions of prefix and exec_prefix are handy to have; # in fact, these are the standard versions used most places in the # distutils2 module. _CONFIG_VARS['prefix'] = _PREFIX _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX _CONFIG_VARS['py_version'] = _PY_VERSION _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2] _CONFIG_VARS['base'] = _PREFIX _CONFIG_VARS['platbase'] = _EXEC_PREFIX _CONFIG_VARS['projectbase'] = _PROJECT_BASE try: _CONFIG_VARS['abiflags'] = sys.abiflags except AttributeError: # sys.abiflags may not be defined on all platforms. _CONFIG_VARS['abiflags'] = '' if os.name in ('nt', 'os2'): _init_non_posix(_CONFIG_VARS) if os.name == 'posix': _init_posix(_CONFIG_VARS) # Setting 'userbase' is done below the call to the # init function to enable using 'get_config_var' in # the init-function. if sys.version >= '2.6': _CONFIG_VARS['userbase'] = _getuserbase() if 'srcdir' not in _CONFIG_VARS: _CONFIG_VARS['srcdir'] = _PROJECT_BASE else: _CONFIG_VARS['srcdir'] = _safe_realpath(_CONFIG_VARS['srcdir']) # Convert srcdir into an absolute path if it appears necessary. # Normally it is relative to the build directory. However, during # testing, for example, we might be running a non-installed python # from a different directory. if _PYTHON_BUILD and os.name == "posix": base = _PROJECT_BASE try: cwd = os.getcwd() except OSError: cwd = None if (not os.path.isabs(_CONFIG_VARS['srcdir']) and base != cwd): # srcdir is relative and we are not in the same directory # as the executable. Assume executable is in the build # directory and make srcdir absolute. srcdir = os.path.join(base, _CONFIG_VARS['srcdir']) _CONFIG_VARS['srcdir'] = os.path.normpath(srcdir) if sys.platform == 'darwin': kernel_version = os.uname()[2] # Kernel version (8.4.3) major_version = int(kernel_version.split('.')[0]) if major_version < 8: # On macOS before 10.4, check if -arch and -isysroot # are in CFLAGS or LDFLAGS and remove them if they are. # This is needed when building extensions on a 10.3 system # using a universal build of python. for key in ('LDFLAGS', 'BASECFLAGS', # a number of derived variables. These need to be # patched up as well. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): flags = _CONFIG_VARS[key] flags = re.sub('-arch\s+\w+\s', ' ', flags) flags = re.sub('-isysroot [^ \t]*', ' ', flags) _CONFIG_VARS[key] = flags else: # Allow the user to override the architecture flags using # an environment variable. # NOTE: This name was introduced by Apple in OSX 10.5 and # is used by several scripting languages distributed with # that OS release. if 'ARCHFLAGS' in os.environ: arch = os.environ['ARCHFLAGS'] for key in ('LDFLAGS', 'BASECFLAGS', # a number of derived variables. These need to be # patched up as well. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): flags = _CONFIG_VARS[key] flags = re.sub('-arch\s+\w+\s', ' ', flags) flags = flags + ' ' + arch _CONFIG_VARS[key] = flags # If we're on OSX 10.5 or later and the user tries to # compiles an extension using an SDK that is not present # on the current machine it is better to not use an SDK # than to fail. # # The major usecase for this is users using a Python.org # binary installer on OSX 10.6: that installer uses # the 10.4u SDK, but that SDK is not installed by default # when you install Xcode. # CFLAGS = _CONFIG_VARS.get('CFLAGS', '') m = re.search('-isysroot\s+(\S+)', CFLAGS) if m is not None: sdk = m.group(1) if not os.path.exists(sdk): for key in ('LDFLAGS', 'BASECFLAGS', # a number of derived variables. These need to be # patched up as well. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): flags = _CONFIG_VARS[key] flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags) _CONFIG_VARS[key] = flags if args: vals = [] for name in args: vals.append(_CONFIG_VARS.get(name)) return vals else: return _CONFIG_VARS def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) """ return get_config_vars().get(name) def get_platform(): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'. """ if os.name == 'nt': # sniff sys.version for architecture. prefix = " bit (" i = sys.version.find(prefix) if i == -1: return sys.platform j = sys.version.find(")", i) look = sys.version[i+len(prefix):j].lower() if look == 'amd64': return 'win-amd64' if look == 'itanium': return 'win-ia64' return sys.platform if os.name != "posix" or not hasattr(os, 'uname'): # XXX what about the architecture? NT is Intel or Alpha, # Mac OS is M68k or PPC, etc. return sys.platform # Try to distinguish various flavours of Unix osname, host, release, version, machine = os.uname() # Convert the OS name to lowercase, remove '/' characters # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh") osname = osname.lower().replace('/', '') machine = machine.replace(' ', '_') machine = machine.replace('/', '-') if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- # i386, etc. # XXX what about Alpha, SPARC, etc? return "%s-%s" % (osname, machine) elif osname[:5] == "sunos": if release[0] >= "5": # SunOS 5 == Solaris 2 osname = "solaris" release = "%d.%s" % (int(release[0]) - 3, release[2:]) # fall through to standard osname-release-machine representation elif osname[:4] == "irix": # could be "irix64"! return "%s-%s" % (osname, release) elif osname[:3] == "aix": return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": osname = "cygwin" rel_re = re.compile(r'[\d.]+') m = rel_re.match(release) if m: release = m.group() elif osname[:6] == "darwin": # # For our purposes, we'll assume that the system version from # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set # to. This makes the compatibility story a bit more sane because the # machine is going to compile and link as if it were # MACOSX_DEPLOYMENT_TARGET. cfgvars = get_config_vars() macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET') if True: # Always calculate the release of the running machine, # needed to determine if we can build fat binaries or not. macrelease = macver # Get the system version. Reading this plist is a documented # way to get the system version (see the documentation for # the Gestalt Manager) try: f = open('/System/Library/CoreServices/SystemVersion.plist') except IOError: # We're on a plain darwin box, fall back to the default # behaviour. pass else: try: m = re.search(r'<key>ProductUserVisibleVersion</key>\s*' r'<string>(.*?)</string>', f.read()) finally: f.close() if m is not None: macrelease = '.'.join(m.group(1).split('.')[:2]) # else: fall back to the default behaviour if not macver: macver = macrelease if macver: release = macver osname = "macosx" if ((macrelease + '.') >= '10.4.' and '-arch' in get_config_vars().get('CFLAGS', '').strip()): # The universal build will build fat binaries, but not on # systems before 10.4 # # Try to detect 4-way universal builds, those have machine-type # 'universal' instead of 'fat'. machine = 'fat' cflags = get_config_vars().get('CFLAGS') archs = re.findall('-arch\s+(\S+)', cflags) archs = tuple(sorted(set(archs))) if len(archs) == 1: machine = archs[0] elif archs == ('i386', 'ppc'): machine = 'fat' elif archs == ('i386', 'x86_64'): machine = 'intel' elif archs == ('i386', 'ppc', 'x86_64'): machine = 'fat3' elif archs == ('ppc64', 'x86_64'): machine = 'fat64' elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'): machine = 'universal' else: raise ValueError( "Don't know machine value for archs=%r" % (archs,)) elif machine == 'i386': # On OSX the machine type returned by uname is always the # 32-bit variant, even if the executable architecture is # the 64-bit variant if sys.maxsize >= 2**32: machine = 'x86_64' elif machine in ('PowerPC', 'Power_Macintosh'): # Pick a sane name for the PPC architecture. # See 'i386' case if sys.maxsize >= 2**32: machine = 'ppc64' else: machine = 'ppc' return "%s-%s-%s" % (osname, release, machine) def get_python_version(): return _PY_VERSION_SHORT def _print_dict(title, data): for index, (key, value) in enumerate(sorted(data.items())): if index == 0: print('%s: ' % (title)) print('\t%s = "%s"' % (key, value)) def _main(): """Display all information sysconfig detains.""" print('Platform: "%s"' % get_platform()) print('Python version: "%s"' % get_python_version()) print('Current installation scheme: "%s"' % _get_default_scheme()) print() _print_dict('Paths', get_paths()) print() _print_dict('Variables', get_config_vars()) if __name__ == '__main__': _main()
gpl-3.0
nop33/indico
indico/web/forms/fields/principals.py
2
5299
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico 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. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, unicode_literals import json from wtforms import HiddenField from indico.core.db.sqlalchemy.principals import PrincipalType from indico.modules.groups import GroupProxy from indico.modules.groups.util import serialize_group from indico.modules.networks.models.networks import IPNetworkGroup from indico.modules.networks.util import serialize_ip_network_group from indico.modules.users.util import serialize_user from indico.util.user import principal_from_fossil from indico.web.forms.widgets import JinjaWidget class PrincipalListField(HiddenField): """A field that lets you select a list Indico user/group ("principal") :param groups: If groups should be selectable. :param allow_networks: If ip networks should be selectable. :param allow_emails: If emails should be allowed. :param allow_external: If "search users with no indico account" should be available. Selecting such a user will automatically create a pending user once the form is submitted, even if other fields in the form fail to validate! """ widget = JinjaWidget('forms/principal_list_widget.html', single_kwargs=True) def __init__(self, *args, **kwargs): self.allow_emails = kwargs.pop('allow_emails', False) self.groups = kwargs.pop('groups', False) self.allow_networks = kwargs.pop('allow_networks', False) self.ip_networks = [] if self.allow_networks: self.ip_networks = map(serialize_ip_network_group, IPNetworkGroup.query.filter_by(hidden=False)) # Whether it is allowed to search for external users with no indico account self.allow_external = kwargs.pop('allow_external', False) # Whether the add user dialog is opened immediately when the field is displayed self.open_immediately = kwargs.pop('open_immediately', False) super(PrincipalListField, self).__init__(*args, **kwargs) def _convert_principal(self, principal): return principal_from_fossil(principal, allow_pending=self.allow_external, allow_emails=self.allow_emails, allow_networks=self.allow_networks, existing_data=self.object_data) def process_formdata(self, valuelist): if valuelist: self.data = {self._convert_principal(x) for x in json.loads(valuelist[0])} def pre_validate(self, form): if not self.groups and any(isinstance(p, GroupProxy) for p in self._get_data()): raise ValueError('You cannot select groups') def _serialize_principal(self, principal): if principal.principal_type == PrincipalType.email: return principal.fossilize() elif principal.principal_type == PrincipalType.network: return serialize_ip_network_group(principal) elif principal.principal_type == PrincipalType.user: return serialize_user(principal) elif principal.is_group: return serialize_group(principal) else: raise ValueError('Invalid principal: {} ({})'.format(principal, principal.principal_type)) def _value(self): from indico.modules.events.models.persons import PersonLinkBase def key(obj): if isinstance(obj, PersonLinkBase): return obj.name.lower() return obj.principal_type, obj.name.lower() principals = sorted(self._get_data(), key=key) return map(self._serialize_principal, principals) def _get_data(self): return sorted(self.data) if self.data else [] class AccessControlListField(PrincipalListField): widget = JinjaWidget('forms/principal_list_widget.html', single_kwargs=True, acl=True) def __init__(self, *args, **kwargs): # The text of the link that changes the protection mode of the object to protected self.default_text = kwargs.pop('default_text') super(AccessControlListField, self).__init__(*args, **kwargs) class PrincipalField(PrincipalListField): """A field that lets you select an Indico user/group ("principal")""" widget = JinjaWidget('forms/principal_widget.html', single_line=True) def _get_data(self): return [] if self.data is None else [self.data] def process_formdata(self, valuelist): if valuelist: data = map(self._convert_principal, json.loads(valuelist[0])) self.data = None if not data else data[0]
gpl-3.0
sanjeevtripurari/hue
desktop/core/ext-py/Django-1.6.10/tests/nested_foreign_keys/tests.py
59
9647
from __future__ import absolute_import from django.test import TestCase from .models import Person, Movie, Event, Screening, ScreeningNullFK, Package, PackageNullFK # These are tests for #16715. The basic scheme is always the same: 3 models with # 2 relations. The first relation may be null, while the second is non-nullable. # In some cases, Django would pick the wrong join type for the second relation, # resulting in missing objects in the queryset. # # Model A # | (Relation A/B : nullable) # Model B # | (Relation B/C : non-nullable) # Model C # # Because of the possibility of NULL rows resulting from the LEFT OUTER JOIN # between Model A and Model B (i.e. instances of A without reference to B), # the second join must also be LEFT OUTER JOIN, so that we do not ignore # instances of A that do not reference B. # # Relation A/B can either be an explicit foreign key or an implicit reverse # relation such as introduced by one-to-one relations (through multi-table # inheritance). class NestedForeignKeysTests(TestCase): def setUp(self): self.director = Person.objects.create(name='Terry Gilliam / Terry Jones') self.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=self.director) # This test failed in #16715 because in some cases INNER JOIN was selected # for the second foreign key relation instead of LEFT OUTER JOIN. def testInheritance(self): some_event = Event.objects.create() screening = Screening.objects.create(movie=self.movie) self.assertEqual(len(Event.objects.all()), 2) self.assertEqual(len(Event.objects.select_related('screening')), 2) # This failed. self.assertEqual(len(Event.objects.select_related('screening__movie')), 2) self.assertEqual(len(Event.objects.values()), 2) self.assertEqual(len(Event.objects.values('screening__pk')), 2) self.assertEqual(len(Event.objects.values('screening__movie__pk')), 2) self.assertEqual(len(Event.objects.values('screening__movie__title')), 2) # This failed. self.assertEqual(len(Event.objects.values('screening__movie__pk', 'screening__movie__title')), 2) # Simple filter/exclude queries for good measure. self.assertEqual(Event.objects.filter(screening__movie=self.movie).count(), 1) self.assertEqual(Event.objects.exclude(screening__movie=self.movie).count(), 1) # These all work because the second foreign key in the chain has null=True. def testInheritanceNullFK(self): some_event = Event.objects.create() screening = ScreeningNullFK.objects.create(movie=None) screening_with_movie = ScreeningNullFK.objects.create(movie=self.movie) self.assertEqual(len(Event.objects.all()), 3) self.assertEqual(len(Event.objects.select_related('screeningnullfk')), 3) self.assertEqual(len(Event.objects.select_related('screeningnullfk__movie')), 3) self.assertEqual(len(Event.objects.values()), 3) self.assertEqual(len(Event.objects.values('screeningnullfk__pk')), 3) self.assertEqual(len(Event.objects.values('screeningnullfk__movie__pk')), 3) self.assertEqual(len(Event.objects.values('screeningnullfk__movie__title')), 3) self.assertEqual(len(Event.objects.values('screeningnullfk__movie__pk', 'screeningnullfk__movie__title')), 3) self.assertEqual(Event.objects.filter(screeningnullfk__movie=self.movie).count(), 1) self.assertEqual(Event.objects.exclude(screeningnullfk__movie=self.movie).count(), 2) def test_null_exclude(self): screening = ScreeningNullFK.objects.create(movie=None) ScreeningNullFK.objects.create(movie=self.movie) self.assertEqual( list(ScreeningNullFK.objects.exclude(movie__id=self.movie.pk)), [screening]) # This test failed in #16715 because in some cases INNER JOIN was selected # for the second foreign key relation instead of LEFT OUTER JOIN. def testExplicitForeignKey(self): package = Package.objects.create() screening = Screening.objects.create(movie=self.movie) package_with_screening = Package.objects.create(screening=screening) self.assertEqual(len(Package.objects.all()), 2) self.assertEqual(len(Package.objects.select_related('screening')), 2) self.assertEqual(len(Package.objects.select_related('screening__movie')), 2) self.assertEqual(len(Package.objects.values()), 2) self.assertEqual(len(Package.objects.values('screening__pk')), 2) self.assertEqual(len(Package.objects.values('screening__movie__pk')), 2) self.assertEqual(len(Package.objects.values('screening__movie__title')), 2) # This failed. self.assertEqual(len(Package.objects.values('screening__movie__pk', 'screening__movie__title')), 2) self.assertEqual(Package.objects.filter(screening__movie=self.movie).count(), 1) self.assertEqual(Package.objects.exclude(screening__movie=self.movie).count(), 1) # These all work because the second foreign key in the chain has null=True. def testExplicitForeignKeyNullFK(self): package = PackageNullFK.objects.create() screening = ScreeningNullFK.objects.create(movie=None) screening_with_movie = ScreeningNullFK.objects.create(movie=self.movie) package_with_screening = PackageNullFK.objects.create(screening=screening) package_with_screening_with_movie = PackageNullFK.objects.create(screening=screening_with_movie) self.assertEqual(len(PackageNullFK.objects.all()), 3) self.assertEqual(len(PackageNullFK.objects.select_related('screening')), 3) self.assertEqual(len(PackageNullFK.objects.select_related('screening__movie')), 3) self.assertEqual(len(PackageNullFK.objects.values()), 3) self.assertEqual(len(PackageNullFK.objects.values('screening__pk')), 3) self.assertEqual(len(PackageNullFK.objects.values('screening__movie__pk')), 3) self.assertEqual(len(PackageNullFK.objects.values('screening__movie__title')), 3) self.assertEqual(len(PackageNullFK.objects.values('screening__movie__pk', 'screening__movie__title')), 3) self.assertEqual(PackageNullFK.objects.filter(screening__movie=self.movie).count(), 1) self.assertEqual(PackageNullFK.objects.exclude(screening__movie=self.movie).count(), 2) # Some additional tests for #16715. The only difference is the depth of the # nesting as we now use 4 models instead of 3 (and thus 3 relations). This # checks if promotion of join types works for deeper nesting too. class DeeplyNestedForeignKeysTests(TestCase): def setUp(self): self.director = Person.objects.create(name='Terry Gilliam / Terry Jones') self.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=self.director) def testInheritance(self): some_event = Event.objects.create() screening = Screening.objects.create(movie=self.movie) self.assertEqual(len(Event.objects.all()), 2) self.assertEqual(len(Event.objects.select_related('screening__movie__director')), 2) self.assertEqual(len(Event.objects.values()), 2) self.assertEqual(len(Event.objects.values('screening__movie__director__pk')), 2) self.assertEqual(len(Event.objects.values('screening__movie__director__name')), 2) self.assertEqual(len(Event.objects.values('screening__movie__director__pk', 'screening__movie__director__name')), 2) self.assertEqual(len(Event.objects.values('screening__movie__pk', 'screening__movie__director__pk')), 2) self.assertEqual(len(Event.objects.values('screening__movie__pk', 'screening__movie__director__name')), 2) self.assertEqual(len(Event.objects.values('screening__movie__title', 'screening__movie__director__pk')), 2) self.assertEqual(len(Event.objects.values('screening__movie__title', 'screening__movie__director__name')), 2) self.assertEqual(Event.objects.filter(screening__movie__director=self.director).count(), 1) self.assertEqual(Event.objects.exclude(screening__movie__director=self.director).count(), 1) def testExplicitForeignKey(self): package = Package.objects.create() screening = Screening.objects.create(movie=self.movie) package_with_screening = Package.objects.create(screening=screening) self.assertEqual(len(Package.objects.all()), 2) self.assertEqual(len(Package.objects.select_related('screening__movie__director')), 2) self.assertEqual(len(Package.objects.values()), 2) self.assertEqual(len(Package.objects.values('screening__movie__director__pk')), 2) self.assertEqual(len(Package.objects.values('screening__movie__director__name')), 2) self.assertEqual(len(Package.objects.values('screening__movie__director__pk', 'screening__movie__director__name')), 2) self.assertEqual(len(Package.objects.values('screening__movie__pk', 'screening__movie__director__pk')), 2) self.assertEqual(len(Package.objects.values('screening__movie__pk', 'screening__movie__director__name')), 2) self.assertEqual(len(Package.objects.values('screening__movie__title', 'screening__movie__director__pk')), 2) self.assertEqual(len(Package.objects.values('screening__movie__title', 'screening__movie__director__name')), 2) self.assertEqual(Package.objects.filter(screening__movie__director=self.director).count(), 1) self.assertEqual(Package.objects.exclude(screening__movie__director=self.director).count(), 1)
apache-2.0
donovan-duplessis/pwnurl
docs/conf.py
1
8358
#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) import pwnurl # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Pwnurl' copyright = u'2014, Donovan du Plessis' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = pwnurl.__version__ # The full version, including alpha/beta/rc tags. release = pwnurl.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pwnurldoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'pwnurl.tex', u'Pwnurl Documentation', u'Donovan du Plessis', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pwnurl', u'Pwnurl Documentation', [u'Donovan du Plessis'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pwnurl', u'Pwnurl Documentation', u'Donovan du Plessis', 'pwnurl', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
mit
google/contentbox
third_party/openid/yadis/manager.py
167
6081
class YadisServiceManager(object): """Holds the state of a list of selected Yadis services, managing storing it in a session and iterating over the services in order.""" def __init__(self, starting_url, yadis_url, services, session_key): # The URL that was used to initiate the Yadis protocol self.starting_url = starting_url # The URL after following redirects (the identifier) self.yadis_url = yadis_url # List of service elements self.services = list(services) self.session_key = session_key # Reference to the current service object self._current = None def __len__(self): """How many untried services remain?""" return len(self.services) def __iter__(self): return self def next(self): """Return the next service self.current() will continue to return that service until the next call to this method.""" try: self._current = self.services.pop(0) except IndexError: raise StopIteration else: return self._current def current(self): """Return the current service. Returns None if there are no services left. """ return self._current def forURL(self, url): return url in [self.starting_url, self.yadis_url] def started(self): """Has the first service been returned?""" return self._current is not None def store(self, session): """Store this object in the session, by its session key.""" session[self.session_key] = self class Discovery(object): """State management for discovery. High-level usage pattern is to call .getNextService(discover) in order to find the next available service for this user for this session. Once a request completes, call .finish() to clean up the session state. @ivar session: a dict-like object that stores state unique to the requesting user-agent. This object must be able to store serializable objects. @ivar url: the URL that is used to make the discovery request @ivar session_key_suffix: The suffix that will be used to identify this object in the session object. """ DEFAULT_SUFFIX = 'auth' PREFIX = '_yadis_services_' def __init__(self, session, url, session_key_suffix=None): """Initialize a discovery object""" self.session = session self.url = url if session_key_suffix is None: session_key_suffix = self.DEFAULT_SUFFIX self.session_key_suffix = session_key_suffix def getNextService(self, discover): """Return the next authentication service for the pair of user_input and session. This function handles fallback. @param discover: a callable that takes a URL and returns a list of services @type discover: str -> [service] @return: the next available service """ manager = self.getManager() if manager is not None and not manager: self.destroyManager() if not manager: yadis_url, services = discover(self.url) manager = self.createManager(services, yadis_url) if manager: service = manager.next() manager.store(self.session) else: service = None return service def cleanup(self, force=False): """Clean up Yadis-related services in the session and return the most-recently-attempted service from the manager, if one exists. @param force: True if the manager should be deleted regardless of whether it's a manager for self.url. @return: current service endpoint object or None if there is no current service """ manager = self.getManager(force=force) if manager is not None: service = manager.current() self.destroyManager(force=force) else: service = None return service ### Lower-level methods def getSessionKey(self): """Get the session key for this starting URL and suffix @return: The session key @rtype: str """ return self.PREFIX + self.session_key_suffix def getManager(self, force=False): """Extract the YadisServiceManager for this object's URL and suffix from the session. @param force: True if the manager should be returned regardless of whether it's a manager for self.url. @return: The current YadisServiceManager, if it's for this URL, or else None """ manager = self.session.get(self.getSessionKey()) if (manager is not None and (manager.forURL(self.url) or force)): return manager else: return None def createManager(self, services, yadis_url=None): """Create a new YadisService Manager for this starting URL and suffix, and store it in the session. @raises KeyError: When I already have a manager. @return: A new YadisServiceManager or None """ key = self.getSessionKey() if self.getManager(): raise KeyError('There is already a %r manager for %r' % (key, self.url)) if not services: return None manager = YadisServiceManager(self.url, yadis_url, services, key) manager.store(self.session) return manager def destroyManager(self, force=False): """Delete any YadisServiceManager with this starting URL and suffix from the session. If there is no service manager or the service manager is for a different URL, it silently does nothing. @param force: True if the manager should be deleted regardless of whether it's a manager for self.url. """ if self.getManager(force=force) is not None: key = self.getSessionKey() del self.session[key]
apache-2.0
devops2014/djangosite
django/contrib/admin/bin/compress.py
100
2075
#!/usr/bin/env python import argparse import os import subprocess import sys js_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'admin', 'js') def main(): description = """With no file paths given this script will automatically compress all jQuery-based files of the admin app. Requires the Google Closure Compiler library and Java version 6 or later.""" parser = argparse.ArgumentParser(description=description) parser.add_argument('file', nargs='*') parser.add_argument("-c", dest="compiler", default="~/bin/compiler.jar", help="path to Closure Compiler jar file") parser.add_argument("-v", "--verbose", action="store_true", dest="verbose") parser.add_argument("-q", "--quiet", action="store_false", dest="verbose") options = parser.parse_args() compiler = os.path.expanduser(options.compiler) if not os.path.exists(compiler): sys.exit( "Google Closure compiler jar file %s not found. Please use the -c " "option to specify the path." % compiler ) if not options.file: if options.verbose: sys.stdout.write("No filenames given; defaulting to admin scripts\n") files = [os.path.join(js_path, f) for f in [ "actions.js", "collapse.js", "inlines.js", "prepopulate.js"]] else: files = options.file for file_name in files: if not file_name.endswith(".js"): file_name = file_name + ".js" to_compress = os.path.expanduser(file_name) if os.path.exists(to_compress): to_compress_min = "%s.min.js" % "".join(file_name.rsplit(".js")) cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min) if options.verbose: sys.stdout.write("Running: %s\n" % cmd) subprocess.call(cmd.split()) else: sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress) if __name__ == '__main__': main()
bsd-3-clause
selfcommit/gaedav
pyxml/sax/drivers/drv_xmlproc.py
4
4400
""" A SAX driver for xmlproc $Id: drv_xmlproc.py,v 1.13 2001/12/30 12:13:45 loewis Exp $ """ version="0.95" from pyxml.sax import saxlib, saxutils from pyxml.parsers.xmlproc import xmlproc import os # --- SAX_XPParser class SAX_XPParser(saxlib.Parser,xmlproc.Application,xmlproc.DTDConsumer, xmlproc.ErrorHandler,xmlproc.PubIdResolver): def __init__(self): saxlib.Parser.__init__(self) self.reset() self.ns_separator=" " self.locator=1 self.is_parsing=0 self.stop_on_error=1 def parse(self,sysID): self.reset() try: self.is_parsing=1 self.parser.parse_resource(sysID) finally: self.is_parsing=0 def parseFile(self,file): self.reset() try: self.is_parsing=1 self.parser.read_from(file) self.parser.flush() self.parser.parseEnd() finally: self.is_parsing=0 def _create_parser(self): return xmlproc.XMLProcessor() def setLocale(self, locale): try: self.parser.set_error_language(locale) except KeyError: raise saxlib.SAXNotSupportedException("Locale '%s' not supported" % locale) # --- data event methods def doc_start(self): if self.locator: self.doc_handler.setDocumentLocator(self) self.doc_handler.startDocument() def doc_end(self): self.doc_handler.endDocument() def handle_data(self,data,start,end): self.doc_handler.characters(data,start,end-start) def handle_ignorable_data(self,data,start,end): self.doc_handler.ignorableWhitespace(data,start,end-start) def handle_pi(self, target, data): self.doc_handler.processingInstruction(target,data) def handle_start_tag(self, name, attrs): self.doc_handler.startElement(name,saxutils.AttributeMap(attrs)) def handle_end_tag(self, name): self.doc_handler.endElement(name) # --- pubid resolution def resolve_entity_pubid(self,pubid,sysid): return self.ent_handler.resolveEntity(pubid,sysid) def resolve_doctype_pubid(self,pubid,sysid): return self.ent_handler.resolveEntity(pubid,sysid) # --- error handling def warning(self,msg): self.err_handler.warning(saxlib.SAXParseException(msg,None,self)) def error(self,msg): self.err_handler.error(saxlib.SAXParseException(msg,None,self)) def fatal(self,msg): self.err_handler.fatalError(saxlib.SAXParseException(msg,None,self)) # --- location handling def getColumnNumber(self): return self.parser.get_column() def getLineNumber(self): return self.parser.get_line() def getSystemId(self): return self.parser.get_current_sysid() # --- DTD parsing def new_external_entity(self,name,pubid,sysid,ndata): if ndata!="": self.dtd_handler.unparsedEntityDecl(name,pubid,sysid,ndata) def new_notation(self,name,pubid,sysid): self.dtd_handler.notationDecl(name,pubid,sysid) # --- entity events def resolve_entity(self,pubid,sysid): newsysid=self.ent_handler.resolveEntity(pubid,sysid) if newsysid==None: return sysid else: return newsysid # --- EXPERIMENTAL PYTHON SAX EXTENSIONS: def get_parser_name(self): return "xmlproc" def get_parser_version(self): return xmlproc.version def get_driver_version(self): return version def is_validating(self): return 0 def is_dtd_reading(self): return 1 def reset(self): if hasattr(self, "parser"): self.parser.deref() self.parser=self._create_parser() self.parser.set_application(self) self.parser.set_error_handler(self) self.parser.set_pubid_resolver(self) self.parser.set_dtd_listener(self) self.parser.reset() def feed(self,data): self.parser.feed(data) def close(self): self.parser.close() self.parser.deref() # Dereferencing to avoid circular references (grrrr) self.err_handler = self.dtd_handler = self.doc_handler = None self.parser = self.locator = self.ent_handler = None # --- Global functions def create_parser(): return SAX_XPParser()
lgpl-2.1
AlexHill/django
django/utils/importlib.py
9
1485
# Taken from Python 2.7 with permission from/by the original author. import warnings import sys from django.utils import six warnings.warn("django.utils.importlib will be removed in Django 1.9.", PendingDeprecationWarning, stacklevel=2) def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in range(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: raise ValueError("attempted relative import beyond top-level package") return "%s.%s" % (package[:dot], name) if six.PY3: from importlib import import_module else: def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ if name.startswith('.'): if not package: raise TypeError("relative imports require the 'package' argument") level = 0 for character in name: if character != '.': break level += 1 name = _resolve_name(name[level:], package, level) __import__(name) return sys.modules[name]
bsd-3-clause
pombredanne/pants
tests/python/pants_test/backend/jvm/tasks/jvm_compile/java/jvm_platform_integration_mixin.py
6
9647
# coding=utf-8 # Copyright 2015 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 import re from subprocess import PIPE, Popen from textwrap import dedent from pants.fs.archive import ZIP from pants.util.contextutil import temporary_dir class JvmPlatformIntegrationMixin(object): """Mixin providing lots of JvmPlatform-related integration tests to java compilers (eg, zinc).""" def get_pants_compile_args(self): """List of arguments to pants that determine what compiler to use. The compiling task must be the last argument (eg, compile.zinc). """ raise NotImplementedError def determine_version(self, path): """Given the filepath to a class file, invokes the 'file' commandline to find its java version. :param str path: filepath (eg, tempdir/Foo.class) :return: A java version string (eg, '1.6'). """ # Map of target version numbers to their equivalent class file versions, which are different. version_map = { '50.0': '1.6', '51.0': '1.7', '52.0': '1.8', } p = Popen(['file', path], stdout=PIPE, stderr=PIPE) out, err = p.communicate() self.assertEqual(0, p.returncode, 'Failed to run file on {}.'.format(path)) match = re.search(r'version (\d+[.]\d+)', out) self.assertTrue(match is not None, 'Could not determine version for {}'.format(path)) return version_map[match.group(1)] def _get_jar_class_versions(self, jarname): path = os.path.join('dist', jarname) self.assertTrue(os.path.exists(path), '{} does not exist.'.format(path)) class_to_version = {} with temporary_dir() as tempdir: ZIP.extract(path, tempdir, filter_func=lambda f: f.endswith('.class')) for root, dirs, files in os.walk(tempdir): for name in files: path = os.path.abspath(os.path.join(root, name)) class_to_version[os.path.relpath(path, tempdir)] = self.determine_version(path) return class_to_version def _get_compiled_class_versions(self, spec, more_args=None): more_args = more_args or [] jar_name = os.path.basename(spec) while jar_name.endswith(':'): jar_name = jar_name[:-1] if ':' in jar_name: jar_name = jar_name[jar_name.find(':') + 1:] with temporary_dir() as cache_dir: config = {'cache.compile.zinc': {'write_to': [cache_dir]}} with self.temporary_workdir() as workdir: pants_run = self.run_pants_with_workdir( ['binary'] + self.get_pants_compile_args() + ['lint.checkstyle', '--skip', spec] + more_args, workdir, config) self.assert_success(pants_run) return self._get_jar_class_versions('{}.jar'.format(jar_name)) def assert_class_versions(self, expected, received): def format_dict(d): return ''.join('\n {} = {}'.format(key, val) for key, val in sorted(d.items())) self.assertEqual(expected, received, 'Compiled class versions differed.\n expected: {}\n received: {}' .format(format_dict(expected), format_dict(received))) def test_compile_java6(self): target_spec = 'testprojects/src/java/org/pantsbuild/testproject/targetlevels/java6' self.assert_class_versions({ 'org/pantsbuild/testproject/targetlevels/java6/Six.class': '1.6', }, self._get_compiled_class_versions(target_spec)) def test_compile_java7(self): target_spec = 'testprojects/src/java/org/pantsbuild/testproject/targetlevels/java7' self.assert_class_versions({ 'org/pantsbuild/testproject/targetlevels/java7/Seven.class': '1.7', }, self._get_compiled_class_versions(target_spec)) def test_compile_java7on6(self): target_spec = 'testprojects/src/java/org/pantsbuild/testproject/targetlevels/java7on6' self.assert_class_versions({ 'org/pantsbuild/testproject/targetlevels/java7on6/SevenOnSix.class': '1.7', 'org/pantsbuild/testproject/targetlevels/java6/Six.class': '1.6', }, self._get_compiled_class_versions(target_spec)) def test_compile_target_coercion(self): target_spec = 'testprojects/src/java/org/pantsbuild/testproject/targetlevels/unspecified' self.assert_class_versions({ 'org/pantsbuild/testproject/targetlevels/unspecified/Unspecified.class': '1.8', 'org/pantsbuild/testproject/targetlevels/unspecified/Seven.class': '1.7', }, self._get_compiled_class_versions(target_spec, more_args=[ '--jvm-platform-validate-check=warn', '--jvm-platform-default-platform=java8', ])) def _test_compile(self, target_level, class_name, source_contents, platform_args=None): with temporary_dir(root_dir=os.path.abspath('.')) as tmpdir: with open(os.path.join(tmpdir, 'BUILD'), 'w') as f: f.write(dedent(''' java_library(name='{target_name}', sources=['{class_name}.java'], platform='{target_level}', ) '''.format(target_name=os.path.basename(tmpdir), class_name=class_name, target_level=target_level))) with open(os.path.join(tmpdir, '{}.java'.format(class_name)), 'w') as f: f.write(source_contents) platforms = str({ str(target_level): { 'source': str(target_level), 'target': str(target_level), 'args': platform_args or [], } }) command = [] command.extend(['--jvm-platform-platforms={}'.format(platforms), '--jvm-platform-default-platform={}'.format(target_level)]) command.extend(self.get_pants_compile_args()) command.extend([tmpdir]) pants_run = self.run_pants(command) return pants_run def test_compile_diamond_operator_java7_works(self): pants_run = self._test_compile('1.7', 'Diamond', dedent(''' public class Diamond<T> { public static void main(String[] args) { Diamond<String> diamond = new Diamond<>(); } } ''')) self.assert_success(pants_run) def test_compile_diamond_operator_java6_fails(self): pants_run = self._test_compile('1.6', 'Diamond', dedent(''' public class Diamond<T> { public static void main(String[] args) { Diamond<String> diamond = new Diamond<>(); } } ''')) self.assert_failure(pants_run) def test_compile_with_javac_args(self): pants_run = self._test_compile('1.7', 'LintyDiamond', dedent(''' public class LintyDiamond<T> { public static void main(String[] args) { LintyDiamond<String> diamond = new LintyDiamond<>(); } } '''), platform_args=['-C-Xlint:cast']) self.assert_success(pants_run) def test_compile_stale_platform_settings(self): # Tests that targets are properly re-compiled when their source/target levels change. with temporary_dir(root_dir=os.path.abspath('.')) as tmpdir: with open(os.path.join(tmpdir, 'BUILD'), 'w') as f: f.write(dedent(''' java_library(name='diamond', sources=['Diamond.java'], ) ''')) with open(os.path.join(tmpdir, 'Diamond.java'), 'w') as f: f.write(dedent(''' public class Diamond<T> { public static void main(String[] args) { // The diamond operator <> for generics was introduced in jdk7. Diamond<String> shinyDiamond = new Diamond<>(); } } ''')) platforms = { 'java6': {'source': '6'}, 'java7': {'source': '7'}, } # We run these all in the same working directory, because we're testing caching behavior. with self.temporary_workdir() as workdir: def compile_diamond(platform): return self.run_pants_with_workdir(['--jvm-platform-platforms={}'.format(platforms), '--jvm-platform-default-platform={}'.format(platform), '-ldebug', 'compile'] + self.get_pants_compile_args() + ['{}:diamond'.format(tmpdir)], workdir=workdir) # We shouldn't be able to compile this with -source=6. self.assert_failure(compile_diamond('java6'), 'Diamond.java was compiled successfully with ' 'java6 starting from a fresh workdir, but ' 'that should not be possible.') # We should be able to compile this with -source=7. self.assert_success(compile_diamond('java7'), 'Diamond.java failed to compile in java7, ' 'which it should be able to.') # We still shouldn't be able to compile this with -source=6. If the below passes, it means # that we saved the cached run from java7 and didn't recompile, which is an error. self.assert_failure(compile_diamond('java6'), 'Diamond.java erroneously compiled in java6,' ' which means that either compilation was' ' skipped due to bad fingerprinting/caching,' ' or the compiler failed to clean up the' ' previous class from the java7' ' compile.')
apache-2.0
sergio-incaser/odoo
addons/hw_posbox_upgrade/__openerp__.py
313
1696
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'PosBox Software Upgrader', 'version': '1.0', 'category': 'Hardware Drivers', 'website': 'https://www.odoo.com/page/point-of-sale', 'sequence': 6, 'summary': 'Allows to remotely upgrade the PosBox software', 'description': """ PosBox Software Upgrader ======================== This module allows to remotely upgrade the PosBox software to a new version. This module is specific to the PosBox setup and environment and should not be installed on regular openerp servers. """, 'author': 'OpenERP SA', 'depends': ['hw_proxy'], 'test': [ ], 'installable': False, 'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
dunkhong/grr
grr/server/setup.py
1
7769
#!/usr/bin/env python """This is the setup.py file for the GRR client. This is just a meta-package which pulls in the minimal requirements to create a full grr server. """ from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import itertools import os import shutil import subprocess import sys from setuptools import find_packages from setuptools import setup from setuptools.command.develop import develop from setuptools.command.sdist import sdist GRR_NO_MAKE_UI_FILES_VAR = "GRR_NO_MAKE_UI_FILES" # TODO: Fix this import once support for Python 2 is dropped. # pylint: disable=g-import-not-at-top if sys.version_info.major == 2: import ConfigParser as configparser else: import configparser # pylint: enable=g-import-not-at-top def find_data_files(source, ignore_dirs=None): ignore_dirs = ignore_dirs or [] result = [] for directory, dirnames, files in os.walk(source): dirnames[:] = [d for d in dirnames if d not in ignore_dirs] files = [os.path.join(directory, x) for x in files] result.append((directory, files)) return result def make_ui_files(): """Builds necessary assets from sources.""" # Install node_modules, but keep package(-lock).json frozen. # Using shell=True, otherwise npm is not found in a nodeenv-built # virtualenv on Windows. subprocess.check_call( "npm ci", shell=True, cwd="grr_response_server/gui/static") subprocess.check_call( "npm run gulp compile", shell=True, cwd="grr_response_server/gui/static") def get_config(): """Get INI parser with version.ini data.""" ini_path = os.path.join(THIS_DIRECTORY, "version.ini") if not os.path.exists(ini_path): ini_path = os.path.join(THIS_DIRECTORY, "../../version.ini") if not os.path.exists(ini_path): raise RuntimeError("Couldn't find version.ini") config = configparser.SafeConfigParser() config.read(ini_path) return config IGNORE_GUI_DIRS = ["node_modules", "tmp"] THIS_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) # If you run setup.py from the root GRR dir you get very different results since # setuptools uses the MANIFEST.in from the root dir. Make sure we are in the # package dir. os.chdir(THIS_DIRECTORY) VERSION = get_config() class Develop(develop): """Build developer version (pip install -e).""" user_options = develop.user_options + [ # TODO: This has to be `bytes` on Python 2. Remove this `str` # call once support for Python 2 is dropped. (str("no-make-ui-files"), None, "Don't build UI JS/CSS bundles."), ] def initialize_options(self): self.no_make_ui_files = None develop.initialize_options(self) def run(self): # pip install -e . --install-option="--no-make-ui-files" passes the # --no-make-ui-files flag to all GRR dependencies, which doesn't make # much sense. Checking an environment variable to have an easy way # to set the flag for grr-response-server package only. if (not self.no_make_ui_files and not os.environ.get(GRR_NO_MAKE_UI_FILES_VAR)): make_ui_files() develop.run(self) class Sdist(sdist): """Build sdist.""" user_options = sdist.user_options + [ # TODO: This has to be `bytes` on Python 2. Remove this `str` # call once support for Python 2 is dropped. (str("no-make-ui-files"), None, "Don't build UI JS/CSS bundles."), ] def initialize_options(self): self.no_make_ui_files = None sdist.initialize_options(self) def run(self): # For consistency, respsecting GRR_NO_MAKE_UI_FILES variable just like # Develop command does. if (not self.no_make_ui_files and not os.environ.get(GRR_NO_MAKE_UI_FILES_VAR)): make_ui_files() sdist.run(self) def make_release_tree(self, base_dir, files): sdist.make_release_tree(self, base_dir, files) sdist_version_ini = os.path.join(base_dir, "version.ini") if os.path.exists(sdist_version_ini): os.unlink(sdist_version_ini) shutil.copy( os.path.join(THIS_DIRECTORY, "../../version.ini"), sdist_version_ini) data_files = list( itertools.chain( find_data_files("grr_response_server/checks"), find_data_files("grr_response_server/databases/mysql_migrations"), find_data_files("grr_response_server/gui/templates"), find_data_files( "grr_response_server/gui/static", ignore_dirs=IGNORE_GUI_DIRS), find_data_files( "grr_response_server/gui/local/static", ignore_dirs=IGNORE_GUI_DIRS), # TODO: This has to be `bytes` on Python 2. Remove this # `str` call once support for Python 2 is dropped. [str("version.ini")], )) setup_args = dict( name="grr-response-server", version=VERSION.get("Version", "packageversion"), description="The GRR Rapid Response Server.", license="Apache License, Version 2.0", maintainer="GRR Development Team", maintainer_email="grr-dev@googlegroups.com", url="https://github.com/google/grr", cmdclass={ "sdist": Sdist, "develop": Develop }, packages=find_packages(), entry_points={ "console_scripts": [ "grr_console = " "grr_response_server.distro_entry:Console", "grr_api_shell_raw_access = " "grr_response_server.distro_entry:ApiShellRawAccess", "grr_config_updater = " "grr_response_server.distro_entry:ConfigUpdater", "grr_frontend = " "grr_response_server.distro_entry:GrrFrontend", "grr_server = " "grr_response_server.distro_entry:GrrServer", "grr_worker = " "grr_response_server.distro_entry:Worker", "grr_admin_ui = " "grr_response_server.distro_entry:AdminUI", ] }, install_requires=[ "google-api-python-client==1.7.11", "google-auth==1.6.3", "google-cloud-bigquery==1.20.0", "grr-api-client==%s" % VERSION.get("Version", "packagedepends"), "grr-response-client-builder==%s" % VERSION.get("Version", "packagedepends"), "grr-response-core==%s" % VERSION.get("Version", "packagedepends"), "Jinja2==2.10.3", "pexpect==4.7.0", "portpicker==1.3.1", "prometheus_client==0.7.1", "pyjwt==1.7.1", "pyopenssl==19.0.0", # https://github.com/google/grr/issues/704 "python-crontab==2.3.9", "python-debian==0.1.36", "Werkzeug==0.16.0", ], extras_require={ # This is an optional component. Install to get MySQL data # store support: pip install grr-response[mysqldatastore] # When installing from .deb, the python-mysqldb package is used as # dependency instead of this pip dependency. This is because we run into # incompatibilities between the system mysqlclient/mariadbclient and the # Python library otherwise. Thus, this version has to be equal to the # python-mysqldb version of the system we support. This is currently # Ubuntu Xenial, see https://packages.ubuntu.com/xenial/python-mysqldb # # NOTE: the Xenial-provided 1.3.7 version is not properly Python 3 # compatible. Versions 1.3.13 or later are API-compatible with 1.3.7 # when running on Python 2 and work correctly on Python 3. However, # they don't have Python 2 wheels released, which makes GRR packaging # for Python 2 much harder if one of these versions is used. # # TODO(user): Find a way to use the latest mysqlclient version # in GRR server DEB. "mysqldatastore": ["mysqlclient==1.3.10"], }, data_files=data_files) setup(**setup_args)
apache-2.0
danijar/sets
sets/process/glove.py
1
1218
from zipfile import ZipFile import numpy as np from sets.core import Embedding class Glove(Embedding): """ The pretrained word embeddings from the Standford NLP group computed by the Glove model. From: http://nlp.stanford.edu/projects/glove/ """ URL = 'http://nlp.stanford.edu/data/glove.6B.zip' def __init__(self, size=100, depth=1): assert size in (50, 100, 300) words, embeddings = self.disk_cache('data', self._load, size) super().__init__(words, embeddings, depth) assert self.shape == (size,) @classmethod def _load(cls, size): filepath = cls.download(cls.URL) with ZipFile(filepath, 'r') as archive: filename = 'glove.6B.{}d.txt'.format(size) with archive.open(filename) as file_: return cls._parse(file_) @staticmethod def _parse(file_): words = [] embeddings = [] for line in file_: chunks = line.split() word = chunks[0].decode('utf-8') embedding = np.array(chunks[1:]).astype(np.float32) words.append(word) embeddings.append(embedding) return np.array(words), np.array(embeddings)
mit
xbianonpi/xbian-package-development
content/usr/local/lib/python2.7/dist-packages/distribute-0.6.30-py2.7.egg/setuptools/command/bdist_wininst.py
137
1548
from distutils.command.bdist_wininst import bdist_wininst as _bdist_wininst import os, sys class bdist_wininst(_bdist_wininst): def create_exe(self, arcname, fullname, bitmap=None): _bdist_wininst.create_exe(self, arcname, fullname, bitmap) dist_files = getattr(self.distribution, 'dist_files', []) if self.target_version: installer_name = os.path.join(self.dist_dir, "%s.win32-py%s.exe" % (fullname, self.target_version)) pyversion = self.target_version # fix 2.5 bdist_wininst ignoring --target-version spec bad = ('bdist_wininst','any',installer_name) if bad in dist_files: dist_files.remove(bad) else: installer_name = os.path.join(self.dist_dir, "%s.win32.exe" % fullname) pyversion = 'any' good = ('bdist_wininst', pyversion, installer_name) if good not in dist_files: dist_files.append(good) def reinitialize_command (self, command, reinit_subcommands=0): cmd = self.distribution.reinitialize_command( command, reinit_subcommands) if command in ('install', 'install_lib'): cmd.install_lib = None # work around distutils bug return cmd def run(self): self._is_running = True try: _bdist_wininst.run(self) finally: self._is_running = False
gpl-2.0
obnam-mirror/obnam
obnamlib/__init__.py
1
5952
# Copyright (C) 2009-2017 Lars Wirzenius # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import cliapp from .version import __version__, __version_info__ from .structurederror import StructuredError from .structurederror_finder import find_structured_errors from .obnamerror import ObnamError from .defaults import ( DEFAULT_NODE_SIZE, DEFAULT_CHUNK_SIZE, DEFAULT_UPLOAD_QUEUE_SIZE, DEFAULT_LRU_SIZE, DEFAULT_CHUNKIDS_PER_GROUP, DEFAULT_NAGIOS_WARN_AGE, DEFAULT_NAGIOS_CRIT_AGE, DEFAULT_DIR_BAG_BYTES, DEFAULT_DIR_CACHE_BYTES, DEFAULT_CHUNK_CACHE_BYTES, DEFAULT_CHUNK_BAG_BYTES, IDPATH_DEPTH, IDPATH_BITS, IDPATH_SKIP, MAX_ID, ) # Import _obnam if it is there. We need to be able to do things without # it, especially at build time, while we're generating manual pages. # If _obnam is not there, substitute a dummy that throws an exception # if used. try: import obnamlib._obnam except ImportError: class DummyExtension(object): def __getattr__(self, name): raise Exception('Trying to use _obnam, but that was not found.') _obnam = DummyExtension() from .sizeparse import SizeSyntaxError, UnitNameError, ByteSizeParser from .encryption import ( generate_symmetric_key, encrypt_symmetric, decrypt_symmetric, get_public_key, get_public_key_user_ids, Keyring, SecretKeyring, encrypt_with_keyring, decrypt_with_secret_keys, SymmetricKeyCache, EncryptionError, GpgError) from .hooks import ( Hook, MissingFilterError, NoFilterTagError, FilterHook, HookManager) from .pluginbase import ObnamPlugin from .vfs import ( VirtualFileSystem, VfsFactory, VfsTests, LockFail, NEW_DIR_MODE, NEW_FILE_MODE) from .vfs_local import LocalFS from .fsck_work_item import WorkItem from .repo_fs import RepositoryFS from .lockmgr import LockManager from .forget_policy import ForgetPolicy from .app import App, ObnamIOError, ObnamSystemError from .humanise import humanise_duration, humanise_size, humanise_speed from .chunkid_token_map import ChunkIdTokenMap from .pathname_excluder import PathnameExcluder from .splitpath import split_pathname from .obj_serialiser import serialise_object, deserialise_object from .bag import Bag, BagIdNotSetError, make_object_id, parse_object_id from .bag_store import BagStore, serialise_bag, deserialise_bag from .blob_store import BlobStore from .repo_factory import ( RepositoryFactory, UnknownRepositoryFormat, UnknownRepositoryFormatWanted) from .repo_interface import ( RepositoryInterface, RepositoryInterfaceTests, RepositoryClientAlreadyExists, RepositoryClientDoesNotExist, RepositoryClientListNotLocked, RepositoryClientListLockingFailed, RepositoryClientLockingFailed, RepositoryClientNotLocked, RepositoryClientKeyNotAllowed, RepositoryClientGenerationUnfinished, RepositoryGenerationKeyNotAllowed, RepositoryGenerationDoesNotExist, RepositoryClientHasNoGenerations, RepositoryFileDoesNotExistInGeneration, RepositoryFileKeyNotAllowed, RepositoryChunkDoesNotExist, RepositoryChunkContentNotInIndexes, RepositoryChunkIndexesNotLocked, RepositoryChunkIndexesLockingFailed, repo_key_name, REPO_CLIENT_TEST_KEY, REPO_GENERATION_TEST_KEY, REPO_GENERATION_STARTED, REPO_GENERATION_ENDED, REPO_GENERATION_IS_CHECKPOINT, REPO_GENERATION_FILE_COUNT, REPO_GENERATION_TOTAL_DATA, REPO_GENERATION_INTEGER_KEYS, REPO_FILE_TEST_KEY, REPO_FILE_MODE, REPO_FILE_MTIME_SEC, REPO_FILE_MTIME_NSEC, REPO_FILE_ATIME_SEC, REPO_FILE_ATIME_NSEC, REPO_FILE_NLINK, REPO_FILE_SIZE, REPO_FILE_UID, REPO_FILE_USERNAME, REPO_FILE_GID, REPO_FILE_GROUPNAME, REPO_FILE_SYMLINK_TARGET, REPO_FILE_XATTR_BLOB, REPO_FILE_BLOCKS, REPO_FILE_DEV, REPO_FILE_INO, REPO_FILE_MD5, REPO_FILE_SHA224, REPO_FILE_SHA256, REPO_FILE_SHA384, REPO_FILE_SHA512, REPO_FILE_INTEGER_KEYS, metadata_file_key_mapping) from .checksummer import ( checksum_algorithms, get_checksum_algorithm, get_checksum_algorithm_name, get_checksum_algorithm_key, ) from .whole_file_checksummer import WholeFileCheckSummer from .delegator import RepositoryDelegator, GenerationId from .backup_progress import BackupProgress # # Repository format green-albatross specific modules. # from .fmt_ga import ( GREEN_ALBATROSS_VERSION, RepositoryFormatGA, GAClientList, GAClient, GADirectory, GAImmutableError, create_gadirectory_from_dict, GATree, GAChunkStore, GAChunkIndexes, InMemoryLeafStore, LeafStore, CowLeaf, CowTree, LeafList, CowDelta, removed_key, ) # # Repository format 6 specific modules. # from .metadata import ( Metadata, read_metadata, set_metadata, SetMetadataError, metadata_fields) from .fmt_6.repo_fmt_6 import RepositoryFormat6 from .fmt_6.repo_tree import RepositoryTree from .fmt_6.chunklist import ChunkList from .fmt_6.clientlist import ClientList from .fmt_6.checksumtree import ChecksumTree from .fmt_6.clientmetadatatree import ClientMetadataTree option_group = { 'perf': 'Performance tweaking', 'devel': 'Development of Obnam itself', } __all__ = locals()
gpl-3.0
nilmini20s/gem5-2016-08-13
src/python/m5/debug.py
51
3475
# Copyright (c) 2008 The Hewlett-Packard Development Company # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Nathan Binkert from UserDict import DictMixin import internal from internal.debug import SimpleFlag, CompoundFlag from internal.debug import schedBreak, setRemoteGDBPort from m5.util import printList def help(): print "Base Flags:" for name in sorted(flags): if name == 'All': continue flag = flags[name] children = [c for c in flag.kids() ] if not children: print " %s: %s" % (name, flag.desc()) print print "Compound Flags:" for name in sorted(flags): if name == 'All': continue flag = flags[name] children = [c for c in flag.kids() ] if children: print " %s: %s" % (name, flag.desc()) printList([ c.name() for c in children ], indent=8) print class AllFlags(DictMixin): def __init__(self): self._version = -1 self._dict = {} def _update(self): current_version = internal.debug.getAllFlagsVersion() if self._version == current_version: return self._dict.clear() for flag in internal.debug.getAllFlags(): self._dict[flag.name()] = flag self._version = current_version def __contains__(self, item): self._update() return item in self._dict def __getitem__(self, item): self._update() return self._dict[item] def keys(self): self._update() return self._dict.keys() def values(self): self._update() return self._dict.values() def items(self): self._update() return self._dict.items() def iterkeys(self): self._update() return self._dict.iterkeys() def itervalues(self): self._update() return self._dict.itervalues() def iteritems(self): self._update() return self._dict.iteritems() flags = AllFlags()
bsd-3-clause
arlowhite/kivy
examples/canvas/tesselate.py
6
4478
''' Tesselate Demonstration ======================= This demonstrates the experimental library for tesselating polygons. You should see a hollow square with some buttons below it. You can click and drag to create additional shapes, watching the number of vertexes and elements at the top of the screen. The 'debug' button toggles showing the mesh in different colors. ''' from kivy.app import App from kivy.graphics import Mesh, Color from kivy.graphics.tesselator import Tesselator, WINDING_ODD, TYPE_POLYGONS from kivy.uix.widget import Widget from kivy.uix.floatlayout import FloatLayout from kivy.lang import Builder from kivy.logger import Logger Builder.load_string(""" <ShapeBuilder>: BoxLayout: size_hint_y: None height: "48dp" spacing: "2dp" padding: "2dp" ToggleButton: text: "Debug" id: debug on_release: root.build() Button: text: "New shape" on_release: root.push_shape() Button: text: "Build" on_release: root.build() Button: text: "Reset" on_release: root.reset() BoxLayout: size_hint_y: None height: "48dp" top: root.top spacing: "2dp" padding: "2dp" Label: id: status text: "Status" """) class ShapeBuilder(FloatLayout): def __init__(self, **kwargs): super(ShapeBuilder, self).__init__(**kwargs) self.shapes = [ [100, 100, 300, 100, 300, 300, 100, 300], [150, 150, 250, 150, 250, 250, 150, 250] ] # the 'hollow square' shape self.shape = [] self.build() def on_touch_down(self, touch): if super(ShapeBuilder, self).on_touch_down(touch): return True Logger.info('tesselate: on_touch_down (%5.2f, %5.2f)' % touch.pos) self.shape.extend(touch.pos) self.build() return True def on_touch_move(self, touch): if super(ShapeBuilder, self).on_touch_move(touch): return True Logger.info('tesselate: on_touch_move (%5.2f, %5.2f)' % touch.pos) self.shape.extend(touch.pos) self.build() return True def on_touch_up(self, touch): if super(ShapeBuilder, self).on_touch_up(touch): return True Logger.info('tesselate: on_touch_up (%5.2f, %5.2f)' % touch.pos) self.push_shape() self.build() def push_shape(self): self.shapes.append(self.shape) self.shape = [] def build(self): tess = Tesselator() count = 0 for shape in self.shapes: if len(shape) >= 3: tess.add_contour(shape) count += 1 if self.shape and len(self.shape) >= 3: tess.add_contour(self.shape) count += 1 if not count: return ret = tess.tesselate(WINDING_ODD, TYPE_POLYGONS) Logger.info('tesselate: build: tess.tesselate returns {}'.format(ret)) self.canvas.after.clear() debug = self.ids.debug.state == "down" if debug: from random import random with self.canvas.after: c = 0 for vertices, indices in tess.meshes: Color(c, 1, 1, mode="hsv") c += 0.3 indices = [0] for i in range(1, len(vertices) // 4): if i > 0: indices.append(i) indices.append(i) indices.append(0) indices.append(i) indices.pop(-1) Mesh(vertices=vertices, indices=indices, mode="lines") else: with self.canvas.after: Color(1, 1, 1, 1) for vertices, indices in tess.meshes: Mesh(vertices=vertices, indices=indices, mode="triangle_fan") self.ids.status.text = "Shapes: {} - Vertex: {} - Elements: {}".format( count, tess.vertex_count, tess.element_count) def reset(self): self.shapes = [] self.shape = [] self.ids.status.text = "Shapes: {} - Vertex: {} - Elements: {}".format( 0, 0, 0) self.canvas.after.clear() class TessApp(App): def build(self): return ShapeBuilder() TessApp().run()
mit
sorenh/cc
nova/tests/network_unittest.py
1
5207
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2010 Anso Labs, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging import unittest from nova import vendor import IPy from nova import flags from nova import test from nova.compute import network from nova.auth import users from nova import utils class NetworkTestCase(test.TrialTestCase): def setUp(self): super(NetworkTestCase, self).setUp() self.flags(fake_libvirt=True, fake_storage=True, fake_network=True, network_size=32) logging.getLogger().setLevel(logging.DEBUG) self.manager = users.UserManager.instance() try: self.manager.create_user('netuser', 'netuser', 'netuser') except: pass for i in range(0, 6): name = 'project%s' % i if not self.manager.get_project(name): self.manager.create_project(name, 'netuser', name) self.network = network.PublicNetworkController() def tearDown(self): super(NetworkTestCase, self).tearDown() for i in range(0, 6): name = 'project%s' % i self.manager.delete_project(name) self.manager.delete_user('netuser') def test_public_network_allocation(self): pubnet = IPy.IP(flags.FLAGS.public_range) address = self.network.allocate_ip("netuser", "project0", "public") self.assertTrue(IPy.IP(address) in pubnet) self.assertTrue(IPy.IP(address) in self.network.network) def test_allocate_deallocate_ip(self): address = network.allocate_ip( "netuser", "project0", utils.generate_mac()) logging.debug("Was allocated %s" % (address)) self.assertEqual(True, address in self._get_project_addresses("project0")) rv = network.deallocate_ip(address) self.assertEqual(False, address in self._get_project_addresses("project0")) def test_range_allocation(self): address = network.allocate_ip( "netuser", "project0", utils.generate_mac()) secondaddress = network.allocate_ip( "netuser", "project1", utils.generate_mac()) self.assertEqual(True, address in self._get_project_addresses("project0")) self.assertEqual(True, secondaddress in self._get_project_addresses("project1")) self.assertEqual(False, address in self._get_project_addresses("project1")) rv = network.deallocate_ip(address) self.assertEqual(False, address in self._get_project_addresses("project0")) rv = network.deallocate_ip(secondaddress) self.assertEqual(False, secondaddress in self._get_project_addresses("project1")) def test_subnet_edge(self): secondaddress = network.allocate_ip("netuser", "project0", utils.generate_mac()) for project in range(1,5): project_id = "project%s" % (project) address = network.allocate_ip( "netuser", project_id, utils.generate_mac()) address2 = network.allocate_ip( "netuser", project_id, utils.generate_mac()) address3 = network.allocate_ip( "netuser", project_id, utils.generate_mac()) self.assertEqual(False, address in self._get_project_addresses("project0")) self.assertEqual(False, address2 in self._get_project_addresses("project0")) self.assertEqual(False, address3 in self._get_project_addresses("project0")) rv = network.deallocate_ip(address) rv = network.deallocate_ip(address2) rv = network.deallocate_ip(address3) rv = network.deallocate_ip(secondaddress) def test_too_many_projects(self): for i in range(0, 30): name = 'toomany-project%s' % i self.manager.create_project(name, 'netuser', name) address = network.allocate_ip( "netuser", name, utils.generate_mac()) rv = network.deallocate_ip(address) self.manager.delete_project(name) def _get_project_addresses(self, project_id): project_addresses = [] for addr in network.get_project_network(project_id).list_addresses(): project_addresses.append(addr) return project_addresses
apache-2.0
Learningtribes/edx-platform
common/djangoapps/external_auth/views.py
12
36626
import functools import json import logging import random import re import string import fnmatch import unicodedata import urllib from textwrap import dedent from external_auth.models import ExternalAuthMap from external_auth.djangostore import DjangoOpenIDStore from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME, authenticate, login from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.core.validators import validate_email from django.core.exceptions import ValidationError if settings.FEATURES.get('AUTH_USE_CAS'): from django_cas.views import login as django_cas_login from student.helpers import get_next_url_for_login_page from student.models import UserProfile from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden from django.utils.http import urlquote, is_safe_url from django.shortcuts import redirect from django.utils.translation import ugettext as _ from edxmako.shortcuts import render_to_response, render_to_string try: from django.views.decorators.csrf import csrf_exempt except ImportError: from django.contrib.csrf.middleware import csrf_exempt from django.views.decorators.csrf import ensure_csrf_cookie import django_openid_auth.views as openid_views from django_openid_auth import auth as openid_auth from openid.consumer.consumer import SUCCESS from openid.server.server import Server, ProtocolError, UntrustedReturnURL from openid.server.trustroot import TrustRoot from openid.extensions import ax, sreg from ratelimitbackend.exceptions import RateLimitException import student.views from xmodule.modulestore.django import modulestore from opaque_keys.edx.locations import SlashSeparatedCourseKey log = logging.getLogger("edx.external_auth") AUDIT_LOG = logging.getLogger("audit") SHIBBOLETH_DOMAIN_PREFIX = settings.SHIBBOLETH_DOMAIN_PREFIX OPENID_DOMAIN_PREFIX = settings.OPENID_DOMAIN_PREFIX # ----------------------------------------------------------------------------- # OpenID Common # ----------------------------------------------------------------------------- @csrf_exempt def default_render_failure(request, message, status=403, template_name='extauth_failure.html', exception=None): """Render an Openid error page to the user""" log.debug("In openid_failure " + message) data = render_to_string(template_name, dict(message=message, exception=exception)) return HttpResponse(data, status=status) # ----------------------------------------------------------------------------- # OpenID Authentication # ----------------------------------------------------------------------------- def generate_password(length=12, chars=string.letters + string.digits): """Generate internal password for externally authenticated user""" choice = random.SystemRandom().choice return ''.join([choice(chars) for _i in range(length)]) @csrf_exempt def openid_login_complete(request, redirect_field_name=REDIRECT_FIELD_NAME, render_failure=None): """Complete the openid login process""" render_failure = (render_failure or default_render_failure) openid_response = openid_views.parse_openid_response(request) if not openid_response: return render_failure(request, 'This is an OpenID relying party endpoint.') if openid_response.status == SUCCESS: external_id = openid_response.identity_url oid_backend = openid_auth.OpenIDBackend() details = oid_backend._extract_user_details(openid_response) log.debug('openid success, details=%s', details) url = getattr(settings, 'OPENID_SSO_SERVER_URL', None) external_domain = "{0}{1}".format(OPENID_DOMAIN_PREFIX, url) fullname = '%s %s' % (details.get('first_name', ''), details.get('last_name', '')) return _external_login_or_signup( request, external_id, external_domain, details, details.get('email', ''), fullname, retfun=functools.partial(redirect, get_next_url_for_login_page(request)), ) return render_failure(request, 'Openid failure') def _external_login_or_signup(request, external_id, external_domain, credentials, email, fullname, retfun=None): """Generic external auth login or signup""" # see if we have a map from this external_id to an edX username try: eamap = ExternalAuthMap.objects.get(external_id=external_id, external_domain=external_domain) log.debug(u'Found eamap=%s', eamap) except ExternalAuthMap.DoesNotExist: # go render form for creating edX user eamap = ExternalAuthMap(external_id=external_id, external_domain=external_domain, external_credentials=json.dumps(credentials)) eamap.external_email = email eamap.external_name = fullname eamap.internal_password = generate_password() log.debug(u'Created eamap=%s', eamap) eamap.save() log.info(u"External_Auth login_or_signup for %s : %s : %s : %s", external_domain, external_id, email, fullname) uses_shibboleth = settings.FEATURES.get('AUTH_USE_SHIB') and external_domain.startswith(SHIBBOLETH_DOMAIN_PREFIX) uses_certs = settings.FEATURES.get('AUTH_USE_CERTIFICATES') internal_user = eamap.user if internal_user is None: if uses_shibboleth: # If we are using shib, try to link accounts # For Stanford shib, the email the idp returns is actually under the control of the user. # Since the id the idps return is not user-editable, and is of the from "username@stanford.edu", # use the id to link accounts instead. try: link_user = User.objects.get(email=eamap.external_id) if not ExternalAuthMap.objects.filter(user=link_user).exists(): # if there's no pre-existing linked eamap, we link the user eamap.user = link_user eamap.save() internal_user = link_user log.info(u'SHIB: Linking existing account for %s', eamap.external_id) # now pass through to log in else: # otherwise, there must have been an error, b/c we've already linked a user with these external # creds failure_msg = _( "You have already created an account using " "an external login like WebAuth or Shibboleth. " "Please contact {tech_support_email} for support." ).format( tech_support_email=settings.TECH_SUPPORT_EMAIL, ) return default_render_failure(request, failure_msg) except User.DoesNotExist: log.info(u'SHIB: No user for %s yet, doing signup', eamap.external_email) return _signup(request, eamap, retfun) else: log.info(u'No user for %s yet. doing signup', eamap.external_email) return _signup(request, eamap, retfun) # We trust shib's authentication, so no need to authenticate using the password again uname = internal_user.username if uses_shibboleth: user = internal_user # Assuming this 'AUTHENTICATION_BACKENDS' is set in settings, which I think is safe if settings.AUTHENTICATION_BACKENDS: auth_backend = settings.AUTHENTICATION_BACKENDS[0] else: auth_backend = 'ratelimitbackend.backends.RateLimitModelBackend' user.backend = auth_backend if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.info(u'Linked user.id: {0} logged in via Shibboleth'.format(user.id)) else: AUDIT_LOG.info(u'Linked user "{0}" logged in via Shibboleth'.format(user.email)) elif uses_certs: # Certificates are trusted, so just link the user and log the action user = internal_user user.backend = 'ratelimitbackend.backends.RateLimitModelBackend' if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.info(u'Linked user_id {0} logged in via SSL certificate'.format(user.id)) else: AUDIT_LOG.info(u'Linked user "{0}" logged in via SSL certificate'.format(user.email)) else: user = authenticate(username=uname, password=eamap.internal_password, request=request) if user is None: # we want to log the failure, but don't want to log the password attempted: if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.warning(u'External Auth Login failed') else: AUDIT_LOG.warning(u'External Auth Login failed for "{0}"'.format(uname)) return _signup(request, eamap, retfun) if not user.is_active: if settings.FEATURES.get('BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH'): # if BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH, we trust external auth and activate any users # that aren't already active user.is_active = True user.save() if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.info(u'Activating user {0} due to external auth'.format(user.id)) else: AUDIT_LOG.info(u'Activating user "{0}" due to external auth'.format(uname)) else: if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.warning(u'User {0} is not active after external login'.format(user.id)) else: AUDIT_LOG.warning(u'User "{0}" is not active after external login'.format(uname)) # TODO: improve error page msg = 'Account not yet activated: please look for link in your email' return default_render_failure(request, msg) login(request, user) request.session.set_expiry(0) if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.info(u"Login success - user.id: {0}".format(user.id)) else: AUDIT_LOG.info(u"Login success - {0} ({1})".format(user.username, user.email)) if retfun is None: return redirect('/') return retfun() def _flatten_to_ascii(txt): """ Flattens possibly unicode txt to ascii (django username limitation) @param name: @return: the flattened txt (in the same type as was originally passed in) """ if isinstance(txt, str): txt = txt.decode('utf-8') return unicodedata.normalize('NFKD', txt).encode('ASCII', 'ignore') else: return unicode(unicodedata.normalize('NFKD', txt).encode('ASCII', 'ignore')) @ensure_csrf_cookie def _signup(request, eamap, retfun=None): """ Present form to complete for signup via external authentication. Even though the user has external credentials, he/she still needs to create an account on the edX system, and fill in the user registration form. eamap is an ExternalAuthMap object, specifying the external user for which to complete the signup. retfun is a function to execute for the return value, if immediate signup is used. That allows @ssl_login_shortcut() to work. """ # save this for use by student.views.create_account request.session['ExternalAuthMap'] = eamap if settings.FEATURES.get('AUTH_USE_CERTIFICATES_IMMEDIATE_SIGNUP', ''): # do signin immediately, by calling create_account, instead of asking # student to fill in form. MIT students already have information filed. username = eamap.external_email.split('@', 1)[0] username = username.replace('.', '_') post_vars = dict(username=username, honor_code=u'true', terms_of_service=u'true') log.info(u'doing immediate signup for %s, params=%s', username, post_vars) student.views.create_account(request, post_vars) # should check return content for successful completion before if retfun is not None: return retfun() else: return redirect('/') # default conjoin name, no spaces, flattened to ascii b/c django can't handle unicode usernames, sadly # but this only affects username, not fullname username = re.sub(r'\s', '', _flatten_to_ascii(eamap.external_name), flags=re.UNICODE) context = {'has_extauth_info': True, 'show_signup_immediately': True, 'extauth_domain': eamap.external_domain, 'extauth_id': eamap.external_id, 'extauth_email': eamap.external_email, 'extauth_username': username, 'extauth_name': eamap.external_name, 'ask_for_tos': True, } # Some openEdX instances can't have terms of service for shib users, like # according to Stanford's Office of General Counsel uses_shibboleth = (settings.FEATURES.get('AUTH_USE_SHIB') and eamap.external_domain.startswith(SHIBBOLETH_DOMAIN_PREFIX)) if uses_shibboleth and settings.FEATURES.get('SHIB_DISABLE_TOS'): context['ask_for_tos'] = False # detect if full name is blank and ask for it from user context['ask_for_fullname'] = eamap.external_name.strip() == '' # validate provided mail and if it's not valid ask the user try: validate_email(eamap.external_email) context['ask_for_email'] = False except ValidationError: context['ask_for_email'] = True log.info(u'EXTAUTH: Doing signup for %s', eamap.external_id) return student.views.register_user(request, extra_context=context) # ----------------------------------------------------------------------------- # MIT SSL # ----------------------------------------------------------------------------- def _ssl_dn_extract_info(dn_string): """ Extract username, email address (may be anyuser@anydomain.com) and full name from the SSL DN string. Return (user,email,fullname) if successful, and None otherwise. """ ss = re.search('/emailAddress=(.*)@([^/]+)', dn_string) if ss: user = ss.group(1) email = "%s@%s" % (user, ss.group(2)) else: return None ss = re.search('/CN=([^/]+)/', dn_string) if ss: fullname = ss.group(1) else: return None return (user, email, fullname) def ssl_get_cert_from_request(request): """ Extract user information from certificate, if it exists, returning (user, email, fullname). Else return None. """ certkey = "SSL_CLIENT_S_DN" # specify the request.META field to use cert = request.META.get(certkey, '') if not cert: cert = request.META.get('HTTP_' + certkey, '') if not cert: try: # try the direct apache2 SSL key cert = request._req.subprocess_env.get(certkey, '') except Exception: return '' return cert def ssl_login_shortcut(fn): """ Python function decorator for login procedures, to allow direct login based on existing ExternalAuth record and MIT ssl certificate. """ def wrapped(*args, **kwargs): """ This manages the function wrapping, by determining whether to inject the _external signup or just continuing to the internal function call. """ if not settings.FEATURES['AUTH_USE_CERTIFICATES']: return fn(*args, **kwargs) request = args[0] if request.user and request.user.is_authenticated(): # don't re-authenticate return fn(*args, **kwargs) cert = ssl_get_cert_from_request(request) if not cert: # no certificate information - show normal login window return fn(*args, **kwargs) def retfun(): """Wrap function again for call by _external_login_or_signup""" return fn(*args, **kwargs) (_user, email, fullname) = _ssl_dn_extract_info(cert) return _external_login_or_signup( request, external_id=email, external_domain="ssl:MIT", credentials=cert, email=email, fullname=fullname, retfun=retfun ) return wrapped @csrf_exempt def ssl_login(request): """ This is called by branding.views.index when FEATURES['AUTH_USE_CERTIFICATES'] = True Used for MIT user authentication. This presumes the web server (nginx) has been configured to require specific client certificates. If the incoming protocol is HTTPS (SSL) then authenticate via client certificate. The certificate provides user email and fullname; this populates the ExternalAuthMap. The user is nevertheless still asked to complete the edX signup. Else continues on with student.views.index, and no authentication. """ # Just to make sure we're calling this only at MIT: if not settings.FEATURES['AUTH_USE_CERTIFICATES']: return HttpResponseForbidden() cert = ssl_get_cert_from_request(request) if not cert: # no certificate information - go onward to main index return student.views.index(request) (_user, email, fullname) = _ssl_dn_extract_info(cert) redirect_to = get_next_url_for_login_page(request) retfun = functools.partial(redirect, redirect_to) return _external_login_or_signup( request, external_id=email, external_domain="ssl:MIT", credentials=cert, email=email, fullname=fullname, retfun=retfun ) # ----------------------------------------------------------------------------- # CAS (Central Authentication Service) # ----------------------------------------------------------------------------- def cas_login(request, next_page=None, required=False): """ Uses django_cas for authentication. CAS is a common authentcation method pioneered by Yale. See http://en.wikipedia.org/wiki/Central_Authentication_Service Does normal CAS login then generates user_profile if nonexistent, and if login was successful. We assume that user details are maintained by the central service, and thus an empty user profile is appropriate. """ ret = django_cas_login(request, next_page, required) if request.user.is_authenticated(): user = request.user UserProfile.objects.get_or_create( user=user, defaults={'name': user.username} ) return ret # ----------------------------------------------------------------------------- # Shibboleth (Stanford and others. Uses *Apache* environment variables) # ----------------------------------------------------------------------------- def shib_login(request): """ Uses Apache's REMOTE_USER environment variable as the external id. This in turn typically uses EduPersonPrincipalName http://www.incommonfederation.org/attributesummary.html#eduPersonPrincipal but the configuration is in the shibboleth software. """ shib_error_msg = _(dedent( """ Your university identity server did not return your ID information to us. Please try logging in again. (You may need to restart your browser.) """)) if not request.META.get('REMOTE_USER'): log.error(u"SHIB: no REMOTE_USER found in request.META") return default_render_failure(request, shib_error_msg) elif not request.META.get('Shib-Identity-Provider'): log.error(u"SHIB: no Shib-Identity-Provider in request.META") return default_render_failure(request, shib_error_msg) else: # If we get here, the user has authenticated properly shib = {attr: request.META.get(attr, '').decode('utf-8') for attr in ['REMOTE_USER', 'givenName', 'sn', 'mail', 'Shib-Identity-Provider', 'displayName']} # Clean up first name, last name, and email address # TODO: Make this less hardcoded re: format, but split will work # even if ";" is not present, since we are accessing 1st element shib['sn'] = shib['sn'].split(";")[0].strip().capitalize() shib['givenName'] = shib['givenName'].split(";")[0].strip().capitalize() # TODO: should we be logging creds here, at info level? log.info(u"SHIB creds returned: %r", shib) fullname = shib['displayName'] if shib['displayName'] else u'%s %s' % (shib['givenName'], shib['sn']) redirect_to = get_next_url_for_login_page(request) retfun = functools.partial(_safe_postlogin_redirect, redirect_to, request.get_host()) return _external_login_or_signup( request, external_id=shib['REMOTE_USER'], external_domain=SHIBBOLETH_DOMAIN_PREFIX + shib['Shib-Identity-Provider'], credentials=shib, email=shib['mail'], fullname=fullname, retfun=retfun ) def _safe_postlogin_redirect(redirect_to, safehost, default_redirect='/'): """ If redirect_to param is safe (not off this host), then perform the redirect. Otherwise just redirect to '/'. Basically copied from django.contrib.auth.views.login @param redirect_to: user-supplied redirect url @param safehost: which host is safe to redirect to @return: an HttpResponseRedirect """ if is_safe_url(url=redirect_to, host=safehost): return redirect(redirect_to) return redirect(default_redirect) def course_specific_login(request, course_id): """ Dispatcher function for selecting the specific login method required by the course """ course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id) course = modulestore().get_course(course_key) if not course: # couldn't find the course, will just return vanilla signin page return redirect_with_get('signin_user', request.GET) # now the dispatching conditionals. Only shib for now if ( settings.FEATURES.get('AUTH_USE_SHIB') and course.enrollment_domain and course.enrollment_domain.startswith(SHIBBOLETH_DOMAIN_PREFIX) ): return redirect_with_get('shib-login', request.GET) # Default fallthrough to normal signin page return redirect_with_get('signin_user', request.GET) def course_specific_register(request, course_id): """ Dispatcher function for selecting the specific registration method required by the course """ course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id) course = modulestore().get_course(course_key) if not course: # couldn't find the course, will just return vanilla registration page return redirect_with_get('register_user', request.GET) # now the dispatching conditionals. Only shib for now if ( settings.FEATURES.get('AUTH_USE_SHIB') and course.enrollment_domain and course.enrollment_domain.startswith(SHIBBOLETH_DOMAIN_PREFIX) ): # shib-login takes care of both registration and login flows return redirect_with_get('shib-login', request.GET) # Default fallthrough to normal registration page return redirect_with_get('register_user', request.GET) def redirect_with_get(view_name, get_querydict, do_reverse=True): """ Helper function to carry over get parameters across redirects Using urlencode(safe='/') because the @login_required decorator generates 'next' queryparams with '/' unencoded """ if do_reverse: url = reverse(view_name) else: url = view_name if get_querydict: return redirect("%s?%s" % (url, get_querydict.urlencode(safe='/'))) return redirect(view_name) # ----------------------------------------------------------------------------- # OpenID Provider # ----------------------------------------------------------------------------- def get_xrds_url(resource, request): """ Return the XRDS url for a resource """ host = request.get_host() location = host + '/openid/provider/' + resource + '/' if request.is_secure(): return 'https://' + location else: return 'http://' + location def add_openid_simple_registration(request, response, data): sreg_data = {} sreg_request = sreg.SRegRequest.fromOpenIDRequest(request) sreg_fields = sreg_request.allRequestedFields() # if consumer requested simple registration fields, add them if sreg_fields: for field in sreg_fields: if field == 'email' and 'email' in data: sreg_data['email'] = data['email'] elif field == 'fullname' and 'fullname' in data: sreg_data['fullname'] = data['fullname'] elif field == 'nickname' and 'nickname' in data: sreg_data['nickname'] = data['nickname'] # construct sreg response sreg_response = sreg.SRegResponse.extractResponse(sreg_request, sreg_data) sreg_response.toMessage(response.fields) def add_openid_attribute_exchange(request, response, data): try: ax_request = ax.FetchRequest.fromOpenIDRequest(request) except ax.AXError: # not using OpenID attribute exchange extension pass else: ax_response = ax.FetchResponse() # if consumer requested attribute exchange fields, add them if ax_request and ax_request.requested_attributes: for type_uri in ax_request.requested_attributes.iterkeys(): email_schema = 'http://axschema.org/contact/email' name_schema = 'http://axschema.org/namePerson' if type_uri == email_schema and 'email' in data: ax_response.addValue(email_schema, data['email']) elif type_uri == name_schema and 'fullname' in data: ax_response.addValue(name_schema, data['fullname']) # construct ax response ax_response.toMessage(response.fields) def provider_respond(server, request, response, data): """ Respond to an OpenID request """ # get and add extensions add_openid_simple_registration(request, response, data) add_openid_attribute_exchange(request, response, data) # create http response from OpenID response webresponse = server.encodeResponse(response) http_response = HttpResponse(webresponse.body) http_response.status_code = webresponse.code # add OpenID headers to response for k, v in webresponse.headers.iteritems(): http_response[k] = v return http_response def validate_trust_root(openid_request): """ Only allow OpenID requests from valid trust roots """ trusted_roots = getattr(settings, 'OPENID_PROVIDER_TRUSTED_ROOT', None) if not trusted_roots: # not using trusted roots return True # don't allow empty trust roots if (not hasattr(openid_request, 'trust_root') or not openid_request.trust_root): log.error('no trust_root') return False # ensure trust root parses cleanly (one wildcard, of form *.foo.com, etc.) trust_root = TrustRoot.parse(openid_request.trust_root) if not trust_root: log.error('invalid trust_root') return False # don't allow empty return tos if (not hasattr(openid_request, 'return_to') or not openid_request.return_to): log.error('empty return_to') return False # ensure return to is within trust root if not trust_root.validateURL(openid_request.return_to): log.error('invalid return_to') return False # check that the root matches the ones we trust if not any(r for r in trusted_roots if fnmatch.fnmatch(trust_root, r)): log.error('non-trusted root') return False return True @csrf_exempt def provider_login(request): """ OpenID login endpoint """ # make and validate endpoint endpoint = get_xrds_url('login', request) if not endpoint: return default_render_failure(request, "Invalid OpenID request") # initialize store and server store = DjangoOpenIDStore() server = Server(store, endpoint) # first check to see if the request is an OpenID request. # If so, the client will have specified an 'openid.mode' as part # of the request. if request.method == 'GET': querydict = dict(request.GET.items()) else: querydict = dict(request.POST.items()) error = False if 'openid.mode' in request.GET or 'openid.mode' in request.POST: # decode request try: openid_request = server.decodeRequest(querydict) except (UntrustedReturnURL, ProtocolError): openid_request = None if not openid_request: return default_render_failure(request, "Invalid OpenID request") # don't allow invalid and non-trusted trust roots if not validate_trust_root(openid_request): return default_render_failure(request, "Invalid OpenID trust root") # checkid_immediate not supported, require user interaction if openid_request.mode == 'checkid_immediate': return provider_respond(server, openid_request, openid_request.answer(False), {}) # checkid_setup, so display login page # (by falling through to the provider_login at the # bottom of this method). elif openid_request.mode == 'checkid_setup': if openid_request.idSelect(): # remember request and original path request.session['openid_setup'] = { 'request': openid_request, 'url': request.get_full_path(), 'post_params': request.POST, } # user failed login on previous attempt if 'openid_error' in request.session: error = True del request.session['openid_error'] # OpenID response else: return provider_respond(server, openid_request, server.handleRequest(openid_request), {}) # handle login redirection: these are also sent to this view function, # but are distinguished by lacking the openid mode. We also know that # they are posts, because they come from the popup elif request.method == 'POST' and 'openid_setup' in request.session: # get OpenID request from session openid_setup = request.session['openid_setup'] openid_request = openid_setup['request'] openid_request_url = openid_setup['url'] post_params = openid_setup['post_params'] # We need to preserve the parameters, and the easiest way to do this is # through the URL url_post_params = { param: post_params[param] for param in post_params if param.startswith('openid') } encoded_params = urllib.urlencode(url_post_params) if '?' not in openid_request_url: openid_request_url = openid_request_url + '?' + encoded_params else: openid_request_url = openid_request_url + '&' + encoded_params del request.session['openid_setup'] # don't allow invalid trust roots if not validate_trust_root(openid_request): return default_render_failure(request, "Invalid OpenID trust root") # check if user with given email exists # Failure is redirected to this method (by using the original URL), # which will bring up the login dialog. email = request.POST.get('email', None) try: user = User.objects.get(email=email) except User.DoesNotExist: request.session['openid_error'] = True if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.warning(u"OpenID login failed - Unknown user email") else: msg = u"OpenID login failed - Unknown user email: {0}".format(email) AUDIT_LOG.warning(msg) return HttpResponseRedirect(openid_request_url) # attempt to authenticate user (but not actually log them in...) # Failure is again redirected to the login dialog. username = user.username password = request.POST.get('password', None) try: user = authenticate(username=username, password=password, request=request) except RateLimitException: AUDIT_LOG.warning(u'OpenID - Too many failed login attempts.') return HttpResponseRedirect(openid_request_url) if user is None: request.session['openid_error'] = True if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.warning(u"OpenID login failed - invalid password") else: AUDIT_LOG.warning( u"OpenID login failed - password for %s is invalid", email) return HttpResponseRedirect(openid_request_url) # authentication succeeded, so fetch user information # that was requested if user is not None and user.is_active: # remove error from session since login succeeded if 'openid_error' in request.session: del request.session['openid_error'] if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.info(u"OpenID login success - user.id: %s", user.id) else: AUDIT_LOG.info( u"OpenID login success - %s (%s)", user.username, user.email) # redirect user to return_to location url = endpoint + urlquote(user.username) response = openid_request.answer(True, None, url) # Note too that this is hardcoded, and not really responding to # the extensions that were registered in the first place. results = { 'nickname': user.username, 'email': user.email, 'fullname': user.profile.name, } # the request succeeded: return provider_respond(server, openid_request, response, results) # the account is not active, so redirect back to the login page: request.session['openid_error'] = True if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.warning( u"Login failed - Account not active for user.id %s", user.id) else: AUDIT_LOG.warning( u"Login failed - Account not active for user %s", username) return HttpResponseRedirect(openid_request_url) # determine consumer domain if applicable return_to = request.GET.get('openid.return_to') or request.POST.get('openid.return_to') or '' if return_to: matches = re.match(r'\w+:\/\/([\w\.-]+)', return_to) return_to = matches.group(1) # display login page response = render_to_response('provider_login.html', { 'error': error, 'return_to': return_to }) # add custom XRDS header necessary for discovery process response['X-XRDS-Location'] = get_xrds_url('xrds', request) return response def provider_identity(request): """ XRDS for identity discovery """ response = render_to_response('identity.xml', {'url': get_xrds_url('login', request)}, content_type='text/xml') # custom XRDS header necessary for discovery process response['X-XRDS-Location'] = get_xrds_url('identity', request) return response def provider_xrds(request): """ XRDS for endpoint discovery """ response = render_to_response('xrds.xml', {'url': get_xrds_url('login', request)}, content_type='text/xml') # custom XRDS header necessary for discovery process response['X-XRDS-Location'] = get_xrds_url('xrds', request) return response
agpl-3.0
overfl0/Bulletproof-Arma-Launcher
src/utils/popupchain.py
1
2070
# Bulletproof Arma Launcher # Copyright (C) 2016 Lukasz Taczuk # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # 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. from __future__ import unicode_literals class PopupChain(object): """A chain of ChainedPopup objects. After a ChainedPopup object has been appended to a PopupChain, try_open() has to be called to ensure the popup will be shown at some point in time. """ def __init__(self): self.chain = [] def append(self, popup): """Add the popup to the popup chain.""" popup.bind(on_dismiss=lambda instance: self.open_next()) self.chain.append(popup) def try_open(self): """Ensure the popup will be shown at some point in time. If there is no active popups, the popup will be shown now. If there are active popups, the popup will be shown as soon as previous popus will be closed. """ # If there is more than one element in the chain, it means a popup is # already active. if len(self.chain) != 1: return self.chain[0].open() def open_next(self): """Callback that shows the first pending popup from the chain.""" try: self.chain.pop(0) if len(self.chain): self.chain[0].open() except IndexError: # Sometimes Kivy will just block because of a CPU-intensive # operation. Then clicking several times on the OK button will # trigger several open_next callbacks. # I don't see any other workaround for this than just ignoring # the error :(. pass # Return True to keep the current window open
gpl-3.0
KL-WLCR/incubator-airflow
tests/contrib/operators/test_spark_submit_operator.py
6
6332
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import unittest from airflow import DAG, configuration from airflow.models import TaskInstance from airflow.contrib.operators.spark_submit_operator import SparkSubmitOperator from airflow.utils import timezone from datetime import timedelta DEFAULT_DATE = timezone.datetime(2017, 1, 1) class TestSparkSubmitOperator(unittest.TestCase): _config = { 'conf': { 'parquet.compression': 'SNAPPY' }, 'files': 'hive-site.xml', 'py_files': 'sample_library.py', 'driver_classpath': 'parquet.jar', 'jars': 'parquet.jar', 'packages': 'com.databricks:spark-avro_2.11:3.2.0', 'exclude_packages': 'org.bad.dependency:1.0.0', 'repositories': 'http://myrepo.org', 'total_executor_cores': 4, 'executor_cores': 4, 'executor_memory': '22g', 'keytab': 'privileged_user.keytab', 'principal': 'user/spark@airflow.org', 'name': '{{ task_instance.task_id }}', 'num_executors': 10, 'verbose': True, 'application': 'test_application.py', 'driver_memory': '3g', 'java_class': 'com.foo.bar.AppMain', 'application_args': [ '-f', 'foo', '--bar', 'bar', '--start', '{{ macros.ds_add(ds, -1)}}', '--end', '{{ ds }}', '--with-spaces', 'args should keep embdedded spaces', ] } def setUp(self): configuration.load_test_config() args = { 'owner': 'airflow', 'start_date': DEFAULT_DATE } self.dag = DAG('test_dag_id', default_args=args) def test_execute(self): # Given / When conn_id = 'spark_default' operator = SparkSubmitOperator( task_id='spark_submit_job', dag=self.dag, **self._config ) # Then expected_dict = { 'conf': { 'parquet.compression': 'SNAPPY' }, 'files': 'hive-site.xml', 'py_files': 'sample_library.py', 'driver_classpath': 'parquet.jar', 'jars': 'parquet.jar', 'packages': 'com.databricks:spark-avro_2.11:3.2.0', 'exclude_packages': 'org.bad.dependency:1.0.0', 'repositories': 'http://myrepo.org', 'total_executor_cores': 4, 'executor_cores': 4, 'executor_memory': '22g', 'keytab': 'privileged_user.keytab', 'principal': 'user/spark@airflow.org', 'name': '{{ task_instance.task_id }}', 'num_executors': 10, 'verbose': True, 'application': 'test_application.py', 'driver_memory': '3g', 'java_class': 'com.foo.bar.AppMain', 'application_args': [ '-f', 'foo', '--bar', 'bar', '--start', '{{ macros.ds_add(ds, -1)}}', '--end', '{{ ds }}', '--with-spaces', 'args should keep embdedded spaces', ] } self.assertEqual(conn_id, operator._conn_id) self.assertEqual(expected_dict['application'], operator._application) self.assertEqual(expected_dict['conf'], operator._conf) self.assertEqual(expected_dict['files'], operator._files) self.assertEqual(expected_dict['py_files'], operator._py_files) self.assertEqual(expected_dict['driver_classpath'], operator._driver_classpath) self.assertEqual(expected_dict['jars'], operator._jars) self.assertEqual(expected_dict['packages'], operator._packages) self.assertEqual(expected_dict['exclude_packages'], operator._exclude_packages) self.assertEqual(expected_dict['repositories'], operator._repositories) self.assertEqual(expected_dict['total_executor_cores'], operator._total_executor_cores) self.assertEqual(expected_dict['executor_cores'], operator._executor_cores) self.assertEqual(expected_dict['executor_memory'], operator._executor_memory) self.assertEqual(expected_dict['keytab'], operator._keytab) self.assertEqual(expected_dict['principal'], operator._principal) self.assertEqual(expected_dict['name'], operator._name) self.assertEqual(expected_dict['num_executors'], operator._num_executors) self.assertEqual(expected_dict['verbose'], operator._verbose) self.assertEqual(expected_dict['java_class'], operator._java_class) self.assertEqual(expected_dict['driver_memory'], operator._driver_memory) self.assertEqual(expected_dict['application_args'], operator._application_args) def test_render_template(self): # Given operator = SparkSubmitOperator(task_id='spark_submit_job', dag=self.dag, **self._config) ti = TaskInstance(operator, DEFAULT_DATE) # When ti.render_templates() # Then expected_application_args = [u'-f', 'foo', u'--bar', 'bar', u'--start', (DEFAULT_DATE - timedelta(days=1)) .strftime("%Y-%m-%d"), u'--end', DEFAULT_DATE.strftime("%Y-%m-%d"), u'--with-spaces', u'args should keep embdedded spaces', ] expected_name = "spark_submit_job" self.assertListEqual(expected_application_args, getattr(operator, '_application_args')) self.assertEqual(expected_name, getattr(operator, '_name')) if __name__ == '__main__': unittest.main()
apache-2.0
CaptainThrowback/kernel_htc_m8whl
Documentation/target/tcm_mod_builder.py
4981
41422
#!/usr/bin/python # The TCM v4 multi-protocol fabric module generation script for drivers/target/$NEW_MOD # # Copyright (c) 2010 Rising Tide Systems # Copyright (c) 2010 Linux-iSCSI.org # # Author: nab@kernel.org # import os, sys import subprocess as sub import string import re import optparse tcm_dir = "" fabric_ops = [] fabric_mod_dir = "" fabric_mod_port = "" fabric_mod_init_port = "" def tcm_mod_err(msg): print msg sys.exit(1) def tcm_mod_create_module_subdir(fabric_mod_dir_var): if os.path.isdir(fabric_mod_dir_var) == True: return 1 print "Creating fabric_mod_dir: " + fabric_mod_dir_var ret = os.mkdir(fabric_mod_dir_var) if ret: tcm_mod_err("Unable to mkdir " + fabric_mod_dir_var) return def tcm_mod_build_FC_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_nacl {\n" buf += " /* Binary World Wide unique Port Name for FC Initiator Nport */\n" buf += " u64 nport_wwpn;\n" buf += " /* ASCII formatted WWPN for FC Initiator Nport */\n" buf += " char nport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_nodeacl() */\n" buf += " struct se_node_acl se_node_acl;\n" buf += "};\n" buf += "\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* FC lport target portal group tag for TCM */\n" buf += " u16 lport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_lport */\n" buf += " struct " + fabric_mod_name + "_lport *lport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n" buf += "\n" buf += "struct " + fabric_mod_name + "_lport {\n" buf += " /* SCSI protocol the lport is providing */\n" buf += " u8 lport_proto_id;\n" buf += " /* Binary World Wide unique Port Name for FC Target Lport */\n" buf += " u64 lport_wwpn;\n" buf += " /* ASCII formatted WWPN for FC Target Lport */\n" buf += " char lport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_lport() */\n" buf += " struct se_wwn lport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "lport" fabric_mod_init_port = "nport" return def tcm_mod_build_SAS_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_nacl {\n" buf += " /* Binary World Wide unique Port Name for SAS Initiator port */\n" buf += " u64 iport_wwpn;\n" buf += " /* ASCII formatted WWPN for Sas Initiator port */\n" buf += " char iport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_nodeacl() */\n" buf += " struct se_node_acl se_node_acl;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* SAS port target portal group tag for TCM */\n" buf += " u16 tport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_tport */\n" buf += " struct " + fabric_mod_name + "_tport *tport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tport {\n" buf += " /* SCSI protocol the tport is providing */\n" buf += " u8 tport_proto_id;\n" buf += " /* Binary World Wide unique Port Name for SAS Target port */\n" buf += " u64 tport_wwpn;\n" buf += " /* ASCII formatted WWPN for SAS Target port */\n" buf += " char tport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_tport() */\n" buf += " struct se_wwn tport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "tport" fabric_mod_init_port = "iport" return def tcm_mod_build_iSCSI_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_nacl {\n" buf += " /* ASCII formatted InitiatorName */\n" buf += " char iport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_nodeacl() */\n" buf += " struct se_node_acl se_node_acl;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* iSCSI target portal group tag for TCM */\n" buf += " u16 tport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_tport */\n" buf += " struct " + fabric_mod_name + "_tport *tport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tport {\n" buf += " /* SCSI protocol the tport is providing */\n" buf += " u8 tport_proto_id;\n" buf += " /* ASCII formatted TargetName for IQN */\n" buf += " char tport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_tport() */\n" buf += " struct se_wwn tport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "tport" fabric_mod_init_port = "iport" return def tcm_mod_build_base_includes(proto_ident, fabric_mod_dir_val, fabric_mod_name): if proto_ident == "FC": tcm_mod_build_FC_include(fabric_mod_dir_val, fabric_mod_name) elif proto_ident == "SAS": tcm_mod_build_SAS_include(fabric_mod_dir_val, fabric_mod_name) elif proto_ident == "iSCSI": tcm_mod_build_iSCSI_include(fabric_mod_dir_val, fabric_mod_name) else: print "Unsupported proto_ident: " + proto_ident sys.exit(1) return def tcm_mod_build_configfs(proto_ident, fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_configfs.c" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#include <linux/module.h>\n" buf += "#include <linux/moduleparam.h>\n" buf += "#include <linux/version.h>\n" buf += "#include <generated/utsrelease.h>\n" buf += "#include <linux/utsname.h>\n" buf += "#include <linux/init.h>\n" buf += "#include <linux/slab.h>\n" buf += "#include <linux/kthread.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/string.h>\n" buf += "#include <linux/configfs.h>\n" buf += "#include <linux/ctype.h>\n" buf += "#include <asm/unaligned.h>\n\n" buf += "#include <target/target_core_base.h>\n" buf += "#include <target/target_core_fabric.h>\n" buf += "#include <target/target_core_fabric_configfs.h>\n" buf += "#include <target/target_core_configfs.h>\n" buf += "#include <target/configfs_macros.h>\n\n" buf += "#include \"" + fabric_mod_name + "_base.h\"\n" buf += "#include \"" + fabric_mod_name + "_fabric.h\"\n\n" buf += "/* Local pointer to allocated TCM configfs fabric module */\n" buf += "struct target_fabric_configfs *" + fabric_mod_name + "_fabric_configfs;\n\n" buf += "static struct se_node_acl *" + fabric_mod_name + "_make_nodeacl(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct se_node_acl *se_nacl, *se_nacl_new;\n" buf += " struct " + fabric_mod_name + "_nacl *nacl;\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " u64 wwpn = 0;\n" buf += " u32 nexus_depth;\n\n" buf += " /* " + fabric_mod_name + "_parse_wwn(name, &wwpn, 1) < 0)\n" buf += " return ERR_PTR(-EINVAL); */\n" buf += " se_nacl_new = " + fabric_mod_name + "_alloc_fabric_acl(se_tpg);\n" buf += " if (!se_nacl_new)\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += "//#warning FIXME: Hardcoded nexus depth in " + fabric_mod_name + "_make_nodeacl()\n" buf += " nexus_depth = 1;\n" buf += " /*\n" buf += " * se_nacl_new may be released by core_tpg_add_initiator_node_acl()\n" buf += " * when converting a NodeACL from demo mode -> explict\n" buf += " */\n" buf += " se_nacl = core_tpg_add_initiator_node_acl(se_tpg, se_nacl_new,\n" buf += " name, nexus_depth);\n" buf += " if (IS_ERR(se_nacl)) {\n" buf += " " + fabric_mod_name + "_release_fabric_acl(se_tpg, se_nacl_new);\n" buf += " return se_nacl;\n" buf += " }\n" buf += " /*\n" buf += " * Locate our struct " + fabric_mod_name + "_nacl and set the FC Nport WWPN\n" buf += " */\n" buf += " nacl = container_of(se_nacl, struct " + fabric_mod_name + "_nacl, se_node_acl);\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " nacl->" + fabric_mod_init_port + "_wwpn = wwpn;\n" buf += " /* " + fabric_mod_name + "_format_wwn(&nacl->" + fabric_mod_init_port + "_name[0], " + fabric_mod_name.upper() + "_NAMELEN, wwpn); */\n\n" buf += " return se_nacl;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_nodeacl(struct se_node_acl *se_acl)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_nacl *nacl = container_of(se_acl,\n" buf += " struct " + fabric_mod_name + "_nacl, se_node_acl);\n" buf += " core_tpg_del_initiator_node_acl(se_acl->se_tpg, se_acl, 1);\n" buf += " kfree(nacl);\n" buf += "}\n\n" buf += "static struct se_portal_group *" + fabric_mod_name + "_make_tpg(\n" buf += " struct se_wwn *wwn,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + "*" + fabric_mod_port + " = container_of(wwn,\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + ", " + fabric_mod_port + "_wwn);\n\n" buf += " struct " + fabric_mod_name + "_tpg *tpg;\n" buf += " unsigned long tpgt;\n" buf += " int ret;\n\n" buf += " if (strstr(name, \"tpgt_\") != name)\n" buf += " return ERR_PTR(-EINVAL);\n" buf += " if (strict_strtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)\n" buf += " return ERR_PTR(-EINVAL);\n\n" buf += " tpg = kzalloc(sizeof(struct " + fabric_mod_name + "_tpg), GFP_KERNEL);\n" buf += " if (!tpg) {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_tpg\");\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += " }\n" buf += " tpg->" + fabric_mod_port + " = " + fabric_mod_port + ";\n" buf += " tpg->" + fabric_mod_port + "_tpgt = tpgt;\n\n" buf += " ret = core_tpg_register(&" + fabric_mod_name + "_fabric_configfs->tf_ops, wwn,\n" buf += " &tpg->se_tpg, (void *)tpg,\n" buf += " TRANSPORT_TPG_TYPE_NORMAL);\n" buf += " if (ret < 0) {\n" buf += " kfree(tpg);\n" buf += " return NULL;\n" buf += " }\n" buf += " return &tpg->se_tpg;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_tpg(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n\n" buf += " core_tpg_deregister(se_tpg);\n" buf += " kfree(tpg);\n" buf += "}\n\n" buf += "static struct se_wwn *" + fabric_mod_name + "_make_" + fabric_mod_port + "(\n" buf += " struct target_fabric_configfs *tf,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + ";\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " u64 wwpn = 0;\n\n" buf += " /* if (" + fabric_mod_name + "_parse_wwn(name, &wwpn, 1) < 0)\n" buf += " return ERR_PTR(-EINVAL); */\n\n" buf += " " + fabric_mod_port + " = kzalloc(sizeof(struct " + fabric_mod_name + "_" + fabric_mod_port + "), GFP_KERNEL);\n" buf += " if (!" + fabric_mod_port + ") {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_" + fabric_mod_port + "\");\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += " }\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " " + fabric_mod_port + "->" + fabric_mod_port + "_wwpn = wwpn;\n" buf += " /* " + fabric_mod_name + "_format_wwn(&" + fabric_mod_port + "->" + fabric_mod_port + "_name[0], " + fabric_mod_name.upper() + "_NAMELEN, wwpn); */\n\n" buf += " return &" + fabric_mod_port + "->" + fabric_mod_port + "_wwn;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_" + fabric_mod_port + "(struct se_wwn *wwn)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = container_of(wwn,\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + ", " + fabric_mod_port + "_wwn);\n" buf += " kfree(" + fabric_mod_port + ");\n" buf += "}\n\n" buf += "static ssize_t " + fabric_mod_name + "_wwn_show_attr_version(\n" buf += " struct target_fabric_configfs *tf,\n" buf += " char *page)\n" buf += "{\n" buf += " return sprintf(page, \"" + fabric_mod_name.upper() + " fabric module %s on %s/%s\"\n" buf += " \"on \"UTS_RELEASE\"\\n\", " + fabric_mod_name.upper() + "_VERSION, utsname()->sysname,\n" buf += " utsname()->machine);\n" buf += "}\n\n" buf += "TF_WWN_ATTR_RO(" + fabric_mod_name + ", version);\n\n" buf += "static struct configfs_attribute *" + fabric_mod_name + "_wwn_attrs[] = {\n" buf += " &" + fabric_mod_name + "_wwn_version.attr,\n" buf += " NULL,\n" buf += "};\n\n" buf += "static struct target_core_fabric_ops " + fabric_mod_name + "_ops = {\n" buf += " .get_fabric_name = " + fabric_mod_name + "_get_fabric_name,\n" buf += " .get_fabric_proto_ident = " + fabric_mod_name + "_get_fabric_proto_ident,\n" buf += " .tpg_get_wwn = " + fabric_mod_name + "_get_fabric_wwn,\n" buf += " .tpg_get_tag = " + fabric_mod_name + "_get_tag,\n" buf += " .tpg_get_default_depth = " + fabric_mod_name + "_get_default_depth,\n" buf += " .tpg_get_pr_transport_id = " + fabric_mod_name + "_get_pr_transport_id,\n" buf += " .tpg_get_pr_transport_id_len = " + fabric_mod_name + "_get_pr_transport_id_len,\n" buf += " .tpg_parse_pr_out_transport_id = " + fabric_mod_name + "_parse_pr_out_transport_id,\n" buf += " .tpg_check_demo_mode = " + fabric_mod_name + "_check_false,\n" buf += " .tpg_check_demo_mode_cache = " + fabric_mod_name + "_check_true,\n" buf += " .tpg_check_demo_mode_write_protect = " + fabric_mod_name + "_check_true,\n" buf += " .tpg_check_prod_mode_write_protect = " + fabric_mod_name + "_check_false,\n" buf += " .tpg_alloc_fabric_acl = " + fabric_mod_name + "_alloc_fabric_acl,\n" buf += " .tpg_release_fabric_acl = " + fabric_mod_name + "_release_fabric_acl,\n" buf += " .tpg_get_inst_index = " + fabric_mod_name + "_tpg_get_inst_index,\n" buf += " .release_cmd = " + fabric_mod_name + "_release_cmd,\n" buf += " .shutdown_session = " + fabric_mod_name + "_shutdown_session,\n" buf += " .close_session = " + fabric_mod_name + "_close_session,\n" buf += " .stop_session = " + fabric_mod_name + "_stop_session,\n" buf += " .fall_back_to_erl0 = " + fabric_mod_name + "_reset_nexus,\n" buf += " .sess_logged_in = " + fabric_mod_name + "_sess_logged_in,\n" buf += " .sess_get_index = " + fabric_mod_name + "_sess_get_index,\n" buf += " .sess_get_initiator_sid = NULL,\n" buf += " .write_pending = " + fabric_mod_name + "_write_pending,\n" buf += " .write_pending_status = " + fabric_mod_name + "_write_pending_status,\n" buf += " .set_default_node_attributes = " + fabric_mod_name + "_set_default_node_attrs,\n" buf += " .get_task_tag = " + fabric_mod_name + "_get_task_tag,\n" buf += " .get_cmd_state = " + fabric_mod_name + "_get_cmd_state,\n" buf += " .queue_data_in = " + fabric_mod_name + "_queue_data_in,\n" buf += " .queue_status = " + fabric_mod_name + "_queue_status,\n" buf += " .queue_tm_rsp = " + fabric_mod_name + "_queue_tm_rsp,\n" buf += " .get_fabric_sense_len = " + fabric_mod_name + "_get_fabric_sense_len,\n" buf += " .set_fabric_sense_len = " + fabric_mod_name + "_set_fabric_sense_len,\n" buf += " .is_state_remove = " + fabric_mod_name + "_is_state_remove,\n" buf += " /*\n" buf += " * Setup function pointers for generic logic in target_core_fabric_configfs.c\n" buf += " */\n" buf += " .fabric_make_wwn = " + fabric_mod_name + "_make_" + fabric_mod_port + ",\n" buf += " .fabric_drop_wwn = " + fabric_mod_name + "_drop_" + fabric_mod_port + ",\n" buf += " .fabric_make_tpg = " + fabric_mod_name + "_make_tpg,\n" buf += " .fabric_drop_tpg = " + fabric_mod_name + "_drop_tpg,\n" buf += " .fabric_post_link = NULL,\n" buf += " .fabric_pre_unlink = NULL,\n" buf += " .fabric_make_np = NULL,\n" buf += " .fabric_drop_np = NULL,\n" buf += " .fabric_make_nodeacl = " + fabric_mod_name + "_make_nodeacl,\n" buf += " .fabric_drop_nodeacl = " + fabric_mod_name + "_drop_nodeacl,\n" buf += "};\n\n" buf += "static int " + fabric_mod_name + "_register_configfs(void)\n" buf += "{\n" buf += " struct target_fabric_configfs *fabric;\n" buf += " int ret;\n\n" buf += " printk(KERN_INFO \"" + fabric_mod_name.upper() + " fabric module %s on %s/%s\"\n" buf += " \" on \"UTS_RELEASE\"\\n\"," + fabric_mod_name.upper() + "_VERSION, utsname()->sysname,\n" buf += " utsname()->machine);\n" buf += " /*\n" buf += " * Register the top level struct config_item_type with TCM core\n" buf += " */\n" buf += " fabric = target_fabric_configfs_init(THIS_MODULE, \"" + fabric_mod_name[4:] + "\");\n" buf += " if (IS_ERR(fabric)) {\n" buf += " printk(KERN_ERR \"target_fabric_configfs_init() failed\\n\");\n" buf += " return PTR_ERR(fabric);\n" buf += " }\n" buf += " /*\n" buf += " * Setup fabric->tf_ops from our local " + fabric_mod_name + "_ops\n" buf += " */\n" buf += " fabric->tf_ops = " + fabric_mod_name + "_ops;\n" buf += " /*\n" buf += " * Setup default attribute lists for various fabric->tf_cit_tmpl\n" buf += " */\n" buf += " TF_CIT_TMPL(fabric)->tfc_wwn_cit.ct_attrs = " + fabric_mod_name + "_wwn_attrs;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_base_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_attrib_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_param_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_np_base_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_base_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_attrib_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_auth_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_param_cit.ct_attrs = NULL;\n" buf += " /*\n" buf += " * Register the fabric for use within TCM\n" buf += " */\n" buf += " ret = target_fabric_configfs_register(fabric);\n" buf += " if (ret < 0) {\n" buf += " printk(KERN_ERR \"target_fabric_configfs_register() failed\"\n" buf += " \" for " + fabric_mod_name.upper() + "\\n\");\n" buf += " return ret;\n" buf += " }\n" buf += " /*\n" buf += " * Setup our local pointer to *fabric\n" buf += " */\n" buf += " " + fabric_mod_name + "_fabric_configfs = fabric;\n" buf += " printk(KERN_INFO \"" + fabric_mod_name.upper() + "[0] - Set fabric -> " + fabric_mod_name + "_fabric_configfs\\n\");\n" buf += " return 0;\n" buf += "};\n\n" buf += "static void __exit " + fabric_mod_name + "_deregister_configfs(void)\n" buf += "{\n" buf += " if (!" + fabric_mod_name + "_fabric_configfs)\n" buf += " return;\n\n" buf += " target_fabric_configfs_deregister(" + fabric_mod_name + "_fabric_configfs);\n" buf += " " + fabric_mod_name + "_fabric_configfs = NULL;\n" buf += " printk(KERN_INFO \"" + fabric_mod_name.upper() + "[0] - Cleared " + fabric_mod_name + "_fabric_configfs\\n\");\n" buf += "};\n\n" buf += "static int __init " + fabric_mod_name + "_init(void)\n" buf += "{\n" buf += " int ret;\n\n" buf += " ret = " + fabric_mod_name + "_register_configfs();\n" buf += " if (ret < 0)\n" buf += " return ret;\n\n" buf += " return 0;\n" buf += "};\n\n" buf += "static void __exit " + fabric_mod_name + "_exit(void)\n" buf += "{\n" buf += " " + fabric_mod_name + "_deregister_configfs();\n" buf += "};\n\n" buf += "MODULE_DESCRIPTION(\"" + fabric_mod_name.upper() + " series fabric driver\");\n" buf += "MODULE_LICENSE(\"GPL\");\n" buf += "module_init(" + fabric_mod_name + "_init);\n" buf += "module_exit(" + fabric_mod_name + "_exit);\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_scan_fabric_ops(tcm_dir): fabric_ops_api = tcm_dir + "include/target/target_core_fabric.h" print "Using tcm_mod_scan_fabric_ops: " + fabric_ops_api process_fo = 0; p = open(fabric_ops_api, 'r') line = p.readline() while line: if process_fo == 0 and re.search('struct target_core_fabric_ops {', line): line = p.readline() continue if process_fo == 0: process_fo = 1; line = p.readline() # Search for function pointer if not re.search('\(\*', line): continue fabric_ops.append(line.rstrip()) continue line = p.readline() # Search for function pointer if not re.search('\(\*', line): continue fabric_ops.append(line.rstrip()) p.close() return def tcm_mod_dump_fabric_ops(proto_ident, fabric_mod_dir_var, fabric_mod_name): buf = "" bufi = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_fabric.c" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) fi = fabric_mod_dir_var + "/" + fabric_mod_name + "_fabric.h" print "Writing file: " + fi pi = open(fi, 'w') if not pi: tcm_mod_err("Unable to open file: " + fi) buf = "#include <linux/slab.h>\n" buf += "#include <linux/kthread.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/list.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/string.h>\n" buf += "#include <linux/ctype.h>\n" buf += "#include <asm/unaligned.h>\n" buf += "#include <scsi/scsi.h>\n" buf += "#include <scsi/scsi_host.h>\n" buf += "#include <scsi/scsi_device.h>\n" buf += "#include <scsi/scsi_cmnd.h>\n" buf += "#include <scsi/libfc.h>\n\n" buf += "#include <target/target_core_base.h>\n" buf += "#include <target/target_core_fabric.h>\n" buf += "#include <target/target_core_configfs.h>\n\n" buf += "#include \"" + fabric_mod_name + "_base.h\"\n" buf += "#include \"" + fabric_mod_name + "_fabric.h\"\n\n" buf += "int " + fabric_mod_name + "_check_true(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_check_true(struct se_portal_group *);\n" buf += "int " + fabric_mod_name + "_check_false(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_check_false(struct se_portal_group *);\n" total_fabric_ops = len(fabric_ops) i = 0 while i < total_fabric_ops: fo = fabric_ops[i] i += 1 # print "fabric_ops: " + fo if re.search('get_fabric_name', fo): buf += "char *" + fabric_mod_name + "_get_fabric_name(void)\n" buf += "{\n" buf += " return \"" + fabric_mod_name[4:] + "\";\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_get_fabric_name(void);\n" continue if re.search('get_fabric_proto_ident', fo): buf += "u8 " + fabric_mod_name + "_get_fabric_proto_ident(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " u8 proto_id;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " proto_id = fc_get_fabric_proto_ident(se_tpg);\n" buf += " break;\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " proto_id = sas_get_fabric_proto_ident(se_tpg);\n" buf += " break;\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " proto_id = iscsi_get_fabric_proto_ident(se_tpg);\n" buf += " break;\n" buf += " }\n\n" buf += " return proto_id;\n" buf += "}\n\n" bufi += "u8 " + fabric_mod_name + "_get_fabric_proto_ident(struct se_portal_group *);\n" if re.search('get_wwn', fo): buf += "char *" + fabric_mod_name + "_get_fabric_wwn(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n\n" buf += " return &" + fabric_mod_port + "->" + fabric_mod_port + "_name[0];\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_get_fabric_wwn(struct se_portal_group *);\n" if re.search('get_tag', fo): buf += "u16 " + fabric_mod_name + "_get_tag(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " return tpg->" + fabric_mod_port + "_tpgt;\n" buf += "}\n\n" bufi += "u16 " + fabric_mod_name + "_get_tag(struct se_portal_group *);\n" if re.search('get_default_depth', fo): buf += "u32 " + fabric_mod_name + "_get_default_depth(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_default_depth(struct se_portal_group *);\n" if re.search('get_pr_transport_id\)\(', fo): buf += "u32 " + fabric_mod_name + "_get_pr_transport_id(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct se_node_acl *se_nacl,\n" buf += " struct t10_pr_registration *pr_reg,\n" buf += " int *format_code,\n" buf += " unsigned char *buf)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " int ret = 0;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " ret = fc_get_pr_transport_id(se_tpg, se_nacl, pr_reg,\n" buf += " format_code, buf);\n" buf += " break;\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " ret = sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,\n" buf += " format_code, buf);\n" buf += " break;\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " ret = iscsi_get_pr_transport_id(se_tpg, se_nacl, pr_reg,\n" buf += " format_code, buf);\n" buf += " break;\n" buf += " }\n\n" buf += " return ret;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_pr_transport_id(struct se_portal_group *,\n" bufi += " struct se_node_acl *, struct t10_pr_registration *,\n" bufi += " int *, unsigned char *);\n" if re.search('get_pr_transport_id_len\)\(', fo): buf += "u32 " + fabric_mod_name + "_get_pr_transport_id_len(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct se_node_acl *se_nacl,\n" buf += " struct t10_pr_registration *pr_reg,\n" buf += " int *format_code)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " int ret = 0;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " ret = fc_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,\n" buf += " format_code);\n" buf += " break;\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " ret = sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,\n" buf += " format_code);\n" buf += " break;\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " ret = iscsi_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,\n" buf += " format_code);\n" buf += " break;\n" buf += " }\n\n" buf += " return ret;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_pr_transport_id_len(struct se_portal_group *,\n" bufi += " struct se_node_acl *, struct t10_pr_registration *,\n" bufi += " int *);\n" if re.search('parse_pr_out_transport_id\)\(', fo): buf += "char *" + fabric_mod_name + "_parse_pr_out_transport_id(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " const char *buf,\n" buf += " u32 *out_tid_len,\n" buf += " char **port_nexus_ptr)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " char *tid = NULL;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " tid = fc_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,\n" buf += " port_nexus_ptr);\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " tid = sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,\n" buf += " port_nexus_ptr);\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " tid = iscsi_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,\n" buf += " port_nexus_ptr);\n" buf += " }\n\n" buf += " return tid;\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_parse_pr_out_transport_id(struct se_portal_group *,\n" bufi += " const char *, u32 *, char **);\n" if re.search('alloc_fabric_acl\)\(', fo): buf += "struct se_node_acl *" + fabric_mod_name + "_alloc_fabric_acl(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_nacl *nacl;\n\n" buf += " nacl = kzalloc(sizeof(struct " + fabric_mod_name + "_nacl), GFP_KERNEL);\n" buf += " if (!nacl) {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_nacl\\n\");\n" buf += " return NULL;\n" buf += " }\n\n" buf += " return &nacl->se_node_acl;\n" buf += "}\n\n" bufi += "struct se_node_acl *" + fabric_mod_name + "_alloc_fabric_acl(struct se_portal_group *);\n" if re.search('release_fabric_acl\)\(', fo): buf += "void " + fabric_mod_name + "_release_fabric_acl(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct se_node_acl *se_nacl)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_nacl *nacl = container_of(se_nacl,\n" buf += " struct " + fabric_mod_name + "_nacl, se_node_acl);\n" buf += " kfree(nacl);\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_release_fabric_acl(struct se_portal_group *,\n" bufi += " struct se_node_acl *);\n" if re.search('tpg_get_inst_index\)\(', fo): buf += "u32 " + fabric_mod_name + "_tpg_get_inst_index(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_tpg_get_inst_index(struct se_portal_group *);\n" if re.search('\*release_cmd\)\(', fo): buf += "void " + fabric_mod_name + "_release_cmd(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_release_cmd(struct se_cmd *);\n" if re.search('shutdown_session\)\(', fo): buf += "int " + fabric_mod_name + "_shutdown_session(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_shutdown_session(struct se_session *);\n" if re.search('close_session\)\(', fo): buf += "void " + fabric_mod_name + "_close_session(struct se_session *se_sess)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_close_session(struct se_session *);\n" if re.search('stop_session\)\(', fo): buf += "void " + fabric_mod_name + "_stop_session(struct se_session *se_sess, int sess_sleep , int conn_sleep)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_stop_session(struct se_session *, int, int);\n" if re.search('fall_back_to_erl0\)\(', fo): buf += "void " + fabric_mod_name + "_reset_nexus(struct se_session *se_sess)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_reset_nexus(struct se_session *);\n" if re.search('sess_logged_in\)\(', fo): buf += "int " + fabric_mod_name + "_sess_logged_in(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_sess_logged_in(struct se_session *);\n" if re.search('sess_get_index\)\(', fo): buf += "u32 " + fabric_mod_name + "_sess_get_index(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_sess_get_index(struct se_session *);\n" if re.search('write_pending\)\(', fo): buf += "int " + fabric_mod_name + "_write_pending(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_write_pending(struct se_cmd *);\n" if re.search('write_pending_status\)\(', fo): buf += "int " + fabric_mod_name + "_write_pending_status(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_write_pending_status(struct se_cmd *);\n" if re.search('set_default_node_attributes\)\(', fo): buf += "void " + fabric_mod_name + "_set_default_node_attrs(struct se_node_acl *nacl)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_set_default_node_attrs(struct se_node_acl *);\n" if re.search('get_task_tag\)\(', fo): buf += "u32 " + fabric_mod_name + "_get_task_tag(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_task_tag(struct se_cmd *);\n" if re.search('get_cmd_state\)\(', fo): buf += "int " + fabric_mod_name + "_get_cmd_state(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_get_cmd_state(struct se_cmd *);\n" if re.search('queue_data_in\)\(', fo): buf += "int " + fabric_mod_name + "_queue_data_in(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_data_in(struct se_cmd *);\n" if re.search('queue_status\)\(', fo): buf += "int " + fabric_mod_name + "_queue_status(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_status(struct se_cmd *);\n" if re.search('queue_tm_rsp\)\(', fo): buf += "int " + fabric_mod_name + "_queue_tm_rsp(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_tm_rsp(struct se_cmd *);\n" if re.search('get_fabric_sense_len\)\(', fo): buf += "u16 " + fabric_mod_name + "_get_fabric_sense_len(void)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u16 " + fabric_mod_name + "_get_fabric_sense_len(void);\n" if re.search('set_fabric_sense_len\)\(', fo): buf += "u16 " + fabric_mod_name + "_set_fabric_sense_len(struct se_cmd *se_cmd, u32 sense_length)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u16 " + fabric_mod_name + "_set_fabric_sense_len(struct se_cmd *, u32);\n" if re.search('is_state_remove\)\(', fo): buf += "int " + fabric_mod_name + "_is_state_remove(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_is_state_remove(struct se_cmd *);\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() ret = pi.write(bufi) if ret: tcm_mod_err("Unable to write fi: " + fi) pi.close() return def tcm_mod_build_kbuild(fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/Makefile" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) buf += fabric_mod_name + "-objs := " + fabric_mod_name + "_fabric.o \\\n" buf += " " + fabric_mod_name + "_configfs.o\n" buf += "obj-$(CONFIG_" + fabric_mod_name.upper() + ") += " + fabric_mod_name + ".o\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_build_kconfig(fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/Kconfig" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) buf = "config " + fabric_mod_name.upper() + "\n" buf += " tristate \"" + fabric_mod_name.upper() + " fabric module\"\n" buf += " depends on TARGET_CORE && CONFIGFS_FS\n" buf += " default n\n" buf += " ---help---\n" buf += " Say Y here to enable the " + fabric_mod_name.upper() + " fabric module\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_add_kbuild(tcm_dir, fabric_mod_name): buf = "obj-$(CONFIG_" + fabric_mod_name.upper() + ") += " + fabric_mod_name.lower() + "/\n" kbuild = tcm_dir + "/drivers/target/Makefile" f = open(kbuild, 'a') f.write(buf) f.close() return def tcm_mod_add_kconfig(tcm_dir, fabric_mod_name): buf = "source \"drivers/target/" + fabric_mod_name.lower() + "/Kconfig\"\n" kconfig = tcm_dir + "/drivers/target/Kconfig" f = open(kconfig, 'a') f.write(buf) f.close() return def main(modname, proto_ident): # proto_ident = "FC" # proto_ident = "SAS" # proto_ident = "iSCSI" tcm_dir = os.getcwd(); tcm_dir += "/../../" print "tcm_dir: " + tcm_dir fabric_mod_name = modname fabric_mod_dir = tcm_dir + "drivers/target/" + fabric_mod_name print "Set fabric_mod_name: " + fabric_mod_name print "Set fabric_mod_dir: " + fabric_mod_dir print "Using proto_ident: " + proto_ident if proto_ident != "FC" and proto_ident != "SAS" and proto_ident != "iSCSI": print "Unsupported proto_ident: " + proto_ident sys.exit(1) ret = tcm_mod_create_module_subdir(fabric_mod_dir) if ret: print "tcm_mod_create_module_subdir() failed because module already exists!" sys.exit(1) tcm_mod_build_base_includes(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_scan_fabric_ops(tcm_dir) tcm_mod_dump_fabric_ops(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_build_configfs(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_build_kbuild(fabric_mod_dir, fabric_mod_name) tcm_mod_build_kconfig(fabric_mod_dir, fabric_mod_name) input = raw_input("Would you like to add " + fabric_mod_name + "to drivers/target/Makefile..? [yes,no]: ") if input == "yes" or input == "y": tcm_mod_add_kbuild(tcm_dir, fabric_mod_name) input = raw_input("Would you like to add " + fabric_mod_name + "to drivers/target/Kconfig..? [yes,no]: ") if input == "yes" or input == "y": tcm_mod_add_kconfig(tcm_dir, fabric_mod_name) return parser = optparse.OptionParser() parser.add_option('-m', '--modulename', help='Module name', dest='modname', action='store', nargs=1, type='string') parser.add_option('-p', '--protoident', help='Protocol Ident', dest='protoident', action='store', nargs=1, type='string') (opts, args) = parser.parse_args() mandatories = ['modname', 'protoident'] for m in mandatories: if not opts.__dict__[m]: print "mandatory option is missing\n" parser.print_help() exit(-1) if __name__ == "__main__": main(str(opts.modname), opts.protoident)
gpl-2.0
ivanhorvath/openshift-tools
ansible/roles/lib_aos_modules/library/aos_rhsm_repos.py
13
6664
#!/usr/bin/python """ansible module for rhsm repo management""" # -*- coding: utf-8 -*- # vim: expandtab:tabstop=4:shiftwidth=4 DOCUMENTATION = ''' --- module: aos_rhsm_repos short_description: this module manages rhsm repositories description: - this module manages rhsm repositories options: enabled: description: - list of repo ids to enable. supports *. required: false default: none aliases: [] disabled: description: - list of repo ids to disable. supports *. required: false default: none aliases: [] state: choices: ['list', 'present'] description: - whether to list or set the repositories. required: false default: present aliases: [] query: choices: ['all', 'enabled', 'disabled'] description: - The query type when looking at repositories. required: false default: all aliases: [] ''' EXAMPLES = ''' # perform a list on the enabled repos - aos_rhsm_repos: state: list query: enabled register: repos # Set repositories 2 repositories and disable the others. - aos_rhsm_repos: state: present enabled: - rhel-7-server-rpms - rhel-7-server-extras-rpms disabled: - '*' ''' import re RHSM_BIN = '/usr/sbin/subscription-manager' class RHSMError(Exception): """rhsm error""" pass class RHSMRepos(object): """simple wrapper class for rhsm repos""" def __init__(self, module): self.module = module self.enabled = module.params['enabled'] self.disabled = module.params['disabled'] def set_repositories(self): """set the enabled and disabled repositories""" cmd = [RHSM_BIN, 'repos'] if self.disabled: cmd.extend(['--disable=%s' % dis for dis in self.disabled]) # enabled must come last as disable will undo the enabled. if self.enabled: cmd.extend(['--enable=%s' % ena for ena in self.enabled]) rcode, out, err = self.module.run_command(cmd) if rcode != 0: self.module.fail_json(rc=rcode, cmd=cmd, msg=err) return rcode, out, err @staticmethod def parse_repos(rinput): """parse the repo output""" all_repos = [] # split rinput on double new lines repos = re.split('\n\n', rinput) for idx, repo in enumerate(repos): repo.strip() if not repo: continue repo = repo.split('\n') # remove the first 3 lines if idx == 0: repo = repo[3:] if len(repo) != 4: raise RHSMError('error parsing repositories. repo=%s' % repo) all_repos.append({'id': repo[0].split('ID:')[1].strip(), 'name': repo[1].split('Name:')[1].strip(), 'url': repo[2].split('URL:')[1].strip(), 'enabled': int(repo[3].split('Enabled:')[1].strip()) == 1 }) return all_repos def query_repos(self, qtype='list'): """query for repos""" cmd = [RHSM_BIN, 'repos'] if qtype == 'enabled': cmd.append('--list-enabled') elif qtype == 'disabled': cmd.append('--list-disabled') else: cmd.append('--list') rcode, out, err = self.module.run_command(cmd) if rcode != 0: self.module.fail_json(rc=rcode, cmd=cmd, msg='Error querying repositories: [%s]' % err) if 'no available repositories matching' in out: return [] try: return RHSMRepos.parse_repos(out) except RHSMError as err: self.module.fail_json(msg=err, rc=1) def needs_update(self): """verify that the enabled repos are enabled""" repos = self.query_repos(qtype='enabled') # build sets of the repo ids and compare them rids = set([rep['id'] for rep in repos]) ren = set(self.enabled) diff = rids - ren if diff or ren - rids: return True, diff return False, repos def check_identity(self): """verify that this system is entitled""" rcode, _, _ = self.module.run_command([RHSM_BIN, 'identity']) if rcode != 0: self.module.fail_json(msg="command `subscription-manager identity` failed. exit code non zero.", rc=1) @staticmethod def run_ansible(module): """run the ansible code""" rhsm = RHSMRepos(module) # Step 1: verify we are entitled rhsm.check_identity() # Step 2: if we are state=list, query and return results if rhsm.module.params['state'] == 'list': repos = rhsm.query_repos(qtype=module.params['query']) rhsm.module.exit_json(changed=False, repos=repos, rc=0) # Step 2: if we are state=present, check if we need to update elif module.params['state'] == 'present': update, repos = rhsm.needs_update() # No updates needed if update == False: module.exit_json(changed=False, repos=repos, rc=0) # Exit if check mode before we make changes if module.check_mode: module.exit_json(changed=True, repos=repos, rc=0) # Step 3: we need to set our repositories rcode, out, err = rhsm.set_repositories() # Query the enabled repositories and verify our changes are set. update, repos = rhsm.needs_update() # Everything went ok, return the enabled repositories if not update: module.exit_json(changed=True, repos=repos, rc=0) # An error occured while calling set_repositories module.fail_json(msg="rhsm repo command failed. Changes not applied.", rc=rcode, stdout=out, stderr=err) module.fail_json(msg="unsupported state.", rc=1) def main(): """Create the ansible module and run the ansible code""" module = AnsibleModule( argument_spec=dict( enabled=dict(default=None, type='list'), disabled=dict(default=None, type='list'), state=dict(default='present', choices=['list', 'present']), query=dict(default='all', choices=['all', 'enabled', 'disabled']), ), supports_check_mode=True ) # call the ansible function RHSMRepos.run_ansible(module) if __name__ == '__main__': # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import # import module snippets from ansible.module_utils.basic import * main()
apache-2.0
asm666/sympy
sympy/physics/quantum/dagger.py
116
2242
"""Hermitian conjugation.""" from __future__ import print_function, division from sympy.core import Expr from sympy.functions.elementary.complexes import adjoint __all__ = [ 'Dagger' ] class Dagger(adjoint): """General Hermitian conjugate operation. Take the Hermetian conjugate of an argument [1]_. For matrices this operation is equivalent to transpose and complex conjugate [2]_. Parameters ========== arg : Expr The sympy expression that we want to take the dagger of. Examples ======== Daggering various quantum objects: >>> from sympy.physics.quantum.dagger import Dagger >>> from sympy.physics.quantum.state import Ket, Bra >>> from sympy.physics.quantum.operator import Operator >>> Dagger(Ket('psi')) <psi| >>> Dagger(Bra('phi')) |phi> >>> Dagger(Operator('A')) Dagger(A) Inner and outer products:: >>> from sympy.physics.quantum import InnerProduct, OuterProduct >>> Dagger(InnerProduct(Bra('a'), Ket('b'))) <b|a> >>> Dagger(OuterProduct(Ket('a'), Bra('b'))) |b><a| Powers, sums and products:: >>> A = Operator('A') >>> B = Operator('B') >>> Dagger(A*B) Dagger(B)*Dagger(A) >>> Dagger(A+B) Dagger(A) + Dagger(B) >>> Dagger(A**2) Dagger(A)**2 Dagger also seamlessly handles complex numbers and matrices:: >>> from sympy import Matrix, I >>> m = Matrix([[1,I],[2,I]]) >>> m Matrix([ [1, I], [2, I]]) >>> Dagger(m) Matrix([ [ 1, 2], [-I, -I]]) References ========== .. [1] http://en.wikipedia.org/wiki/Hermitian_adjoint .. [2] http://en.wikipedia.org/wiki/Hermitian_transpose """ def __new__(cls, arg): if hasattr(arg, 'adjoint'): obj = arg.adjoint() elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose'): obj = arg.conjugate().transpose() if obj is not None: return obj return Expr.__new__(cls, arg) adjoint.__name__ = "Dagger" adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
bsd-3-clause
FrankBian/kuma
vendor/packages/ipython/IPython/Extensions/ipy_which.py
8
1973
r""" %which magic command %which <cmd> => search PATH for files matching PATH. Also scans aliases """ import IPython.ipapi ip = IPython.ipapi.get() import os,sys from fnmatch import fnmatch def which(fname): fullpath = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) if '.' not in fullpath: fullpath = ['.'] + fullpath fn = fname for p in fullpath: for f in os.listdir(p): head, ext = os.path.splitext(f) if f == fn or fnmatch(head, fn): yield os.path.join(p,f) return def which_alias(fname): for al, tgt in ip.IP.alias_table.items(): if not (al == fname or fnmatch(al, fname)): continue if callable(tgt): print "Callable alias",tgt d = tgt.__doc__ if d: print "Docstring:\n",d continue trg = tgt[1] trans = ip.expand_alias(trg) cmd = trans.split(None,1)[0] print al,"->",trans for realcmd in which(cmd): print " ==",realcmd def which_f(self, arg): r""" %which <cmd> => search PATH for files matching cmd. Also scans aliases. Traverses PATH and prints all files (not just executables!) that match the pattern on command line. Probably more useful in finding stuff interactively than 'which', which only prints the first matching item. Also discovers and expands aliases, so you'll see what will be executed when you call an alias. Example: [~]|62> %which d d -> ls -F --color=auto == c:\cygwin\bin\ls.exe c:\cygwin\bin\d.exe [~]|64> %which diff* diff3 -> diff3 == c:\cygwin\bin\diff3.exe diff -> diff == c:\cygwin\bin\diff.exe c:\cygwin\bin\diff.exe c:\cygwin\bin\diff3.exe """ which_alias(arg) for e in which(arg): print e ip.expose_magic("which",which_f)
mpl-2.0
elffersj/cnfgen
cnfformula/families/graphisomorphism.py
1
4562
#!/usr/bin/env python # -*- coding:utf-8 -*- """Graph isomorphimsm/automorphism formulas """ from cnfformula.cnf import CNF from cnfformula.cmdline import SimpleGraphHelper from cnfformula.cmdline import register_cnfgen_subcommand from cnfformula.families import register_cnf_generator from cnfformula.graphs import enumerate_vertices from itertools import combinations,product def _graph_isomorphism_var(u, v): """Standard variable name""" return "x_{{{0},{1}}}".format(u, v) @register_cnf_generator def GraphIsomorphism(G1, G2): """Graph Isomorphism formula The formula is the CNF encoding of the statement that two simple graphs G1 and G2 are isomorphic. Parameters ---------- G1 : networkx.Graph an undirected graph object G2 : networkx.Graph an undirected graph object Returns ------- A CNF formula which is satiafiable if and only if graphs G1 and G2 are isomorphic. """ F = CNF() F.header = "Graph Isomorphism problem between graphs " +\ G1.name + " and " + G2.name + "\n" + F.header U=enumerate_vertices(G1) V=enumerate_vertices(G2) var = _graph_isomorphism_var for (u, v) in product(U,V): F.add_variable(var(u, v)) # Defined on both side for u in U: F.add_clause([(True, var(u, v)) for v in V], strict=True) for v in V: F.add_clause([(True, var(u, v)) for u in U], strict=True) # Injective on both sides for u in U: for v1, v2 in combinations(V, 2): F.add_clause([(False, var(u, v1)), (False, var(u, v2))], strict=True) for v in V: for u1, u2 in combinations(U, 2): F.add_clause([(False, var(u1, v)), (False, var(u2, v))], strict=True) # Edge consistency for u1, u2 in combinations(U, 2): for v1, v2 in combinations(V, 2): if G1.has_edge(u1, u2) != G2.has_edge(v1, v2): F.add_clause([(False, var(u1, v1)), (False, var(u2, v2))], strict=True) F.add_clause([(False, var(u1, v2)), (False, var(u2, v1))], strict=True) return F @register_cnf_generator def GraphAutomorphism(G): """Graph Automorphism formula The formula is the CNF encoding of the statement that a graph G has a nontrivial automorphism, i.e. an automorphism different from the idential one. Parameter --------- G : a simple graph Returns ------- A CNF formula which is satiafiable if and only if graph G has a nontrivial automorphism. """ tmp = CNF() header = "Graph automorphism formula for graph "+ G.name +"\n"+ tmp.header F = GraphIsomorphism(G, G) F.header = header var = _graph_isomorphism_var F.add_clause([(False, var(u, u)) for u in enumerate_vertices(G)], strict=True) return F @register_cnfgen_subcommand class GAutoCmdHelper(object): """Command line helper for Graph Automorphism formula """ name='gauto' description='graph automorphism formula' @staticmethod def setup_command_line(parser): """Setup the command line options for graph automorphism formula Arguments: - `parser`: parser to load with options. """ SimpleGraphHelper.setup_command_line(parser) @staticmethod def build_cnf(args): """Build a graph automorphism formula according to the arguments Arguments: - `args`: command line options """ G = SimpleGraphHelper.obtain_graph(args) return GraphAutomorphism(G) @register_cnfgen_subcommand class GIsoCmdHelper(object): """Command line helper for Graph Isomorphism formula """ name='giso' description='graph isomorphism formula' @staticmethod def setup_command_line(parser): """Setup the command line options for graph isomorphism formula Arguments: - `parser`: parser to load with options. """ SimpleGraphHelper.setup_command_line(parser,suffix="1",required=True) SimpleGraphHelper.setup_command_line(parser,suffix="2",required=True) @staticmethod def build_cnf(args): """Build a graph automorphism formula according to the arguments Arguments: - `args`: command line options """ G1 = SimpleGraphHelper.obtain_graph(args,suffix="1") G2 = SimpleGraphHelper.obtain_graph(args,suffix="2") return GraphIsomorphism(G1,G2)
gpl-3.0
lmb/Supermega
supermega/tests/test_session.py
1
2433
import unittest import hashlib import os import random from StringIO import StringIO from .. import Session, User, File, Directory from .. import errors USERNAME = os.environ.get('MEGA_USERNAME', None) PASSWORD = os.environ.get('MEGA_PASSWORD', None) def random_string(length): return (('%0'+str(length)+'x') % random.randrange(256**(length/2)))[:length] def calculate_hash(string): hash = hashlib.sha256() hash.update(string) return hash.hexdigest() def verify_hash(file, chunks, obj, sha256): hash = hashlib.sha256() for chunk in chunks: hash.update(chunk) obj.assertEqual(hash.hexdigest(), sha256) requires_account = unittest.skipUnless(USERNAME and PASSWORD, "MEGA_USERNAME or MEGA_PASSWORD missing") class TestSession(unittest.TestCase): def setUp(self): self.sess = Session() def test_public_file_download(self): url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E' sha256 = '9431103cb989f2913cbc503767015ca22c0ae40942932186c59ffe6d6a69830d' self.sess.download(verify_hash, url, self, sha256) def test_ephemeral_account(self): sess = Session.ephemeral() sess.root # This triggers lazy-loading the datastore def test_key_derivation(self): self.assertEqual(User.derive_key("password"), 'd\x039r^n\xbd\x13\xa2_\x00R\x12\x9f|\xb1') @requires_account def test_create_from_env(self): s = Session.from_env() @requires_account def test_print_tree(self): sess = Session(USERNAME, PASSWORD) sess.root.print_tree() class TestFile(unittest.TestCase): def setUp(self): self.sess = Session(USERNAME, PASSWORD) self.random_filename = random_string(5) def tearDown(self): try: f = self.sess.root[self.random_filename] f.delete() except KeyError, errors.ObjectNotFound: pass @requires_account def test_file_upload_download(self): length = random.randint(120, 400) * 0x400 contents = chr(random.randint(0,256)) * length sha256 = calculate_hash(contents) fileobj = StringIO(contents) uploaded_file = File.upload(self.sess.root, fileobj, name=self.random_filename, size=length) uploaded_file.download(verify_hash, self, sha256) class TestDirectory(unittest.TestCase): def setUp(self): self.sess = Session(USERNAME, PASSWORD) @requires_account def test_create(self): root = self.sess.root d = None try: random_dir = random_string(5) d = Directory.create(random_dir, root) finally: if d: d.delete()
bsd-3-clause
rhertzog/django
tests/indexes/models.py
7
1816
from django.db import connection, models class CurrentTranslation(models.ForeignObject): """ Creates virtual relation to the translation with model cache enabled. """ # Avoid validation requires_unique_target = False def __init__(self, to, on_delete, from_fields, to_fields, **kwargs): # Disable reverse relation kwargs['related_name'] = '+' # Set unique to enable model cache. kwargs['unique'] = True super(CurrentTranslation, self).__init__(to, on_delete, from_fields, to_fields, **kwargs) class ArticleTranslation(models.Model): article = models.ForeignKey('indexes.Article', models.CASCADE) article_no_constraint = models.ForeignKey('indexes.Article', models.CASCADE, db_constraint=False) language = models.CharField(max_length=10, unique=True) content = models.TextField() class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() # Add virtual relation to the ArticleTranslation model. translation = CurrentTranslation(ArticleTranslation, models.CASCADE, ['id'], ['article']) class Meta: index_together = [ ["headline", "pub_date"], ] # Model for index_together being used only with single list class IndexTogetherSingleList(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: index_together = ["headline", "pub_date"] # Indexing a TextField on Oracle or MySQL results in index creation error. if connection.vendor == 'postgresql': class IndexedArticle(models.Model): headline = models.CharField(max_length=100, db_index=True) body = models.TextField(db_index=True) slug = models.CharField(max_length=40, unique=True)
bsd-3-clause
sujitbehera27/MyRoboticsProjects-Arduino
src/resource/Python/examples/InMoov2.Alessandruino.py
4
1744
headPort = "COM5" i01 = Runtime.createAndStart("i01", "InMoov") mouthControl=i01.startMouthControl("COM5") head = i01.startHead(headPort) leftArm = i01.startLeftArm(headPort) leftHand = i01.startLeftHand(headPort) headTracking = i01.startHeadTracking("COM5") eyesTracking= i01.startEyesTracking("COM5") i01.headTracking.startLKTracking() i01.eyesTracking.startLKTracking() i01.startEar() ############################################################ #!!!my eyeY servo and jaw servo are reverted, Gael should delete this part !!!! i01.leftArm.bicep.setMinMax(10,85) i01.head.eyeY.map(0,180,180,0) i01.head.eyeY.setMinMax(22,85) i01.head.eyeX.setMinMax(60,85) i01.head.eyeY.setRest(45) i01.head.eyeY.moveTo(45) i01.head.jaw.setMinMax(10,75) i01.head.jaw.moveTo(70) i01.mouthControl.setmouth(75,55) ############################################################ i01.startMouth() i01.mouth.setGoogleURI("http://thehackettfamily.org/Voice_api/api2.php?voice=Graham&txt=") i01.headTracking.xpid.setPID(10.0,5.0,0.1) i01.headTracking.ypid.setPID(15.0,5.0,0.1) i01.eyesTracking.xpid.setPID(15.0,5.0,0.1) i01.eyesTracking.ypid.setPID(15.0,5.0,0.1) ear = i01.ear ear.addCommand("attach", "i01", "attach") ear.addCommand("detach", "i01", "detach") ear.addCommand("track humans", "python", "trackHumans") ear.addCommand("track point", "python", "trackPoint") ear.addCommand("stop tracking", "python", "stopTracking") ear.addCommand("rest position", "i01.head", "rest") ear.addCommand("close hand", "i01.leftHand", "close") ear.addCommand("open hand", "i01.leftHand", "open") ear.addComfirmations("yes", "correct", "yeah", "ya") ear.addNegations("no", "wrong", "nope", "nah") # all commands MUST be before startListening ear.startListening()
apache-2.0
muddy1/herckernels
scripts/build-all.py
1250
9474
#! /usr/bin/env python # Copyright (c) 2009-2011, Code Aurora Forum. 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 Code Aurora 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, FITNESS FOR A PARTICULAR PURPOSE AND # NON-INFRINGEMENT 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. # Build the kernel for all targets using the Android build environment. # # TODO: Accept arguments to indicate what to build. import glob from optparse import OptionParser import subprocess import os import os.path import shutil import sys version = 'build-all.py, version 0.01' build_dir = '../all-kernels' make_command = ["vmlinux", "modules"] make_env = os.environ make_env.update({ 'ARCH': 'arm', 'CROSS_COMPILE': 'arm-none-linux-gnueabi-', 'KCONFIG_NOTIMESTAMP': 'true' }) all_options = {} def error(msg): sys.stderr.write("error: %s\n" % msg) def fail(msg): """Fail with a user-printed message""" error(msg) sys.exit(1) def check_kernel(): """Ensure that PWD is a kernel directory""" if (not os.path.isfile('MAINTAINERS') or not os.path.isfile('arch/arm/mach-msm/Kconfig')): fail("This doesn't seem to be an MSM kernel dir") def check_build(): """Ensure that the build directory is present.""" if not os.path.isdir(build_dir): try: os.makedirs(build_dir) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise def update_config(file, str): print 'Updating %s with \'%s\'\n' % (file, str) defconfig = open(file, 'a') defconfig.write(str + '\n') defconfig.close() def scan_configs(): """Get the full list of defconfigs appropriate for this tree.""" names = {} for n in glob.glob('arch/arm/configs/[fm]sm[0-9-]*_defconfig'): names[os.path.basename(n)[:-10]] = n for n in glob.glob('arch/arm/configs/qsd*_defconfig'): names[os.path.basename(n)[:-10]] = n for n in glob.glob('arch/arm/configs/apq*_defconfig'): names[os.path.basename(n)[:-10]] = n return names class Builder: def __init__(self, logname): self.logname = logname self.fd = open(logname, 'w') def run(self, args): devnull = open('/dev/null', 'r') proc = subprocess.Popen(args, stdin=devnull, env=make_env, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) count = 0 # for line in proc.stdout: rawfd = proc.stdout.fileno() while True: line = os.read(rawfd, 1024) if not line: break self.fd.write(line) self.fd.flush() if all_options.verbose: sys.stdout.write(line) sys.stdout.flush() else: for i in range(line.count('\n')): count += 1 if count == 64: count = 0 print sys.stdout.write('.') sys.stdout.flush() print result = proc.wait() self.fd.close() return result failed_targets = [] def build(target): dest_dir = os.path.join(build_dir, target) log_name = '%s/log-%s.log' % (build_dir, target) print 'Building %s in %s log %s' % (target, dest_dir, log_name) if not os.path.isdir(dest_dir): os.mkdir(dest_dir) defconfig = 'arch/arm/configs/%s_defconfig' % target dotconfig = '%s/.config' % dest_dir savedefconfig = '%s/defconfig' % dest_dir shutil.copyfile(defconfig, dotconfig) devnull = open('/dev/null', 'r') subprocess.check_call(['make', 'O=%s' % dest_dir, '%s_defconfig' % target], env=make_env, stdin=devnull) devnull.close() if not all_options.updateconfigs: build = Builder(log_name) result = build.run(['make', 'O=%s' % dest_dir] + make_command) if result != 0: if all_options.keep_going: failed_targets.append(target) fail_or_error = error else: fail_or_error = fail fail_or_error("Failed to build %s, see %s" % (target, build.logname)) # Copy the defconfig back. if all_options.configs or all_options.updateconfigs: devnull = open('/dev/null', 'r') subprocess.check_call(['make', 'O=%s' % dest_dir, 'savedefconfig'], env=make_env, stdin=devnull) devnull.close() shutil.copyfile(savedefconfig, defconfig) def build_many(allconf, targets): print "Building %d target(s)" % len(targets) for target in targets: if all_options.updateconfigs: update_config(allconf[target], all_options.updateconfigs) build(target) if failed_targets: fail('\n '.join(["Failed targets:"] + [target for target in failed_targets])) def main(): global make_command check_kernel() check_build() configs = scan_configs() usage = (""" %prog [options] all -- Build all targets %prog [options] target target ... -- List specific targets %prog [options] perf -- Build all perf targets %prog [options] noperf -- Build all non-perf targets""") parser = OptionParser(usage=usage, version=version) parser.add_option('--configs', action='store_true', dest='configs', help="Copy configs back into tree") parser.add_option('--list', action='store_true', dest='list', help='List available targets') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='Output to stdout in addition to log file') parser.add_option('--oldconfig', action='store_true', dest='oldconfig', help='Only process "make oldconfig"') parser.add_option('--updateconfigs', dest='updateconfigs', help="Update defconfigs with provided option setting, " "e.g. --updateconfigs=\'CONFIG_USE_THING=y\'") parser.add_option('-j', '--jobs', type='int', dest="jobs", help="Number of simultaneous jobs") parser.add_option('-l', '--load-average', type='int', dest='load_average', help="Don't start multiple jobs unless load is below LOAD_AVERAGE") parser.add_option('-k', '--keep-going', action='store_true', dest='keep_going', default=False, help="Keep building other targets if a target fails") parser.add_option('-m', '--make-target', action='append', help='Build the indicated make target (default: %s)' % ' '.join(make_command)) (options, args) = parser.parse_args() global all_options all_options = options if options.list: print "Available targets:" for target in configs.keys(): print " %s" % target sys.exit(0) if options.oldconfig: make_command = ["oldconfig"] elif options.make_target: make_command = options.make_target if options.jobs: make_command.append("-j%d" % options.jobs) if options.load_average: make_command.append("-l%d" % options.load_average) if args == ['all']: build_many(configs, configs.keys()) elif args == ['perf']: targets = [] for t in configs.keys(): if "perf" in t: targets.append(t) build_many(configs, targets) elif args == ['noperf']: targets = [] for t in configs.keys(): if "perf" not in t: targets.append(t) build_many(configs, targets) elif len(args) > 0: targets = [] for t in args: if t not in configs.keys(): parser.error("Target '%s' not one of %s" % (t, configs.keys())) targets.append(t) build_many(configs, targets) else: parser.error("Must specify a target to build, or 'all'") if __name__ == "__main__": main()
gpl-2.0
bcarroll/authmgr
python-3.6.2-Win64/Lib/site-packages/sqlalchemy/schema.py
32
1200
# schema.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Compatibility namespace for sqlalchemy.sql.schema and related. """ from .sql.base import ( SchemaVisitor ) from .sql.schema import ( BLANK_SCHEMA, CheckConstraint, Column, ColumnDefault, Constraint, DefaultClause, DefaultGenerator, FetchedValue, ForeignKey, ForeignKeyConstraint, Index, MetaData, PassiveDefault, PrimaryKeyConstraint, SchemaItem, Sequence, Table, ThreadLocalMetaData, UniqueConstraint, _get_table_key, ColumnCollectionConstraint, ColumnCollectionMixin ) from .sql.naming import conv from .sql.ddl import ( DDL, CreateTable, DropTable, CreateSequence, DropSequence, CreateIndex, DropIndex, CreateSchema, DropSchema, _DropView, CreateColumn, AddConstraint, DropConstraint, DDLBase, DDLElement, _CreateDropBase, _DDLCompiles, sort_tables, sort_tables_and_constraints )
bsd-3-clause
eudoxos/woodem
scripts/test-OLD/dispatcher-torture.py
3
2017
""" Script that shows dispatch matrices when all available functors are loaded. Later ones will overwrite earlier ones, this is not what you will get in reality. Pipe the output to file and open it in browser: $ woo-trunk dispatcher-torture.py > /tmp/aa.html $ firefox /tmp/aa.html """ import collections Dispatch=collections.namedtuple('Dispatch',['basename','types']) dispatches=[ Dispatch('Law',('IGeom','IPhys')), Dispatch('IGeom',('Shape','Shape')), Dispatch('IPhys',('Material','Material')), Dispatch('Bound',('Shape',)), Dispatch('GlBound',('Bound',)), Dispatch('GlIGeom',('IGeom',)), Dispatch('GlIPhys',('IPhys',)), Dispatch('GlShape',('Shape',)), #Dispatch('GlState',('State',)) # broken for now ] sys.path.append('.') import HTML outStr='' for D in dispatches: functors=woo.system.childClasses(D.basename+'Functor') # create dispatcher with all available functors dispatcher=eval(D.basename+'Dispatcher([%s])'%(','.join(['%s()'%f for f in functors]))) if len(D.types)==1: allDim0=list(woo.system.childClasses(D.types[0])) table=HTML.Table(header_row=allDim0) row=[] for d0 in allDim0: dd0=eval(d0+'()') try: f=dispatcher.dispFunctor(dd0) row.append(f.name if f else '-') except RuntimeError as strerror: row.append('<b>ambiguous (%s)</b>'%(strerror)) table.rows.append(row) elif len(D.types)==2: # lists of types the dispatcher accepts allDim0=list(woo.system.childClasses(D.types[0])) allDim1=list(woo.system.childClasses(D.types[1])) table=HTML.Table(header_row=['']+allDim1) for d0 in allDim0: row=['<b>'+d0+'</b>'] for d1 in allDim1: dd0,dd1=eval(d0+'()'),eval(d1+'()') try: f=dispatcher.dispFunctor(dd0,dd1) row.append(f.__class__.__name__ if f else '-') except RuntimeError: # ambiguous row.append('<b>ambiguous</b>') table.rows.append(row) else: raise ValueError("Dispatcher must be 1D or 2D, not %dD"%len(D.types)) outStr+='\n<h1>%sDispatcher</h1>'%D.basename outStr+=str(table) print outStr quit()
gpl-2.0
mblue9/tools-iuc
tools/raxml/raxml.py
17
4043
#!/usr/bin/env python """ Runs RAxML on a sequence file. For use with RAxML version 8.2.4 """ import fnmatch import glob import optparse def getint(name): basename = name.partition('RUN.') if basename[2] != '': num = basename[2] return int(num) def __main__(): # Parse the primary wrapper's command line options parser = optparse.OptionParser() # (-b) parser.add_option("--bootseed", action="store", type="int", dest="bootseed", help="Random number for non-parametric bootstrapping") # (-N/#) parser.add_option("--number_of_runs", action="store", type="int", dest="number_of_runs", default=1, help="Number of alternative runs") # (-q) parser.add_option("--multiple_model", action="store", type="string", dest="multiple_model", help="Multiple Model File") # (-x) parser.add_option("--rapid_bootstrap_random_seed", action="store", type="int", dest="rapid_bootstrap_random_seed", help="Rapid Boostrap Random Seed") (options, args) = parser.parse_args() # Multiple runs - concatenate if options.number_of_runs > 1: if options.bootseed is None and options.rapid_bootstrap_random_seed is None: runfiles = glob.glob('RAxML*RUN*') runfiles.sort(key=getint) # Logs with open('RAxML_log.galaxy', 'w') as outfile: for filename in runfiles: if fnmatch.fnmatch(filename, 'RAxML_log.galaxy.RUN.*'): with open(filename, 'r') as infile: for line in infile: outfile.write(line) # Parsimony Trees with open('RAxML_parsimonyTree.galaxy', 'w') as outfile: for filename in runfiles: if fnmatch.fnmatch(filename, 'RAxML_parsimonyTree.galaxy.RUN.*'): with open(filename, 'r') as infile: for line in infile: outfile.write(line) # Results with open('RAxML_result.galaxy', 'w') as outfile: for filename in runfiles: if fnmatch.fnmatch(filename, 'RAxML_result.galaxy.RUN.*'): with open(filename, 'r') as infile: for line in infile: outfile.write(line) # Multiple Model Partition Files if options.multiple_model: files = glob.glob('RAxML_bestTree.galaxy.PARTITION.*') if len(files) > 0: files.sort(key=getint) # Best Tree Partitions with open('RAxML_bestTreePartitions.galaxy', 'w') as outfile: for filename in files: if fnmatch.fnmatch(filename, 'RAxML_bestTree.galaxy.PARTITION.*'): with open(filename, 'r') as infile: for line in infile: outfile.write(line) else: with open('RAxML_bestTreePartitions.galaxy', 'w') as outfile: outfile.write("No partition files were produced.\n") # Result Partitions files = glob.glob('RAxML_result.galaxy.PARTITION.*') if len(files) > 0: files.sort(key=getint) with open('RAxML_resultPartitions.galaxy', 'w') as outfile: for filename in files: if fnmatch.fnmatch(filename, 'RAxML_result.galaxy.PARTITION.*'): with open(filename, 'r') as infile: for line in infile: outfile.write(line) else: with open('RAxML_resultPartitions.galaxy', 'w') as outfile: outfile.write("No partition files were produced.\n") # DEBUG options with open('RAxML_info.galaxy', 'a') as infof: infof.write('\nOM: CLI options DEBUG START:\n') infof.write(options.__repr__()) infof.write('\nOM: CLI options DEBUG END\n') if __name__ == "__main__": __main__()
mit
belmiromoreira/nova
nova/tests/unit/api/openstack/compute/test_api.py
26
5850
# Copyright 2010 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_serialization import jsonutils import six import webob import webob.dec import webob.exc from nova.api import openstack as openstack_api from nova.api.openstack import wsgi from nova import exception from nova import test from nova.tests.unit.api.openstack import fakes class APITest(test.NoDBTestCase): def _wsgi_app(self, inner_app): # simpler version of the app than fakes.wsgi_app return openstack_api.FaultWrapper(inner_app) def test_malformed_json(self): req = webob.Request.blank('/') req.method = 'POST' req.body = '{' req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 400) def test_malformed_xml(self): req = webob.Request.blank('/') req.method = 'POST' req.body = '<hi im not xml>' req.headers["content-type"] = "application/xml" res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 400) def test_vendor_content_type_json(self): ctype = 'application/vnd.openstack.compute+json' req = webob.Request.blank('/') req.headers['Accept'] = ctype res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) self.assertEqual(res.content_type, ctype) jsonutils.loads(res.body) def test_exceptions_are_converted_to_faults_webob_exc(self): @webob.dec.wsgify def raise_webob_exc(req): raise webob.exc.HTTPNotFound(explanation='Raised a webob.exc') # api.application = raise_webob_exc api = self._wsgi_app(raise_webob_exc) resp = webob.Request.blank('/').get_response(api) self.assertEqual(resp.status_int, 404, resp.body) def test_exceptions_are_converted_to_faults_api_fault(self): @webob.dec.wsgify def raise_api_fault(req): exc = webob.exc.HTTPNotFound(explanation='Raised a webob.exc') return wsgi.Fault(exc) # api.application = raise_api_fault api = self._wsgi_app(raise_api_fault) resp = webob.Request.blank('/').get_response(api) self.assertIn('itemNotFound', resp.body) self.assertEqual(resp.status_int, 404, resp.body) def test_exceptions_are_converted_to_faults_exception(self): @webob.dec.wsgify def fail(req): raise Exception("Threw an exception") # api.application = fail api = self._wsgi_app(fail) resp = webob.Request.blank('/').get_response(api) self.assertIn('{"computeFault', resp.body) self.assertEqual(resp.status_int, 500, resp.body) def _do_test_exception_safety_reflected_in_faults(self, expose): class ExceptionWithSafety(exception.NovaException): safe = expose @webob.dec.wsgify def fail(req): raise ExceptionWithSafety('some explanation') api = self._wsgi_app(fail) resp = webob.Request.blank('/').get_response(api) self.assertIn('{"computeFault', resp.body) expected = ('ExceptionWithSafety: some explanation' if expose else 'The server has either erred or is incapable ' 'of performing the requested operation.') self.assertIn(expected, resp.body) self.assertEqual(resp.status_int, 500, resp.body) def test_safe_exceptions_are_described_in_faults(self): self._do_test_exception_safety_reflected_in_faults(True) def test_unsafe_exceptions_are_not_described_in_faults(self): self._do_test_exception_safety_reflected_in_faults(False) def _do_test_exception_mapping(self, exception_type, msg): @webob.dec.wsgify def fail(req): raise exception_type(msg) api = self._wsgi_app(fail) resp = webob.Request.blank('/').get_response(api) self.assertIn(msg, resp.body) self.assertEqual(resp.status_int, exception_type.code, resp.body) if hasattr(exception_type, 'headers'): for (key, value) in six.iteritems(exception_type.headers): self.assertIn(key, resp.headers) self.assertEqual(resp.headers[key], str(value)) def test_quota_error_mapping(self): self._do_test_exception_mapping(exception.QuotaError, 'too many used') def test_non_nova_notfound_exception_mapping(self): class ExceptionWithCode(Exception): code = 404 self._do_test_exception_mapping(ExceptionWithCode, 'NotFound') def test_non_nova_exception_mapping(self): class ExceptionWithCode(Exception): code = 417 self._do_test_exception_mapping(ExceptionWithCode, 'Expectation failed') def test_exception_with_none_code_throws_500(self): class ExceptionWithNoneCode(Exception): code = None @webob.dec.wsgify def fail(req): raise ExceptionWithNoneCode() api = self._wsgi_app(fail) resp = webob.Request.blank('/').get_response(api) self.assertEqual(500, resp.status_int)
apache-2.0
CiscoSystems/avos
openstack_dashboard/test/integration_tests/pages/project/compute/overviewpage.py
3
1619
# 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 selenium.webdriver.common import by from openstack_dashboard.test.integration_tests.pages import basepage from openstack_dashboard.test.integration_tests.regions import forms from openstack_dashboard.test.integration_tests.regions import tables class OverviewPage(basepage.BaseNavigationPage): _usage_table_locator = (by.By.CSS_SELECTOR, 'table#project_usage') _date_form_locator = (by.By.CSS_SELECTOR, 'form#date_form') USAGE_TABLE_ACTIONS = ("download_csv",) def __init__(self, driver, conf): super(OverviewPage, self).__init__(driver, conf) self._page_title = 'Instance Overview' @property def usage_table(self): src_elem = self._get_element(*self._usage_table_locator) return tables.ActionsTableRegion(self.driver, self.conf, src_elem, self.USAGE_TABLE_ACTIONS) @property def date_form(self): src_elem = self._get_element(*self._date_form_locator) return forms.DateFormRegion(self.driver, self.conf, src_elem)
apache-2.0
nvoron23/statsmodels
statsmodels/graphics/mosaicplot.py
6
26886
"""Create a mosaic plot from a contingency table. It allows to visualize multivariate categorical data in a rigorous and informative way. see the docstring of the mosaic function for more informations. """ # Author: Enrico Giampieri - 21 Jan 2013 from __future__ import division from statsmodels.compat.python import (iteritems, iterkeys, lrange, string_types, lzip, itervalues, zip, range) import numpy as np from statsmodels.compat.collections import OrderedDict from itertools import product from numpy import iterable, r_, cumsum, array from statsmodels.graphics import utils from pandas import DataFrame __all__ = ["mosaic"] def _normalize_split(proportion): """ return a list of proportions of the available space given the division if only a number is given, it will assume a split in two pieces """ if not iterable(proportion): if proportion == 0: proportion = array([0.0, 1.0]) elif proportion >= 1: proportion = array([1.0, 0.0]) elif proportion < 0: raise ValueError("proportions should be positive," "given value: {}".format(proportion)) else: proportion = array([proportion, 1.0 - proportion]) proportion = np.asarray(proportion, dtype=float) if np.any(proportion < 0): raise ValueError("proportions should be positive," "given value: {}".format(proportion)) if np.allclose(proportion, 0): raise ValueError("at least one proportion should be" "greater than zero".format(proportion)) # ok, data are meaningful, so go on if len(proportion) < 2: return array([0.0, 1.0]) left = r_[0, cumsum(proportion)] left /= left[-1] * 1.0 return left def _split_rect(x, y, width, height, proportion, horizontal=True, gap=0.05): """ Split the given rectangle in n segments whose proportion is specified along the given axis if a gap is inserted, they will be separated by a certain amount of space, retaining the relative proportion between them a gap of 1 correspond to a plot that is half void and the remaining half space is proportionally divided among the pieces. """ x, y, w, h = float(x), float(y), float(width), float(height) if (w < 0) or (h < 0): raise ValueError("dimension of the square less than" "zero w={} h=()".format(w, h)) proportions = _normalize_split(proportion) # extract the starting point and the dimension of each subdivision # in respect to the unit square starting = proportions[:-1] amplitude = proportions[1:] - starting # how much each extrema is going to be displaced due to gaps starting += gap * np.arange(len(proportions) - 1) # how much the squares plus the gaps are extended extension = starting[-1] + amplitude[-1] - starting[0] # normalize everything for fit again in the original dimension starting /= extension amplitude /= extension # bring everything to the original square starting = (x if horizontal else y) + starting * (w if horizontal else h) amplitude = amplitude * (w if horizontal else h) # create each 4-tuple for each new block results = [(s, y, a, h) if horizontal else (x, s, w, a) for s, a in zip(starting, amplitude)] return results def _reduce_dict(count_dict, partial_key): """ Make partial sum on a counter dict. Given a match for the beginning of the category, it will sum each value. """ L = len(partial_key) count = sum(v for k, v in iteritems(count_dict) if k[:L] == partial_key) return count def _key_splitting(rect_dict, keys, values, key_subset, horizontal, gap): """ Given a dictionary where each entry is a rectangle, a list of key and value (count of elements in each category) it split each rect accordingly, as long as the key start with the tuple key_subset. The other keys are returned without modification. """ result = OrderedDict() L = len(key_subset) for name, (x, y, w, h) in iteritems(rect_dict): if key_subset == name[:L]: # split base on the values given divisions = _split_rect(x, y, w, h, values, horizontal, gap) for key, rect in zip(keys, divisions): result[name + (key,)] = rect else: result[name] = (x, y, w, h) return result def _tuplify(obj): """convert an object in a tuple of strings (even if it is not iterable, like a single integer number, but keep the string healthy) """ if np.iterable(obj) and not isinstance(obj, string_types): res = tuple(str(o) for o in obj) else: res = (str(obj),) return res def _categories_level(keys): """use the Ordered dict to implement a simple ordered set return each level of each category [[key_1_level_1,key_2_level_1],[key_1_level_2,key_2_level_2]] """ res = [] for i in zip(*(keys)): tuplefied = _tuplify(i) res.append(list(OrderedDict([(j, None) for j in tuplefied]))) return res def _hierarchical_split(count_dict, horizontal=True, gap=0.05): """ Split a square in a hierarchical way given a contingency table. Hierarchically split the unit square in alternate directions in proportion to the subdivision contained in the contingency table count_dict. This is the function that actually perform the tiling for the creation of the mosaic plot. If the gap array has been specified it will insert a corresponding amount of space (proportional to the unit lenght), while retaining the proportionality of the tiles. Parameters ---------- count_dict : dict Dictionary containing the contingency table. Each category should contain a non-negative number with a tuple as index. It expects that all the combination of keys to be representes; if that is not true, will automatically consider the missing values as 0 horizontal : bool The starting direction of the split (by default along the horizontal axis) gap : float or array of floats The list of gaps to be applied on each subdivision. If the lenght of the given array is less of the number of subcategories (or if it's a single number) it will extend it with exponentially decreasing gaps Returns ---------- base_rect : dict A dictionary containing the result of the split. To each key is associated a 4-tuple of coordinates that are required to create the corresponding rectangle: 0 - x position of the lower left corner 1 - y position of the lower left corner 2 - width of the rectangle 3 - height of the rectangle """ # this is the unit square that we are going to divide base_rect = OrderedDict([(tuple(), (0, 0, 1, 1))]) # get the list of each possible value for each level categories_levels = _categories_level(list(iterkeys(count_dict))) L = len(categories_levels) # recreate the gaps vector starting from an int if not np.iterable(gap): gap = [gap / 1.5 ** idx for idx in range(L)] # extend if it's too short if len(gap) < L: last = gap[-1] gap = list(*gap) + [last / 1.5 ** idx for idx in range(L)] # trim if it's too long gap = gap[:L] # put the count dictionay in order for the keys # this will allow some code simplification count_ordered = OrderedDict([(k, count_dict[k]) for k in list(product(*categories_levels))]) for cat_idx, cat_enum in enumerate(categories_levels): # get the partial key up to the actual level base_keys = list(product(*categories_levels[:cat_idx])) for key in base_keys: # for each partial and each value calculate how many # observation we have in the counting dictionary part_count = [_reduce_dict(count_ordered, key + (partial,)) for partial in cat_enum] # reduce the gap for subsequents levels new_gap = gap[cat_idx] # split the given subkeys in the rectangle dictionary base_rect = _key_splitting(base_rect, cat_enum, part_count, key, horizontal, new_gap) horizontal = not horizontal return base_rect def _single_hsv_to_rgb(hsv): """Transform a color from the hsv space to the rgb.""" from matplotlib.colors import hsv_to_rgb return hsv_to_rgb(array(hsv).reshape(1, 1, 3)).reshape(3) def _create_default_properties(data): """"Create the default properties of the mosaic given the data first it will varies the color hue (first category) then the color saturation (second category) and then the color value (third category). If a fourth category is found, it will put decoration on the rectangle. Doesn't manage more than four level of categories """ categories_levels = _categories_level(list(iterkeys(data))) Nlevels = len(categories_levels) # first level, the hue L = len(categories_levels[0]) # hue = np.linspace(1.0, 0.0, L+1)[:-1] hue = np.linspace(0.0, 1.0, L + 2)[:-2] # second level, the saturation L = len(categories_levels[1]) if Nlevels > 1 else 1 saturation = np.linspace(0.5, 1.0, L + 1)[:-1] # third level, the value L = len(categories_levels[2]) if Nlevels > 2 else 1 value = np.linspace(0.5, 1.0, L + 1)[:-1] # fourth level, the hatch L = len(categories_levels[3]) if Nlevels > 3 else 1 hatch = ['', '/', '-', '|', '+'][:L + 1] # convert in list and merge with the levels hue = lzip(list(hue), categories_levels[0]) saturation = lzip(list(saturation), categories_levels[1] if Nlevels > 1 else ['']) value = lzip(list(value), categories_levels[2] if Nlevels > 2 else ['']) hatch = lzip(list(hatch), categories_levels[3] if Nlevels > 3 else ['']) # create the properties dictionary properties = {} for h, s, v, t in product(hue, saturation, value, hatch): hv, hn = h sv, sn = s vv, vn = v tv, tn = t level = (hn,) + ((sn,) if sn else tuple()) level = level + ((vn,) if vn else tuple()) level = level + ((tn,) if tn else tuple()) hsv = array([hv, sv, vv]) prop = {'color': _single_hsv_to_rgb(hsv), 'hatch': tv, 'lw': 0} properties[level] = prop return properties def _normalize_data(data, index): """normalize the data to a dict with tuples of strings as keys right now it works with: 0 - dictionary (or equivalent mappable) 1 - pandas.Series with simple or hierarchical indexes 2 - numpy.ndarrays 3 - everything that can be converted to a numpy array 4 - pandas.DataFrame (via the _normalize_dataframe function) """ # if data is a dataframe we need to take a completely new road # before coming back here. Use the hasattr to avoid importing # pandas explicitly if hasattr(data, 'pivot') and hasattr(data, 'groupby'): data = _normalize_dataframe(data, index) index = None # can it be used as a dictionary? try: items = list(iteritems(data)) except AttributeError: # ok, I cannot use the data as a dictionary # Try to convert it to a numpy array, or die trying data = np.asarray(data) temp = OrderedDict() for idx in np.ndindex(data.shape): name = tuple(i for i in idx) temp[name] = data[idx] data = temp items = list(iteritems(data)) # make all the keys a tuple, even if simple numbers data = OrderedDict([_tuplify(k), v] for k, v in items) categories_levels = _categories_level(list(iterkeys(data))) # fill the void in the counting dictionary indexes = product(*categories_levels) contingency = OrderedDict([(k, data.get(k, 0)) for k in indexes]) data = contingency # reorder the keys order according to the one specified by the user # or if the index is None convert it into a simple list # right now it doesn't do any check, but can be modified in the future index = lrange(len(categories_levels)) if index is None else index contingency = OrderedDict() for key, value in iteritems(data): new_key = tuple(key[i] for i in index) contingency[new_key] = value data = contingency return data def _normalize_dataframe(dataframe, index): """Take a pandas DataFrame and count the element present in the given columns, return a hierarchical index on those columns """ #groupby the given keys, extract the same columns and count the element # then collapse them with a mean data = dataframe[index].dropna() grouped = data.groupby(index, sort=False) counted = grouped[index].count() averaged = counted.mean(axis=1) return averaged def _statistical_coloring(data): """evaluate colors from the indipendence properties of the matrix It will encounter problem if one category has all zeros """ data = _normalize_data(data, None) categories_levels = _categories_level(list(iterkeys(data))) Nlevels = len(categories_levels) total = 1.0 * sum(v for v in itervalues(data)) # count the proportion of observation # for each level that has the given name # at each level levels_count = [] for level_idx in range(Nlevels): proportion = {} for level in categories_levels[level_idx]: proportion[level] = 0.0 for key, value in iteritems(data): if level == key[level_idx]: proportion[level] += value proportion[level] /= total levels_count.append(proportion) # for each key I obtain the expected value # and it's standard deviation from a binomial distribution # under the hipothesys of independence expected = {} for key, value in iteritems(data): base = 1.0 for i, k in enumerate(key): base *= levels_count[i][k] expected[key] = base * total, np.sqrt(total * base * (1.0 - base)) # now we have the standard deviation of distance from the # expected value for each tile. We create the colors from this sigmas = dict((k, (data[k] - m) / s) for k, (m, s) in iteritems(expected)) props = {} for key, dev in iteritems(sigmas): red = 0.0 if dev < 0 else (dev / (1 + dev)) blue = 0.0 if dev > 0 else (dev / (-1 + dev)) green = (1.0 - red - blue) / 2.0 hatch = 'x' if dev > 2 else 'o' if dev < -2 else '' props[key] = {'color': [red, green, blue], 'hatch': hatch} return props def _create_labels(rects, horizontal, ax, rotation): """find the position of the label for each value of each category right now it supports only up to the four categories ax: the axis on which the label should be applied rotation: the rotation list for each side """ categories = _categories_level(list(iterkeys(rects))) if len(categories) > 4: msg = ("maximum of 4 level supported for axes labeling..and 4" "is alreay a lot of level, are you sure you need them all?") raise NotImplementedError(msg) labels = {} #keep it fixed as will be used a lot of times items = list(iteritems(rects)) vertical = not horizontal #get the axis ticks and labels locator to put the correct values! ax2 = ax.twinx() ax3 = ax.twiny() #this is the order of execution for horizontal disposition ticks_pos = [ax.set_xticks, ax.set_yticks, ax3.set_xticks, ax2.set_yticks] ticks_lab = [ax.set_xticklabels, ax.set_yticklabels, ax3.set_xticklabels, ax2.set_yticklabels] #for the vertical one, rotate it by one if vertical: ticks_pos = ticks_pos[1:] + ticks_pos[:1] ticks_lab = ticks_lab[1:] + ticks_lab[:1] #clean them for pos, lab in zip(ticks_pos, ticks_lab): pos([]) lab([]) #for each level, for each value in the level, take the mean of all #the sublevel that correspond to that partial key for level_idx, level in enumerate(categories): #this dictionary keep the labels only for this level level_ticks = dict() for value in level: #to which level it should refer to get the preceding #values of labels? it's rather a tricky question... #this is dependent on the side. It's a very crude management #but I couldn't think a more general way... if horizontal: if level_idx == 3: index_select = [-1, -1, -1] else: index_select = [+0, -1, -1] else: if level_idx == 3: index_select = [+0, -1, +0] else: index_select = [-1, -1, -1] #now I create the base key name and append the current value #It will search on all the rects to find the corresponding one #and use them to evaluate the mean position basekey = tuple(categories[i][index_select[i]] for i in range(level_idx)) basekey = basekey + (value,) subset = dict((k, v) for k, v in items if basekey == k[:level_idx + 1]) #now I extract the center of all the tiles and make a weighted #mean of all these center on the area of the tile #this should give me the (more or less) correct position #of the center of the category vals = list(itervalues(subset)) W = sum(w * h for (x, y, w, h) in vals) x_lab = sum((x + w / 2.0) * w * h / W for (x, y, w, h) in vals) y_lab = sum((y + h / 2.0) * w * h / W for (x, y, w, h) in vals) #now base on the ordering, select which position to keep #needs to be written in a more general form of 4 level are enough? #should give also the horizontal and vertical alignment side = (level_idx + vertical) % 4 level_ticks[value] = y_lab if side % 2 else x_lab #now we add the labels of this level to the correct axis ticks_pos[level_idx](list(itervalues(level_ticks))) ticks_lab[level_idx](list(iterkeys(level_ticks)), rotation=rotation[level_idx]) return labels def mosaic(data, index=None, ax=None, horizontal=True, gap=0.005, properties=lambda key: None, labelizer=None, title='', statistic=False, axes_label=True, label_rotation=0.0): """Create a mosaic plot from a contingency table. It allows to visualize multivariate categorical data in a rigorous and informative way. Parameters ---------- data : dict, pandas.Series, np.ndarray, pandas.DataFrame The contingency table that contains the data. Each category should contain a non-negative number with a tuple as index. It expects that all the combination of keys to be representes; if that is not true, will automatically consider the missing values as 0. The order of the keys will be the same as the one of insertion. If a dict of a Series (or any other dict like object) is used, it will take the keys as labels. If a np.ndarray is provided, it will generate a simple numerical labels. index: list, optional Gives the preferred order for the category ordering. If not specified will default to the given order. It doesn't support named indexes for hierarchical Series. If a DataFrame is provided, it expects a list with the name of the columns. ax : matplotlib.Axes, optional The graph where display the mosaic. If not given, will create a new figure horizontal : bool, optional (default True) The starting direction of the split (by default along the horizontal axis) gap : float or array of floats The list of gaps to be applied on each subdivision. If the lenght of the given array is less of the number of subcategories (or if it's a single number) it will extend it with exponentially decreasing gaps labelizer : function (key) -> string, optional A function that generate the text to display at the center of each tile base on the key of that tile properties : function (key) -> dict, optional A function that for each tile in the mosaic take the key of the tile and returns the dictionary of properties of the generated Rectangle, like color, hatch or similar. A default properties set will be provided fot the keys whose color has not been defined, and will use color variation to help visually separates the various categories. It should return None to indicate that it should use the default property for the tile. A dictionary of the properties for each key can be passed, and it will be internally converted to the correct function statistic: bool, optional (default False) if true will use a crude statistical model to give colors to the plot. If the tile has a containt that is more than 2 standard deviation from the expected value under independence hipotesys, it will go from green to red (for positive deviations, blue otherwise) and will acquire an hatching when crosses the 3 sigma. title: string, optional The title of the axis axes_label: boolean, optional Show the name of each value of each category on the axis (default) or hide them. label_rotation: float or list of float the rotation of the axis label (if present). If a list is given each axis can have a different rotation Returns ---------- fig : matplotlib.Figure The generate figure rects : dict A dictionary that has the same keys of the original dataset, that holds a reference to the coordinates of the tile and the Rectangle that represent it See Also ---------- A Brief History of the Mosaic Display Michael Friendly, York University, Psychology Department Journal of Computational and Graphical Statistics, 2001 Mosaic Displays for Loglinear Models. Michael Friendly, York University, Psychology Department Proceedings of the Statistical Graphics Section, 1992, 61-68. Mosaic displays for multi-way contingecy tables. Michael Friendly, York University, Psychology Department Journal of the american statistical association March 1994, Vol. 89, No. 425, Theory and Methods Examples ---------- The most simple use case is to take a dictionary and plot the result >>> data = {'a': 10, 'b': 15, 'c': 16} >>> mosaic(data, title='basic dictionary') >>> pylab.show() A more useful example is given by a dictionary with multiple indices. In this case we use a wider gap to a better visual separation of the resulting plot >>> data = {('a', 'b'): 1, ('a', 'c'): 2, ('d', 'b'): 3, ('d', 'c'): 4} >>> mosaic(data, gap=0.05, title='complete dictionary') >>> pylab.show() The same data can be given as a simple or hierarchical indexed Series >>> rand = np.random.random >>> from itertools import product >>> >>> tuples = list(product(['bar', 'baz', 'foo', 'qux'], ['one', 'two'])) >>> index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) >>> data = pd.Series(rand(8), index=index) >>> mosaic(data, title='hierarchical index series') >>> pylab.show() The third accepted data structureis the np array, for which a very simple index will be created. >>> rand = np.random.random >>> data = 1+rand((2,2)) >>> mosaic(data, title='random non-labeled array') >>> pylab.show() If you need to modify the labeling and the coloring you can give a function tocreate the labels and one with the graphical properties starting from the key tuple >>> data = {'a': 10, 'b': 15, 'c': 16} >>> props = lambda key: {'color': 'r' if 'a' in key else 'gray'} >>> labelizer = lambda k: {('a',): 'first', ('b',): 'second', ('c',): 'third'}[k] >>> mosaic(data, title='colored dictionary', properties=props, labelizer=labelizer) >>> pylab.show() Using a DataFrame as source, specifying the name of the columns of interest >>> gender = ['male', 'male', 'male', 'female', 'female', 'female'] >>> pet = ['cat', 'dog', 'dog', 'cat', 'dog', 'cat'] >>> data = pandas.DataFrame({'gender': gender, 'pet': pet}) >>> mosaic(data, ['pet', 'gender']) >>> pylab.show() """ if isinstance(data, DataFrame) and index is None: raise ValueError("You must pass an index if data is a DataFrame." " See examples.") from pylab import Rectangle fig, ax = utils.create_mpl_ax(ax) # normalize the data to a dict with tuple of strings as keys data = _normalize_data(data, index) # split the graph into different areas rects = _hierarchical_split(data, horizontal=horizontal, gap=gap) # if there is no specified way to create the labels # create a default one if labelizer is None: labelizer = lambda k: "\n".join(k) if statistic: default_props = _statistical_coloring(data) else: default_props = _create_default_properties(data) if isinstance(properties, dict): color_dict = properties properties = lambda key: color_dict.get(key, None) for k, v in iteritems(rects): # create each rectangle and put a label on it x, y, w, h = v conf = properties(k) props = conf if conf else default_props[k] text = labelizer(k) Rect = Rectangle((x, y), w, h, label=text, **props) ax.add_patch(Rect) ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', size='smaller') #creating the labels on the axis #o clearing it if axes_label: if np.iterable(label_rotation): rotation = label_rotation else: rotation = [label_rotation] * 4 labels = _create_labels(rects, horizontal, ax, rotation) else: ax.set_xticks([]) ax.set_xticklabels([]) ax.set_yticks([]) ax.set_yticklabels([]) ax.set_title(title) return fig, rects
bsd-3-clause
HRF92/myflask
foobar/app.py
1
1483
# -*- coding: utf-8 -*- '''The app module, containing the app factory function.''' from flask import Flask, render_template from foobar.settings import ProdConfig from foobar.assets import assets from foobar.extensions import ( bcrypt, cache, db, login_manager, migrate, debug_toolbar, ) from foobar import public, user def create_app(config_object=ProdConfig): '''An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ :param config_object: The configuration object to use. ''' app = Flask(__name__) app.config.from_object(config_object) register_extensions(app) register_blueprints(app) register_errorhandlers(app) return app def register_extensions(app): assets.init_app(app) bcrypt.init_app(app) cache.init_app(app) db.init_app(app) login_manager.init_app(app) debug_toolbar.init_app(app) migrate.init_app(app, db) return None def register_blueprints(app): app.register_blueprint(public.views.blueprint) app.register_blueprint(user.views.blueprint) return None def register_errorhandlers(app): def render_error(error): # If a HTTPException, pull the `code` attribute; default to 500 error_code = getattr(error, 'code', 500) return render_template("{0}.html".format(error_code)), error_code for errcode in [401, 404, 500]: app.errorhandler(errcode)(render_error) return None
bsd-3-clause
veltzer/demos-python
src/examples/short/multi_processing/single_process.py
1
1245
#!/usr/bin/env python import fcntl import os import os.path import sys import time ''' This is an example of how to make sure only a single python process is running of a specific kind... References: - http://stackoverflow.com/questions/220525/ensure-a-single-instance-of-an-application-in-linux ''' do_fork = False def single_runner(): program_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] pid_file = '/tmp/{}.pid'.format(program_name) try: fp = os.open(pid_file, os.O_WRONLY | os.O_CREAT) fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: # another instance is running print('this program is already running...', file=sys.stderr) sys.exit(1) # this does not work def single_runner_simple(): program_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] pid_file = '/tmp/{}.pid'.format(program_name) # if os.path.isfile(pid_file): # os.unlink(pid_file) try: os.open(pid_file, os.O_CREAT | os.O_EXCL) except IOError as e: print(e) # another instance is running print('this program is already running...', file=sys.stderr) sys.exit(1) single_runner() while True: time.sleep(3600)
gpl-3.0
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/policy_forwarding/policies/policy/rules/rule/config/__init__.py
1
12349
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListType from pyangbind.lib.yangtypes import YANGDynClass from pyangbind.lib.yangtypes import ReferenceType from pyangbind.lib.base import PybindBase from collections import OrderedDict from decimal import Decimal from bitarray import bitarray import six # PY3 support of some PY2 keywords (needs improved) if six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ class config(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/policy-forwarding/policies/policy/rules/rule/config. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Configuration parameters relating to the match rule. """ __slots__ = ("_path_helper", "_extmethods", "__sequence_id") _yang_name = "config" _pybind_generated_by = "container" def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__sequence_id = YANGDynClass( base=RestrictedClassType( base_type=long, restriction_dict={"range": ["0..4294967295"]}, int_size=32, ), is_leaf=True, yang_name="sequence-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="uint32", is_config=True, ) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path() + [self._yang_name] else: return [ "network-instances", "network-instance", "policy-forwarding", "policies", "policy", "rules", "rule", "config", ] def _get_sequence_id(self): """ Getter method for sequence_id, mapped from YANG variable /network_instances/network_instance/policy_forwarding/policies/policy/rules/rule/config/sequence_id (uint32) YANG Description: Unique sequence number for the policy rule. """ return self.__sequence_id def _set_sequence_id(self, v, load=False): """ Setter method for sequence_id, mapped from YANG variable /network_instances/network_instance/policy_forwarding/policies/policy/rules/rule/config/sequence_id (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_sequence_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sequence_id() directly. YANG Description: Unique sequence number for the policy rule. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=RestrictedClassType( base_type=long, restriction_dict={"range": ["0..4294967295"]}, int_size=32, ), is_leaf=True, yang_name="sequence-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="uint32", is_config=True, ) except (TypeError, ValueError): raise ValueError( { "error-string": """sequence_id must be of a type compatible with uint32""", "defined-type": "uint32", "generated-type": """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="sequence-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='uint32', is_config=True)""", } ) self.__sequence_id = t if hasattr(self, "_set"): self._set() def _unset_sequence_id(self): self.__sequence_id = YANGDynClass( base=RestrictedClassType( base_type=long, restriction_dict={"range": ["0..4294967295"]}, int_size=32, ), is_leaf=True, yang_name="sequence-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="uint32", is_config=True, ) sequence_id = __builtin__.property(_get_sequence_id, _set_sequence_id) _pyangbind_elements = OrderedDict([("sequence_id", sequence_id)]) class config(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/policy-forwarding/policies/policy/rules/rule/config. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Configuration parameters relating to the match rule. """ __slots__ = ("_path_helper", "_extmethods", "__sequence_id") _yang_name = "config" _pybind_generated_by = "container" def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__sequence_id = YANGDynClass( base=RestrictedClassType( base_type=long, restriction_dict={"range": ["0..4294967295"]}, int_size=32, ), is_leaf=True, yang_name="sequence-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="uint32", is_config=True, ) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path() + [self._yang_name] else: return [ "network-instances", "network-instance", "policy-forwarding", "policies", "policy", "rules", "rule", "config", ] def _get_sequence_id(self): """ Getter method for sequence_id, mapped from YANG variable /network_instances/network_instance/policy_forwarding/policies/policy/rules/rule/config/sequence_id (uint32) YANG Description: Unique sequence number for the policy rule. """ return self.__sequence_id def _set_sequence_id(self, v, load=False): """ Setter method for sequence_id, mapped from YANG variable /network_instances/network_instance/policy_forwarding/policies/policy/rules/rule/config/sequence_id (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_sequence_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sequence_id() directly. YANG Description: Unique sequence number for the policy rule. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=RestrictedClassType( base_type=long, restriction_dict={"range": ["0..4294967295"]}, int_size=32, ), is_leaf=True, yang_name="sequence-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="uint32", is_config=True, ) except (TypeError, ValueError): raise ValueError( { "error-string": """sequence_id must be of a type compatible with uint32""", "defined-type": "uint32", "generated-type": """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="sequence-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='uint32', is_config=True)""", } ) self.__sequence_id = t if hasattr(self, "_set"): self._set() def _unset_sequence_id(self): self.__sequence_id = YANGDynClass( base=RestrictedClassType( base_type=long, restriction_dict={"range": ["0..4294967295"]}, int_size=32, ), is_leaf=True, yang_name="sequence-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="uint32", is_config=True, ) sequence_id = __builtin__.property(_get_sequence_id, _set_sequence_id) _pyangbind_elements = OrderedDict([("sequence_id", sequence_id)])
apache-2.0
tonysyu/deli
deli/layout/grid_layout.py
1
4491
""" Tick generator classes and helper functions for calculating axis tick-related values (i.e., bounds and intervals). """ import numpy as np from traits.api import (Array, HasStrictTraits, Instance, Property, cached_property) from .bounding_box import BoundingBox class BaseGridLayout(HasStrictTraits): #: The bounding box containing data added to plot. data_bbox = Instance(BoundingBox) #: The data limits of in the grid direction. axial_limits = Property(Array, depends_on='data_bbox.updated') #: The grid positions in data space. axial_offsets = Property(Array, depends_on='axial_limits') @cached_property def _get_axial_offsets(self): a_min, a_max = self.axial_limits return np.array(auto_ticks(a_min, a_max), np.float64) class XGridLayout(BaseGridLayout): @cached_property def _get_axial_limits(self): return self.data_bbox.x_limits class YGridLayout(BaseGridLayout): @cached_property def _get_axial_limits(self): return self.data_bbox.y_limits def auto_ticks(x_min, x_max): """ Finds locations for axis tick marks. Calculates the locations for tick marks on an axis. The *x_min*, *x_max*, and *tick_interval* parameters specify how the axis end points and tick interval are calculated. Parameters ---------- x_min, x_max : 'auto', 'fit', or a number. The lower and upper bounds of the axis. If the value is a number, that value is used for the corresponding end point. If the value is 'auto', then the end point is calculated automatically. If the value is 'fit', then the axis bound is set to the corresponding *data_low* or *data_high* value. Returns ------- An array of tick mark locations. The first and last tick entries are the axis end points. """ lower = float(x_min) upper = float(x_max) tick_interval = auto_interval(lower, upper) # Compute the range of ticks values: start = np.floor(lower / tick_interval) * tick_interval end = np.floor(upper / tick_interval) * tick_interval if upper > end: end += tick_interval ticks = np.arange(start, end + (tick_interval / 2.0), tick_interval) return [tick for tick in ticks if tick >= x_min and tick <= x_max] def auto_interval(data_low, data_high): """ Calculates the tick interval for a range. The function chooses the number of tick marks, which can be between 3 and 9 marks (including end points), and chooses tick intervals at 1, 2, 2.5, 5, 10, 20, ... Returns ------- interval : float tick mark interval for axis """ x_range = float(data_high) - float(data_low) # Choose from between 2 and 8 tick marks. Preference given to more ticks. # Note: reverse order and see kludge below... divisions = np.arange(8.0, 2.0, -1.0) # (7, 6, ..., 3) # Calculate the intervals for the divisions: candidate_intervals = x_range / divisions # Get magnitudes and mantissas for each candidate: magnitudes = 10.0 ** np.floor(np.log10(candidate_intervals)) mantissas = candidate_intervals / magnitudes # List of "pleasing" intervals between ticks on graph. # Only the first magnitude are listed, higher mags others are inferred: magic_intervals = np.array((1.0, 2.0, 2.5, 5.0, 10.0)) # Calculate the absolute differences between the candidates # (with magnitude removed) and the magic intervals: differences = abs(magic_intervals[:, np.newaxis] - mantissas) # Find the division and magic interval combo that produce the # smallest differences: # KLUDGE: 'np.argsort' doesn't preserve the order of equal values, # so we subtract a small, index dependent amount from each difference # to force correct ordering. sh = np.shape(differences) small = 2.2e-16 * np.arange(sh[1]) * np.arange(sh[0])[:, np.newaxis] small = small[::-1, ::-1] # reverse the order differences = differences - small best_mantissa = np.minimum.reduce(differences, axis=0) best_magic = np.minimum.reduce(differences, axis=-1) magic_index = np.argsort(best_magic)[0] mantissa_index = np.argsort(best_mantissa)[0] # The best interval is the magic_interval multiplied by the magnitude # of the best mantissa: interval = magic_intervals[magic_index] magnitude = magnitudes[mantissa_index] result = interval * magnitude return result
bsd-3-clause
dcneeme/droidcontroller
droidcontroller/uniscada.py
1
36234
# This Python file uses the following encoding: utf-8 # send and receive monitoring and control messages to from UniSCADA monitoring system # udp kuulamiseks thread? # neeme import time, datetime import sqlite3 import traceback from socket import * import sys import os import gzip import tarfile import requests import logging log = logging.getLogger(__name__) class UDPchannel(): ''' Sends away the messages, combining different key:value pairs and adding host id and time. Listens for incoming commands and setup data. Several UDPchannel instances can be used in parallel, to talk with different servers. Used by sqlgeneral.py ''' def __init__(self, id = '000000000000', ip = '127.0.0.1', port = 44445, receive_timeout = 0.1, retrysend_delay = 5, loghost = '0.0.0.0', logport=514): # delays in seconds #from droidcontroller.connstate import ConnState from droidcontroller.statekeeper import StateKeeper self.sk = StateKeeper(off_tout=300, on_tout=0) # conn state with up/down times. # do hard reboot via 0xFEED when changed to down. # what to do if never up? keep hard rebooting? try: from droidcontroller.gpio_led import GPIOLED self.led = GPIOLED() # led alarm and conn except: log.warning('GPIOLED not imported') self.host_id = id self.ip = ip self.port = port self.loghost = loghost self.logport = logport self.logaddr = (self.loghost,self.logport) # tuple self.traffic = [0,0] # UDP bytes in, out self.UDPSock = socket(AF_INET,SOCK_DGRAM) self.UDPSock.settimeout(receive_timeout) self.retrysend_delay = retrysend_delay self.inum = 0 # sent message counter self.UDPlogSock = socket(AF_INET,SOCK_DGRAM) self.UDPlogSock.settimeout(None) # for syslog self.UDPlogSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) # broadcast allowed print('init: created uniscada and syslog connections to '+ip+':'+str(port)+' and '+loghost+':'+str(logport)) self.table = 'buff2server' # can be anything, not accessible to other objects WHY? would be useful to know the queue length... self.Initialize() def Initialize(self): ''' initialize time/related variables and create buffer database with one table in memory ''' self.ts = round(time.time(),1) #self.ts_inum = self.ts # inum increase time, is it used at all? NO! self.ts_unsent = self.ts # last unsent chk self.ts_udpsent=self.ts self.ts_udpgot=self.ts self.conn = sqlite3.connect(':memory:') #self.cur=self.conn.cursor() # cursors to read data from tables / cursor can be local self.makebuff() # create buffer table for unsent messages self.setIP(self.ip) self.setLogIP(self.loghost) def setIP(self, invar): ''' Set the monitoring server ip address ''' self.ip = invar self.saddr = (self.ip,self.port) # refresh needed def setLogIP(self, invar): ''' Set the syslog monitor ip address ''' self.loghost = invar self.logaddr = (self.loghost,self.logport) # refresh needed def setPort(self, invar): ''' Set the monitoring server UDP port ''' self.port = invar self.saddr = (self.ip,self.port) # refresh needed def setID(self, invar): ''' Set the host id ''' self.host_id = invar def setRetryDelay(self, invar): ''' Set the monitoring server UDP port ''' self.retrysend_delay = invar def getTS(self): ''' returns timestamps for last send trial and successful receive ''' return self.ts_udpsent, self.ts_udpgot def getID(self): ''' returns host id for this instance ''' return self.host_id def getIP(self): ''' returns server ip for this instance ''' return self.ip def getLogIP(self): ''' returns syslog server ip for this instance ''' return self.loghost def get_traffic(self): return self.traffic # tuple in, out def set_traffic(self, bytes_in = None, bytes_out = None): # set UDP traffic counters (it is possible to update only one of them as well) ''' Restores UDP traffic counter''' if bytes_in != None: if not bytes_in < 0: self.traffic[0] = bytes_in else: print('invalid bytes_in',bytes_in) if bytes_out != None: if not bytes_out < 0: self.traffic[1] = bytes_out else: print('invalid bytes_out',bytes_out) def set_inum(self,inum = 0): # set message counter self.inum=inum def get_inum(self): #get message counter return self.inum def get_ts_udpgot(self): #get ts of last ack from monitoring server return self.ts_udpgot def makebuff(self): # drops buffer table and creates Cmd='drop table if exists '+self.table sql="CREATE TABLE "+self.table+"(sta_reg,status NUMERIC,val_reg,value,ts_created NUMERIC,inum NUMERIC,ts_tried NUMERIC);" # semicolon needed for NPE for some reason! try: self.conn.execute(Cmd) # drop the table if it exists self.conn.executescript(sql) # read table into database self.conn.commit() msg='sqlread: successfully (re)created table '+self.table return 0 except: msg='sqlread: '+str(sys.exc_info()[1]) print(msg) #syslog(msg) traceback.print_exc() time.sleep(1) return 1 def delete_buffer(self): # empty buffer Cmd='delete from '+self.table try: self.conn.execute(Cmd) self.conn.commit() print('buffer content deleted') except: traceback.print_exc() def send(self, servicetuple): # store service components to buffer for send and resend ''' Adds service components into buffer table to be sent as a string message the components are sta_reg = '', status = 0, val_reg = '', value = '' ''' if servicetuple == None: log.warning('ignored servicetuple with value None') return 2 try: sta_reg=str(servicetuple[0]) status=int(servicetuple[1]) val_reg=str(servicetuple[2]) value=str(servicetuple[3]) self.ts = round(time.time(),1) Cmd="INSERT into "+self.table+" values('"+sta_reg+"',"+str(status)+",'"+val_reg+"','"+value+"',"+str(self.ts)+",0,0)" # inum and ts_tried left initially empty #print(Cmd) # debug self.conn.execute(Cmd) return 0 except: msg='FAILED to write svc into buffer' #syslog(msg) # incl syslog print(msg) traceback.print_exc() return 1 def unsent(self): # delete unsent for too long messages - otherwise the udp messages will contain older key:value duplicates! ''' Counts the non-acknowledged messages and removes older than 3 times retrysend_delay ''' if self.ts - self.ts_unsent < self.retrysend_delay / 2: # no need to recheck too early return 0 self.ts = round(time.time(),1) self.ts_unsent = self.ts mintscreated=0 maxtscreated=0 try: Cmd="BEGIN IMMEDIATE TRANSACTION" # buff2server self.conn.execute(Cmd) Cmd="SELECT count(sta_reg),min(ts_created),max(ts_created) from "+self.table+" where ts_created+0+"+str(3*self.retrysend_delay)+"<"+str(self.ts) # yle 3x regular notif cur = self.conn.cursor() cur.execute(Cmd) for rida in cur: # only one line for count if any at all delcount=rida[0] # int if delcount>0: # stalled services found #print repr(rida) # debug mintscreated=rida[1] maxtscreated=rida[2] print(delcount,'services lines waiting ack for',10*self.retrysend_delay,' s to be deleted') Cmd="delete from "+self.table+" where ts_created+0+"+str(10*self.retrysend_delay)+"<"+str(self.ts) # +" limit 10" # limit lisatud 23.03.2014 aga miks? self.conn.execute(Cmd) Cmd="SELECT count(sta_reg),min(ts_created),max(ts_created) from "+self.table cur.execute(Cmd) for rida in cur: # only one line for count if any at all delcount=rida[0] # int if delcount>50: # delete all! Cmd="delete from "+self.table self.conn.execute(Cmd) msg='deleted '+str(delcount)+' unsent messages from '+self.table+'!' print(msg) #syslog(msg) self.conn.commit() # buff2server transaction end return delcount # 0 #time.sleep(1) # prooviks except: msg='problem with unsent, '+str(sys.exc_info()[1]) print(msg) #syslog(msg) traceback.print_exc() #sys.stdout.flush() time.sleep(1) return 1 #unsent() end def buff2server(self): # send the buffer content ''' UDP monitoring message creation and sending (using udpsend) based on already existing buff2server data, does the retransmits too if needed. buff2server rows successfully send will be deleted by udpread() based on in: contained in the received message ''' timetoretry = 0 # local ts_created = 0 # local svc_count = 0 # local sendstring = '' timetoretry=int(self.ts-self.retrysend_delay) # send again services older than that Cmd = "BEGIN IMMEDIATE TRANSACTION" # buff2server try: self.conn.execute(Cmd) except: print('could not start transaction on self.conn, '+self.table) traceback.print_exc() Cmd = "SELECT * from "+self.table+" where ts_tried=0 or (ts_tried+0>1358756016 and ts_tried+0<"+str(self.ts)+"+0-"+str(timetoretry)+") AND status+0 != 3 order by ts_created asc limit 30" try: cur = self.conn.cursor() cur.execute(Cmd) for srow in cur: #print(repr(srow)) # debug, what will be sent if svc_count == 0: # on first row only increase the inum! self.inum=self.inum+1 # increase the message number / WHY HERE? ACK WILL NOT DELETE THE ROWS! if self.inum > 65535: self.inum = 1 # avoid zero for sending #self.ts_inum=self.ts # time to set new inum value svc_count=svc_count+1 sta_reg=srow[0] status=srow[1] val_reg=srow[2] value=srow[3] ts_created=srow[4] if val_reg != '': sendstring += val_reg+":"+str(value)+"\n" if sta_reg != '': sendstring += sta_reg+":"+str(status)+"\n" Cmd="update "+self.table+" set ts_tried="+str(int(self.ts))+",inum="+str(self.inum)+" where sta_reg='"+sta_reg+"' and status="+str(status)+" and ts_created="+str(ts_created) #print "update Cmd=",Cmd # debug self.conn.execute(Cmd) if svc_count>0: # there is something (changed services) to be sent! #print(svc_count,"services to send using inum",self.inum) # debug self.udpsend(sendstring) # sending away Cmd="SELECT count(inum) from "+self.table # unsent service count in buffer cur.execute(Cmd) # for srow in cur: svc_count2=int(srow[0]) # total number of unsent messages if svc_count2>30: # do not complain below 30 print(svc_count2,"SERVICES IN BUFFER waiting for ack from monitoring server") except: # buff2server read unsuccessful. unlikely... msg='problem with '+self.table+' read '+str(sys.exc_info()[1]) print(msg) #syslog(msg) traceback.print_exc() #sys.stdout.flush() time.sleep(1) return 1 self.conn.commit() # buff2server transaction end return 0 # udpmessage() end # ################# def udpsend(self, sendstring = ''): # actual udp sending, no resend. give message as parameter. used by buff2server too. ''' Sends UDP data immediately, adding self.inum if >0. ''' if sendstring == '': # nothing to send print('udpsend(): nothing to send!') return 1 self.ts = round(time.time(),1) sendstring += "id:"+str(self.host_id)+"\n" # loodame, et ts_created on enam-vahem yhine neil teenustel... if self.inum > 0: # "in:inum" to be added sendstring += "in:"+str(self.inum)+","+str(int(round(self.ts)))+"\n" self.traffic[1]=self.traffic[1]+len(sendstring) # adding to the outgoing UDP byte counter try: self.led.commLED(0) # off, blinking shows sending and time to ack except: pass try: sendlen=self.UDPSock.sendto(sendstring.encode('utf-8'),self.saddr) # tagastab saadetud baitide arvu self.traffic[1]=self.traffic[1]+sendlen # traffic counter udp out msg='==>> sent ' +str(sendlen)+' bytes to '+str(repr(self.saddr))+' '+sendstring.replace('\n',' ') # show as one line print(msg) #syslog(msg) sendstring='' self.ts_udpsent=self.ts # last successful udp send return sendlen except: msg='udp send failure in udpsend() to saddr '+repr(self.saddr)+', lasting s '+str(int(self.ts - self.ts_udpsent)) # cannot send, this means problem with connectivity #syslog(msg) print(msg) traceback.print_exc() try: self.led.alarmLED(1) # send failure except: pass return None def read_buffer(self, mode = 0): # 0 prints content, 1 is silent but returns record count, min and max ts ''' reads the content of the buffer, debugging needs mainly. Returns the number of waiting to be deleted messages, the earliest and the latest timestamps. ''' if mode == 0: # just print the waiting messages Cmd ="SELECT * from "+self.table cur = self.conn.cursor() cur.execute(Cmd) for row in cur: print(repr(row)) elif mode == 1: # stats Cmd ="SELECT count(ts_created),min(ts_created),max(ts_created) from "+self.table cur = self.conn.cursor() cur.execute(Cmd) for row in cur: return row[0],row[1],row[2] # print(repr(row)) def udpread(self): ''' Checks received data for monitoring server to see if the data contains key "in", then deletes the rows with this inum in the sql table. If the received datagram contains more data, these key:value pairs are returned as dictionary. ''' data='' data_dict={} # possible setup and commands sendstring = '' try: # if anything is comes into udp buffer before timepout buf=1024 rdata,raddr = self.UDPSock.recvfrom(buf) data=rdata.decode("utf-8") # python3 related need due to mac in hex except: #print('no new udp data received') # debug #traceback.print_exc() return None if len(data) > 0: # something arrived #log.info('>>> got from receiver '+str(repr(raddr))+' '+str(repr(data))) self.traffic[0]=self.traffic[0]+len(data) # adding top the incoming UDP byte counter log.debug('<<<< got from receiver '+str(data.replace('\n', ' '))) if (int(raddr[1]) < 1 or int(raddr[1]) > 65536): msg='illegal remote port '+str(raddr[1])+' in the message received from '+raddr[0] print(msg) #syslog(msg) if raddr[0] != self.ip: msg='illegal sender '+str(raddr[0])+' of message: '+data+' at '+str(int(self.ts)) # ignore the data received! print(msg) #syslog(msg) data='' # data destroy if "id:" in data: # first check based on host id existence in the received message, must exist to be valid message! in_id=data[data.find("id:")+3:].splitlines()[0] if in_id != self.host_id: log.warning("invalid id "+in_id+" in server message from "+str(raddr[0])) # this is not for us! data='' return data # error condition, traffic counter was still increased else: self.ts_udpgot=self.ts # timestamp of last udp received try: self.led.commLED(1) # data from server, comm OK except: pass self.sk.up() lines=data.splitlines() # split message into key:value lines for i in range(len(lines)): # looking into every member of incoming message if ":" in lines[i]: #print " "+lines[i] line = lines[i].split(':') line = lines[i].split(':') sregister = line[0] # setup reg name svalue = line[1] # setup reg value log.debug('processing key:value '+sregister+':'+svalue) if sregister != 'in' and sregister != 'id': # may be setup or command (cmd:) msg='got setup/cmd reg:val '+sregister+':'+svalue # need to reply in order to avoid retransmits of the command(s) log.info(msg) data_dict.update({ sregister : svalue }) # in and id are not included in dict #udp.syslog(msg) # cannot use udp here #sendstring += sregister+":"+svalue+"\n" # add to the answer - better to answer with real values immediately after change else: if sregister == "in": # one such a key in message inumm=eval(data[data.find("in:")+3:].splitlines()[0].split(',')[0]) # loodaks integerit if inumm >= 0 and inumm<65536: # valid inum, response to message sent if 1...65535. datagram including "in:0" is a server initiated "fast communication" message #print "found valid inum",inum,"in the incoming message " # temporary msg='got ack '+str(inumm)+' in message: '+data.replace('\n',' ') log.debug(msg) #syslog(msg) Cmd="BEGIN IMMEDIATE TRANSACTION" # buff2server, to delete acknowledged rows from the buffer self.conn.execute(Cmd) # buff2server ack transactioni algus, loeme ja kustutame saadetud read Cmd="DELETE from "+self.table+" WHERE inum='"+str(inumm)+"'" # deleting all rows where inum matches server ack try: self.conn.execute(Cmd) # deleted except: msg='problem with '+Cmd+'\n'+str(sys.exc_info()[1]) print(msg) #syslog(msg) time.sleep(1) self.conn.commit() # buff2server transaction end #if len(sendstring) > 0: # self.udpsend(sendstring) # send the response right away to avoid multiple retransmits # log.info('response to server: '+str(sendstring)) # this answers to the server but does not update the setup or service table yet! #siin ei vasta return data_dict # possible key:value pairs here for setup change or commands. returns {} for just ack with no cmd else: return None def syslog(self, msg,logaddr=()): # sending out syslog message to self.logaddr. msg=msg+"\n" # add newline to the end #print('syslog send to',self.logaddr) # debug dnsize=0 if self.logaddr == None and logaddr != (): self.logaddr = logaddr try: # self.UDPlogSock.sendto(msg.encode('utf-8'),self.logaddr) if not '255.255.' in self.logaddr[0] and not '10.0.' in self.logaddr[0] and not '192.168.' in self.logaddr[0]: # sending syslog out of local network dnsize=len(msg) # udp out increase, payload only except: pass # kui udp ei toimi, ei toimi ka syslog print('could NOT send syslog message to '+repr(self.logaddr)) traceback.print_exc() self.traffic[1] += dnsize # udp traffic return 0 def comm(self): # do this regularly, blocks for the time of socket timeout! ''' Communicates with monitoring server, listens to return cmd and setup key:value and sends waiting data. ''' self.ts = round(time.time(),1) # timestamp self.unsent() # delete old records udpgot = self.udpread() # check for incoming udp data # parse_udp() self.buff2server() # send away. the ack for this is available on next comm() hopefully return udpgot class TCPchannel(UDPchannel): # used this parent to share self.syslog() ''' Communication via TCP (pull, push, calendar) ''' def __init__(self, id = '000000000000', supporthost = 'www.itvilla.ee', directory = '/support/pyapp/', uploader='/upload.php', base64string='cHlhcHA6QkVMYXVwb2E='): self.supporthost = supporthost self.uploader=uploader self.base64string=base64string self.traffic = [0,0] # TCP bytes in, out self.setID(id) self.directory=directory self.ts_cal=time.time() self.conn = sqlite3.connect(':memory:') # for calendar table self.makecalendar() def setID(self, invar): ''' Set the host id ''' self.host_id = invar def getID(self): '''returns server ip for this instance ''' return self.host_id def get_traffic(self): # TCP traffic counter return self.traffic # tuple in, out def set_traffic(self, bytes_in = None, bytes_out = None): # set TCP traffic counters (it is possible to update only one of them as well) ''' Restores TCP traffic counter [in, out] ''' if bytes_in != None: if not bytes_in < 0: self.traffic[0] = bytes_in log.debug('set bytes_in to '+str(bytes_in)) else: log.warning('invalid bytes_in '+str(bytes_in)) if bytes_out != None: if not bytes_out < 0: self.traffic[1] = bytes_out log.debug('set bytes_out to '+str(bytes_in)) else: print('invalid bytes_out',bytes_out) log.warning('invalid bytes_out '+str(bytes_in)) def get_ts_cal(self): # last time calendar was accessed return int(round(self.ts_cal)) def push(self, filename): # send (gzipped) file to supporthost ''' push file filename to supporthost directory using uploader and base64string (for basic auth) ''' if os.path.isfile(filename): pass else: msg='push: found no file '+filename print(msg) return 2 # no such file if '.gz' in filename or '.tgz' in filename: # packed already pass else: # lets unpack too f_in = open(filename, 'rb') f_out = gzip.open(filename+'.gz', 'wb') f_out.writelines(f_in) f_out.close() f_in.close() filename = filename+'.gz' # new filename to send dnsize=os.stat(filename)[6] # file size to be sent msg='the file was gzipped to '+filename+' with size '+str(dnsize) # the original file is kept! print(msg) #udp.syslog(msg) try: r = requests.post('http://'+self.supporthost+self.uploader, files={'file': open(filename, 'rb')}, headers={'Authorization': 'Basic '+self.base64string}, data={'mac': self.directory+self.host_id+'/'} ) print('post response:',r.text) # nothing? msg='file '+filename+' with size '+str(dnsize)+' sent to '+self.directory+self.host_id+'/' #udp.syslog(msg) print(msg) self.traffic[1] += dnsize return 0 except: msg='the file '+filename+' was NOT sent to '+self.directory+self.host_id+'/ '+str(sys.exc_info()[1]) #udp.syslog(msg) print(msg) #traceback.print_exc() return 1 def pull(self, filename, filesize, start=0): ''' Retrieves file from support server via http get, uncompressing too if filename contains .gz or tgz and succesfully retrieved. Parameter start=0 normally, higher with resume. ''' oksofar=1 # success flag filename2='' # for uncompressed from the downloaded file filepart=filename+'.part' # temporary, to be renamed to filename when complete filebak=filename+'.bak' dnsize=0 # size of downloaded file if start>filesize: msg='pull parameters: file '+filename+' start '+str(start)+' above filesize '+str(filesize) log.debug(msg) #udp.syslog(msg) return 99 # illegal parameters or file bigger than stated during download resume req = 'http://'+self.supporthost+self.directory+self.host_id+'/'+filename pullheaders={'Range': 'bytes=%s-' % (start)} # with requests msg='trying '+req+' from byte '+str(start)+' using '+repr(pullheaders) log.info(msg) #udp.syslog(msg) try: response = requests.get(req, headers=pullheaders) # with python3 output = open(filepart,'wb') output.write(response.content) output.close() except: msg='pull: partial or failed download of temporary file '+filepart+' '+str(sys.exc_info()[1]) log.warning(msg) #udp.syslog(msg) #traceback.print_exc() try: dnsize=os.stat(filepart)[6] # int(float(subexec('ls -l '+filename,1).split(' ')[4])) except: msg='pull: got no size for file '+os.getcwd()+'/'+filepart+' '+str(sys.exc_info()[1]) print(msg) #udp.syslog(msg) #traceback.print_exc() oksofar=0 if dnsize == filesize: # ok msg='pull: file '+filename+' download OK, size '+str(dnsize) print(msg) #udp.syslog(msg) try: os.rename(filename, filebak) # keep the previous version if exists #msg='renamed '+filename+' to '+filebak except: #traceback.print_exc() msg='FAILED to rename '+filename+' to '+filebak+' '+str(sys.exc_info()[1]) print(msg) #udp.syslog(msg) oksofar=0 try: os.rename(filepart, filename) #rename filepart to filename2 #msg='renamed '+filepart+' to '+filename except: msg='FAILED to rename '+filepart+' to '+filename+' '+str(sys.exc_info()[1]) print(msg) #udp.syslog(msg) oksofar=0 #traceback.print_exc() if oksofar == 0: # trouble, exit self.traffic[0] += dnsize return 1 if '.gz' in filename: # lets unpack too filename2=filename.replace('.gz','') try: os.rename(filename2, filename2+'.bak') # keep the previous versioon if exists except: #traceback.print_exc() pass try: f = gzip.open(filename,'rb') output = open(filename2,'wb') output.write(f.read()); output.close() # file with filename2 created msg='pull: gz file '+filename+' unzipped to '+filename2+', previous file kept as '+filebak print(msg) except: os.rename(filename2+'.bak', filename2) # restore the previous versioon if unzip failed msg='pull: file '+filename+' unzipping failure, previous file '+filename2+' restored. '+str(sys.exc_info()[1]) #traceback.print_exc() print(msg) #udp.syslog(msg) self.traffic[0] += dnsize return 1 if '.tgz' in filename: # possibly contains a directory try: f = tarfile.open(filename,'r') f.extractall() # extract all into the current directory f.close() msg='pull: tgz file '+filename+' successfully unpacked' print(msg) #udp.syslog(msg) except: msg='pull: tgz file '+filename+' unpacking failure! '+str(sys.exc_info()[1]) #traceback.print_exc() print(msg) #udp.syslog(msg) self.traffic[0] += dnsize return 1 # temporarely switching off this chmod feature, failing!! #if '.py' in filename2 or '.sh' in filename2: # make it executable, only works with gzipped files! # try: # st = os.stat('filename2') # os.chmod(filename2, st.st_mode | stat.S_IEXEC) # add +x for the owner # msg='made the pulled file executable' # print(msg) # syslog(msg) # return 0 # except: # msg='FAILED to make pulled file executable!' # print(msg) ## syslog(msg) # traceback.print_exc() # return 99 self.traffic[0] += dnsize return 0 else: if dnsize<filesize: msg='pull: file '+filename+' received partially with size '+str(dnsize) print(msg) #udp.syslog(msg) self.traffic[0] += dnsize return 1 # next try will continue else: msg='pull: file '+filename+' received larger than unexpected, in size '+str(dnsize) print(msg) #udp.syslog(msg) self.traffic[0] += dnsize return 99 def makecalendar(self, table='calendar'): # creates buffer table in memory for calendar events Cmd='drop table if exists '+table sql="CREATE TABLE "+table+"(title,timestamp,value);CREATE INDEX ts_calendar on "+table+"(timestamp);" # semicolon needed for NPE for some reason! try: self.conn.execute(Cmd) # drop the table if it exists self.conn.executescript(sql) # read table into database self.conn.commit() msg='successfully (re)created table '+table return 0 except: msg='sqlread: '+str(sys.exc_info()[1]) print(msg) #udp.syslog(msg) traceback.print_exc() time.sleep(1) return 1 def get_calendar(self, id, days = 3): # query to SUPPORTHOST, returning txt. started by cmd:GCAL too for testing ''' google calendar events via monitoring server ''' # example: http://www.itvilla.ee/cgi-bin/gcal.cgi?mac=000101000001&days=10 self.ts_cal=time.time() # calendar access timestamp cur=self.conn.cursor() req = 'http://www.itvilla.ee/cgi-bin/gcal.cgi?mac='+id+'&days='+str(days)+'&format=json' headers={'Authorization': 'Basic YmFyaXg6Y29udHJvbGxlcg=='} # Base64$="YmFyaXg6Y29udHJvbGxlcg==" ' barix:controller msg='starting gcal query '+req print(msg) # debug try: response = requests.get(req, headers = headers) except: msg='gcal query '+req+' failed!' traceback.print_exc() print(msg) #udp.syslog(msg) return 1 # kui ei saa gcal yhendust, siis lopetab ja vana ei havita! try: events = eval(response.content) # string to list except: msg='getting calendar events failed for host id '+id print(msg) #udp.syslog(msg) traceback.print_exc() # debug return 1 # kui ei saa normaalseid syndmusi, siis ka lopetab #print(repr(events)) # debug Cmd = "BEGIN IMMEDIATE TRANSACTION" try: self.conn.execute(Cmd) Cmd="delete from calendar" self.conn.execute(Cmd) for event in events: #print('event',event) # debug columns=str(list(event.keys())).replace('[','(').replace(']',')') values=str(list(event.values())).replace('[','(').replace(']',')') #columns=str(list(event.keys())).replace('{','(').replace('}',')') #values=str(list(event.values())).replace('{','(').replace('}',')') Cmd = "insert into calendar"+columns+" values"+values print(Cmd) # debug self.conn.execute(Cmd) self.conn.commit() msg='calendar table updated' print(msg) #udp.syslog(msg) # FIXME - syslog via UDPchannel does not work. syslog() is found, but not it's logaddr? #self.syslog(msg) # common parent UDP TCP channel return 0 except: msg='delete + insert to calendar table failed!' print(msg) #udp.syslog(msg) print('logaddr in tcp',self.logaddr) #self.syslog(msg,logaddr=self.logaddr) # class UDPchannel is parent to TCPchannel #UDPchannel.syslog(msg) traceback.print_exc() # debug return 1 # kui insert ei onnestu, siis ka delete ei toimu def chk_calevents(self, title = ''): # set a new setpoint if found in table calendar (sharing database connection with setup) ''' Obsolete, functionality moved to gcal.py ''' ts=time.time() cur=self.conn.cursor() value='' # local string value if title == '': return None Cmd = "BEGIN IMMEDIATE TRANSACTION" try: conn.execute(Cmd) Cmd="select value from calendar where title='"+title+"' and timestamp+0<"+str(ts)+" order by timestamp asc" # find the last passed event value cur.execute(Cmd) for row in cur: value=row[0] # overwrite with the last value before now #print(Cmd4,', value',value) # debug. voib olla mitu rida, viimane value jaab iga title jaoks kehtima self.conn.commit() return value # last one for given title becomes effective. can be empty string too, then use default value for setpoint related to title except: traceback.print_exc() return None
gpl-3.0
xenim/django-radioportal
radioportal/migrations/0011_auto_20151116_1920.py
2
1771
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def forwards_func(apps, schema_editor): Stream = apps.get_model("radioportal", "Stream") db_alias = schema_editor.connection.alias for s in Stream.objects.all(): if s.format == "mp3": s.codec = "mp3" s.container = "mp3" s.transports = "http" elif s.format == "ogg": s.codec = "vorbis" s.container = "ogg" s.transports = "http" elif s.format == "ogm": s.codec = "theora" s.container = "ogg" s.transports = "http" elif s.format == "aac": s.codec = "aac" s.container = "mpegts" s.transports = "hls" s.save() class Migration(migrations.Migration): dependencies = [ ('radioportal', '0010_auto_20151116_1918'), ] operations = [ migrations.RunPython(forwards_func), migrations.AlterField( model_name='stream', name='codec', field=models.CharField(default=b'mp3', max_length=100, choices=[(b'mp3', 'MP3'), (b'aac', 'AAC'), (b'vorbis', 'Vorbis'), (b'theora', 'Theora'), (b'opus', 'Opus')]), ), migrations.AlterField( model_name='stream', name='container', field=models.CharField(default=b'mp3', max_length=100, choices=[(b'mp3', 'MP3'), (b'ogg', 'OGG'), (b'mpegts', 'MPEG/TS')]), ), migrations.AlterField( model_name='stream', name='transports', field=models.CharField(default=b'http', max_length=100, choices=[(b'http', 'HTTP (Icecast)'), (b'hls', 'Apple HTTP Live Streaming')]), ), ]
bsd-3-clause
Denisolt/IEEE-NYIT-MA
local/lib/python2.7/site-packages/django/contrib/gis/db/backends/spatialite/operations.py
41
11651
""" SQL functions reference lists: http://www.gaia-gis.it/spatialite-2.4.0/spatialite-sql-2.4.html http://www.gaia-gis.it/spatialite-3.0.0-BETA/spatialite-sql-3.0.0.html http://www.gaia-gis.it/gaia-sins/spatialite-sql-4.2.1.html """ import re import sys from django.contrib.gis.db.backends.base.operations import \ BaseSpatialOperations from django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.db.models import aggregates from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.operations import DatabaseOperations from django.db.utils import DatabaseError from django.utils import six from django.utils.functional import cached_property class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations): name = 'spatialite' spatialite = True version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)') Adapter = SpatiaLiteAdapter Adaptor = Adapter # Backwards-compatibility alias. area = 'Area' centroid = 'Centroid' collect = 'Collect' contained = 'MbrWithin' difference = 'Difference' distance = 'Distance' envelope = 'Envelope' extent = 'Extent' intersection = 'Intersection' length = 'GLength' # OpenGis defines Length, but this conflicts with an SQLite reserved keyword num_geom = 'NumGeometries' num_points = 'NumPoints' point_on_surface = 'PointOnSurface' scale = 'ScaleCoords' svg = 'AsSVG' sym_difference = 'SymDifference' transform = 'Transform' translate = 'ShiftCoords' union = 'GUnion' # OpenGis defines Union, but this conflicts with an SQLite reserved keyword unionagg = 'GUnion' from_text = 'GeomFromText' from_wkb = 'GeomFromWKB' select = 'AsText(%s)' gis_operators = { 'equals': SpatialOperator(func='Equals'), 'disjoint': SpatialOperator(func='Disjoint'), 'touches': SpatialOperator(func='Touches'), 'crosses': SpatialOperator(func='Crosses'), 'within': SpatialOperator(func='Within'), 'overlaps': SpatialOperator(func='Overlaps'), 'contains': SpatialOperator(func='Contains'), 'intersects': SpatialOperator(func='Intersects'), 'relate': SpatialOperator(func='Relate'), # Returns true if B's bounding box completely contains A's bounding box. 'contained': SpatialOperator(func='MbrWithin'), # Returns true if A's bounding box completely contains B's bounding box. 'bbcontains': SpatialOperator(func='MbrContains'), # Returns true if A's bounding box overlaps B's bounding box. 'bboverlaps': SpatialOperator(func='MbrOverlaps'), # These are implemented here as synonyms for Equals 'same_as': SpatialOperator(func='Equals'), 'exact': SpatialOperator(func='Equals'), 'distance_gt': SpatialOperator(func='Distance', op='>'), 'distance_gte': SpatialOperator(func='Distance', op='>='), 'distance_lt': SpatialOperator(func='Distance', op='<'), 'distance_lte': SpatialOperator(func='Distance', op='<='), } @cached_property def function_names(self): return { 'Length': 'ST_Length', 'Reverse': 'ST_Reverse', 'Scale': 'ScaleCoords', 'Translate': 'ST_Translate' if self.spatial_version >= (3, 1, 0) else 'ShiftCoords', 'Union': 'ST_Union', } @cached_property def unsupported_functions(self): unsupported = {'BoundingCircle', 'ForceRHR', 'GeoHash', 'MemSize'} if not self.gml: unsupported.add('AsGML') if not self.kml: unsupported.add('AsKML') if self.spatial_version < (3, 0, 0): unsupported.add('AsGeoJSON') if self.spatial_version < (3, 1, 0): unsupported.add('SnapToGrid') if self.spatial_version < (4, 0, 0): unsupported.update({'Perimeter', 'Reverse'}) return unsupported @cached_property def spatial_version(self): """Determine the version of the SpatiaLite library.""" try: version = self.spatialite_version_tuple()[1:] except Exception as msg: new_msg = ( 'Cannot determine the SpatiaLite version for the "%s" ' 'database (error was "%s"). Was the SpatiaLite initialization ' 'SQL loaded on this database?') % (self.connection.settings_dict['NAME'], msg) six.reraise(ImproperlyConfigured, ImproperlyConfigured(new_msg), sys.exc_info()[2]) if version < (2, 4, 0): raise ImproperlyConfigured('GeoDjango only supports SpatiaLite versions ' '2.4.0 and above') return version @property def _version_greater_2_4_0_rc4(self): if self.spatial_version >= (2, 4, 1): return True else: # Spatialite 2.4.0-RC4 added AsGML and AsKML, however both # RC2 (shipped in popular Debian/Ubuntu packages) and RC4 # report version as '2.4.0', so we fall back to feature detection try: self._get_spatialite_func("AsGML(GeomFromText('POINT(1 1)'))") except DatabaseError: return False return True @cached_property def disallowed_aggregates(self): disallowed = (aggregates.Extent3D, aggregates.MakeLine) if self.spatial_version < (3, 0, 0): disallowed += (aggregates.Collect, aggregates.Extent) return disallowed @cached_property def gml(self): return 'AsGML' if self._version_greater_2_4_0_rc4 else None @cached_property def kml(self): return 'AsKML' if self._version_greater_2_4_0_rc4 else None @cached_property def geojson(self): return 'AsGeoJSON' if self.spatial_version >= (3, 0, 0) else None def convert_extent(self, box, srid): """ Convert the polygon data received from Spatialite to min/max values. """ if box is None: return None shell = Geometry(box, srid).shell xmin, ymin = shell[0][:2] xmax, ymax = shell[2][:2] return (xmin, ymin, xmax, ymax) def convert_geom(self, wkt, geo_field): """ Converts geometry WKT returned from a SpatiaLite aggregate. """ if wkt: return Geometry(wkt, geo_field.srid) else: return None def geo_db_type(self, f): """ Returns None because geometry columnas are added via the `AddGeometryColumn` stored procedure on SpatiaLite. """ return None def get_distance(self, f, value, lookup_type): """ Returns the distance parameters for the given geometry field, lookup value, and lookup type. SpatiaLite only supports regular cartesian-based queries (no spheroid/sphere calculations for point geometries like PostGIS). """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): raise ValueError('SpatiaLite does not support distance queries on ' 'geometry fields with a geodetic coordinate system. ' 'Distance objects; use a numeric value of your ' 'distance in degrees instead.') else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value return [dist_param] def get_geom_placeholder(self, f, value, compiler): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the Transform() and GeomFromText() function call(s). """ def transform_value(value, srid): return not (value is None or value.srid == srid) if hasattr(value, 'as_sql'): if transform_value(value, f.srid): placeholder = '%s(%%s, %s)' % (self.transform, f.srid) else: placeholder = '%s' # No geometry value used for F expression, substitute in # the column name instead. sql, _ = compiler.compile(value) return placeholder % sql else: if transform_value(value, f.srid): # Adding Transform() to the SQL placeholder. return '%s(%s(%%s,%s), %s)' % (self.transform, self.from_text, value.srid, f.srid) else: return '%s(%%s,%s)' % (self.from_text, f.srid) def _get_spatialite_func(self, func): """ Helper routine for calling SpatiaLite functions and returning their result. Any error occurring in this method should be handled by the caller. """ cursor = self.connection._cursor() try: cursor.execute('SELECT %s' % func) row = cursor.fetchone() finally: cursor.close() return row[0] def geos_version(self): "Returns the version of GEOS used by SpatiaLite as a string." return self._get_spatialite_func('geos_version()') def proj4_version(self): "Returns the version of the PROJ.4 library used by SpatiaLite." return self._get_spatialite_func('proj4_version()') def spatialite_version(self): "Returns the SpatiaLite library version as a string." return self._get_spatialite_func('spatialite_version()') def spatialite_version_tuple(self): """ Returns the SpatiaLite version as a tuple (version string, major, minor, subminor). """ version = self.spatialite_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception('Could not parse SpatiaLite version string: %s' % version) return (version, major, minor1, minor2) def spatial_aggregate_name(self, agg_name): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = 'unionagg' if agg_name.lower() == 'union' else agg_name.lower() return getattr(self, agg_name) # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.spatialite.models import SpatialiteGeometryColumns return SpatialiteGeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.spatialite.models import SpatialiteSpatialRefSys return SpatialiteSpatialRefSys def get_db_converters(self, expression): converters = super(SpatiaLiteOperations, self).get_db_converters(expression) if hasattr(expression.output_field, 'geom_type'): converters.append(self.convert_geometry) return converters def convert_geometry(self, value, expression, connection, context): if value: value = Geometry(value) if 'transformed_srid' in context: value.srid = context['transformed_srid'] return value
gpl-3.0
manqala/erpnext
erpnext/config/setup.py
29
3006
from __future__ import unicode_literals from frappe import _ from frappe.desk.moduleview import add_setup_section def get_data(): data = [ { "label": _("Settings"), "icon": "fa fa-wrench", "items": [ { "type": "doctype", "name": "Global Defaults", "label": _("Global Settings"), "description": _("Set Default Values like Company, Currency, Current Fiscal Year, etc."), "hide_count": True } ] }, { "label": _("Printing"), "icon": "fa fa-print", "items": [ { "type": "doctype", "name": "Letter Head", "description": _("Letter Heads for print templates.") }, { "type": "doctype", "name": "Print Heading", "description": _("Titles for print templates e.g. Proforma Invoice.") }, { "type": "doctype", "name": "Address Template", "description": _("Country wise default Address Templates") }, { "type": "doctype", "name": "Terms and Conditions", "description": _("Standard contract terms for Sales or Purchase.") }, ] }, { "label": _("Help"), "items": [ { "type": "help", "name": _("Data Import and Export"), "youtube_id": "6wiriRKPhmg" }, { "type": "help", "label": _("Setting up Email"), "youtube_id": "YFYe0DrB95o" }, { "type": "help", "label": _("Printing and Branding"), "youtube_id": "cKZHcx1znMc" }, { "type": "help", "label": _("Users and Permissions"), "youtube_id": "fnBoRhBrwR4" }, { "type": "help", "label": _("Workflow"), "youtube_id": "yObJUg9FxFs" }, ] }, { "label": _("Customize"), "icon": "fa fa-glass", "items": [ { "type": "doctype", "name": "Authorization Rule", "description": _("Create rules to restrict transactions based on values.") }, { "type": "doctype", "name": "Notification Control", "label": _("Email Notifications"), "description": _("Automatically compose message on submission of transactions.") } ] }, { "label": _("Email"), "icon": "fa fa-envelope", "items": [ { "type": "doctype", "name": "Feedback Trigger", "label": _("Feedback Trigger"), "description": _("Automatically triggers the feedback request based on conditions.") }, { "type": "doctype", "name": "Email Digest", "description": _("Create and manage daily, weekly and monthly email digests.") }, { "type": "doctype", "name": "SMS Settings", "description": _("Setup SMS gateway settings") }, ] } ] for module, label, icon in ( ("accounts", _("Accounts"), "fa fa-money"), ("stock", _("Stock"), "fa fa-truck"), ("selling", _("Selling"), "fa fa-tag"), ("buying", _("Buying"), "fa fa-shopping-cart"), ("hr", _("Human Resources"), "fa fa-group"), ("support", _("Support"), "fa fa-phone")): add_setup_section(data, "erpnext", module, label, icon) return data
gpl-3.0
dwadler/QGIS
tests/src/python/test_qgsserver_projectutils.py
22
2949
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsServerProject. .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'Paul Blottiere' __date__ = '26/12/2016' __copyright__ = 'Copyright 2016, The QGIS Project' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.server import QgsServerProjectUtils from qgis.core import QgsProject from qgis.testing import unittest from utilities import unitTestDataPath class TestQgsServerProjectUtils(unittest.TestCase): def setUp(self): self.testdata_path = unitTestDataPath('qgis_server_project') + '/' self.prj = QgsProject() self.prjPath = os.path.join(self.testdata_path, "project.qgs") self.prj.read(self.prjPath) self.prj2 = QgsProject() self.prj2Path = os.path.join(self.testdata_path, "project2.qgs") self.prj2.read(self.prj2Path) def tearDown(self): pass def test_size(self): self.assertEqual(QgsServerProjectUtils.wmsMaxWidth(self.prj), 400) self.assertEqual(QgsServerProjectUtils.wmsMaxHeight(self.prj), 500) def test_url(self): self.assertEqual(QgsServerProjectUtils.wmsServiceUrl(self.prj), "my_wms_advertised_url") self.assertEqual(QgsServerProjectUtils.wcsServiceUrl(self.prj), "my_wcs_advertised_url") self.assertEqual(QgsServerProjectUtils.wfsServiceUrl(self.prj), "my_wfs_advertised_url") def test_wmsuselayerids(self): self.assertEqual(QgsServerProjectUtils.wmsUseLayerIds(self.prj), False) self.assertEqual(QgsServerProjectUtils.wmsUseLayerIds(self.prj2), True) def test_wmsrestrictedlayers(self): # retrieve entry from project result = QgsServerProjectUtils.wmsRestrictedLayers(self.prj) expected = [] expected.append('points') # layer expected.append('group1') # local group expected.append('groupEmbedded') # embedded group self.assertListEqual(sorted(expected), sorted(result)) def test_wfslayersids(self): # retrieve entry from project result = QgsServerProjectUtils.wfsLayerIds(self.prj) expected = [] expected.append('multipoint20170309173637804') # from embedded group expected.append('points20170309173738552') # local layer expected.append('polys20170309173913723') # from local group self.assertEqual(expected, result) def test_wcslayersids(self): # retrieve entry from project result = QgsServerProjectUtils.wcsLayerIds(self.prj) expected = [] expected.append('landsat20170313142548073') self.assertEqual(expected, result) if __name__ == '__main__': unittest.main()
gpl-2.0
YuriyIlyin/ansible-modules-core
cloud/azure/azure.py
11
24048
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: azure short_description: create or terminate a virtual machine in azure description: - Creates or terminates azure instances. When created optionally waits for it to be 'running'. version_added: "1.7" options: name: description: - name of the virtual machine and associated cloud service. required: true default: null location: description: - the azure location to use (e.g. 'East US') required: true default: null subscription_id: description: - azure subscription id. Overrides the AZURE_SUBSCRIPTION_ID environment variable. required: false default: null management_cert_path: description: - path to an azure management certificate associated with the subscription id. Overrides the AZURE_CERT_PATH environment variable. required: false default: null storage_account: description: - the azure storage account in which to store the data disks. required: true image: description: - system image for creating the virtual machine (e.g., b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu_DAILY_BUILD-precise-12_04_3-LTS-amd64-server-20131205-en-us-30GB) required: true default: null role_size: description: - azure role size for the new virtual machine (e.g., Small, ExtraLarge, A6). You have to pay attention to the fact that instances of type G and DS are not available in all regions (locations). Make sure if you selected the size and type of instance available in your chosen location. required: false default: Small endpoints: description: - a comma-separated list of TCP ports to expose on the virtual machine (e.g., "22,80") required: false default: 22 user: description: - the unix username for the new virtual machine. required: false default: null password: description: - the unix password for the new virtual machine. required: false default: null ssh_cert_path: description: - path to an X509 certificate containing the public ssh key to install in the virtual machine. See http://www.windowsazure.com/en-us/manage/linux/tutorials/intro-to-linux/ for more details. - if this option is specified, password-based ssh authentication will be disabled. required: false default: null virtual_network_name: description: - Name of virtual network. required: false default: null hostname: description: - hostname to write /etc/hostname. Defaults to <name>.cloudapp.net. required: false default: null wait: description: - wait for the instance to be in state 'running' before returning required: false default: "no" choices: [ "yes", "no" ] aliases: [] wait_timeout: description: - how long before wait gives up, in seconds default: 600 aliases: [] wait_timeout_redirects: description: - how long before wait gives up for redirects, in seconds default: 300 aliases: [] state: description: - create or terminate instances required: false default: 'present' aliases: [] reset_pass_atlogon: description: - Reset the admin password on first logon for windows hosts required: false default: "no" version_added: "2.0" choices: [ "yes", "no" ] auto_updates: description: - Enable Auto Updates on Windows Machines required: false version_added: "2.0" default: "no" choices: [ "yes", "no" ] enable_winrm: description: - Enable winrm on Windows Machines required: false version_added: "2.0" default: "yes" choices: [ "yes", "no" ] os_type: description: - The type of the os that is gettings provisioned required: false version_added: "2.0" default: "linux" choices: [ "windows", "linux" ] requirements: - "python >= 2.6" - "azure >= 0.7.1" author: "John Whitbeck (@jwhitbeck)" ''' EXAMPLES = ''' # Note: None of these examples set subscription_id or management_cert_path # It is assumed that their matching environment variables are set. # Provision virtual machine example - local_action: module: azure name: my-virtual-machine role_size: Small image: b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu_DAILY_BUILD-precise-12_04_3-LTS-amd64-server-20131205-en-us-30GB location: 'East US' user: ubuntu ssh_cert_path: /path/to/azure_x509_cert.pem storage_account: my-storage-account wait: yes # Terminate virtual machine example - local_action: module: azure name: my-virtual-machine state: absent #Create windows machine - hosts: all connection: local tasks: - local_action: module: azure name: "ben-Winows-23" hostname: "win123" os_type: windows enable_winrm: yes subscription_id: "{{ azure_sub_id }}" management_cert_path: "{{ azure_cert_path }}" role_size: Small image: 'bd507d3a70934695bc2128e3e5a255ba__RightImage-Windows-2012-x64-v13.5' location: 'East Asia' password: "xxx" storage_account: benooytes user: admin wait: yes virtual_network_name: "{{ vnet_name }}" ''' import base64 import datetime import os import time from urlparse import urlparse from ansible.module_utils.facts import * # TimeoutError AZURE_LOCATIONS = ['South Central US', 'Central US', 'East US 2', 'East US', 'West US', 'North Central US', 'North Europe', 'West Europe', 'East Asia', 'Southeast Asia', 'Japan West', 'Japan East', 'Brazil South'] AZURE_ROLE_SIZES = ['ExtraSmall', 'Small', 'Medium', 'Large', 'ExtraLarge', 'A5', 'A6', 'A7', 'A8', 'A9', 'Basic_A0', 'Basic_A1', 'Basic_A2', 'Basic_A3', 'Basic_A4', 'Standard_D1', 'Standard_D2', 'Standard_D3', 'Standard_D4', 'Standard_D11', 'Standard_D12', 'Standard_D13', 'Standard_D14', 'Standard_DS1', 'Standard_DS2', 'Standard_DS3', 'Standard_DS4', 'Standard_DS11', 'Standard_DS12', 'Standard_DS13', 'Standard_DS14', 'Standard_G1', 'Standard_G2', 'Standard_G3', 'Standard_G4', 'Standard_G5'] try: import azure as windows_azure from azure import WindowsAzureError, WindowsAzureMissingResourceError from azure.servicemanagement import (ServiceManagementService, OSVirtualHardDisk, SSH, PublicKeys, PublicKey, LinuxConfigurationSet, ConfigurationSetInputEndpoints, ConfigurationSetInputEndpoint, Listener, WindowsConfigurationSet) HAS_AZURE = True except ImportError: HAS_AZURE = False from distutils.version import LooseVersion from types import MethodType import json def _wait_for_completion(azure, promise, wait_timeout, msg): if not promise: return wait_timeout = time.time() + wait_timeout while wait_timeout > time.time(): operation_result = azure.get_operation_status(promise.request_id) time.sleep(5) if operation_result.status == "Succeeded": return raise WindowsAzureError('Timed out waiting for async operation ' + msg + ' "' + str(promise.request_id) + '" to complete.') def _delete_disks_when_detached(azure, wait_timeout, disk_names): def _handle_timeout(signum, frame): raise TimeoutError("Timeout reached while waiting for disks to become detached.") signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(wait_timeout) try: while len(disk_names) > 0: for disk_name in disk_names: disk = azure.get_disk(disk_name) if disk.attached_to is None: azure.delete_disk(disk.name, True) disk_names.remove(disk_name) except WindowsAzureError, e: module.fail_json(msg="failed to get or delete disk, error was: %s" % (disk_name, str(e))) finally: signal.alarm(0) def get_ssh_certificate_tokens(module, ssh_cert_path): """ Returns the sha1 fingerprint and a base64-encoded PKCS12 version of the certificate. """ # This returns a string such as SHA1 Fingerprint=88:60:0B:13:A9:14:47:DA:4E:19:10:7D:34:92:2B:DF:A1:7D:CA:FF rc, stdout, stderr = module.run_command(['openssl', 'x509', '-in', ssh_cert_path, '-fingerprint', '-noout']) if rc != 0: module.fail_json(msg="failed to generate the key fingerprint, error was: %s" % stderr) fingerprint = stdout.strip()[17:].replace(':', '') rc, stdout, stderr = module.run_command(['openssl', 'pkcs12', '-export', '-in', ssh_cert_path, '-nokeys', '-password', 'pass:']) if rc != 0: module.fail_json(msg="failed to generate the pkcs12 signature from the certificate, error was: %s" % stderr) pkcs12_base64 = base64.b64encode(stdout.strip()) return (fingerprint, pkcs12_base64) def create_virtual_machine(module, azure): """ Create new virtual machine module : AnsibleModule object azure: authenticated azure ServiceManagementService object Returns: True if a new virtual machine and/or cloud service was created, false otherwise """ name = module.params.get('name') os_type = module.params.get('os_type') hostname = module.params.get('hostname') or name + ".cloudapp.net" endpoints = module.params.get('endpoints').split(',') ssh_cert_path = module.params.get('ssh_cert_path') user = module.params.get('user') password = module.params.get('password') location = module.params.get('location') role_size = module.params.get('role_size') storage_account = module.params.get('storage_account') image = module.params.get('image') virtual_network_name = module.params.get('virtual_network_name') wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) changed = False # Check if a deployment with the same name already exists cloud_service_name_available = azure.check_hosted_service_name_availability(name) if cloud_service_name_available.result: # cloud service does not exist; create it try: result = azure.create_hosted_service(service_name=name, label=name, location=location) _wait_for_completion(azure, result, wait_timeout, "create_hosted_service") changed = True except WindowsAzureError, e: module.fail_json(msg="failed to create the new service, error was: %s" % str(e)) try: # check to see if a vm with this name exists; if so, do nothing azure.get_role(name, name, name) except WindowsAzureMissingResourceError: # vm does not exist; create it if os_type == 'linux': # Create linux configuration disable_ssh_password_authentication = not password vm_config = LinuxConfigurationSet(hostname, user, password, disable_ssh_password_authentication) else: #Create Windows Config vm_config = WindowsConfigurationSet(hostname, password, module.params.get('reset_pass_atlogon'),\ module.params.get('auto_updates'), None, user) vm_config.domain_join = None if module.params.get('enable_winrm'): listener = Listener('Http') vm_config.win_rm.listeners.listeners.append(listener) else: vm_config.win_rm = None # Add ssh certificates if specified if ssh_cert_path: fingerprint, pkcs12_base64 = get_ssh_certificate_tokens(module, ssh_cert_path) # Add certificate to cloud service result = azure.add_service_certificate(name, pkcs12_base64, 'pfx', '') _wait_for_completion(azure, result, wait_timeout, "add_service_certificate") # Create ssh config ssh_config = SSH() ssh_config.public_keys = PublicKeys() authorized_keys_path = u'/home/%s/.ssh/authorized_keys' % user ssh_config.public_keys.public_keys.append(PublicKey(path=authorized_keys_path, fingerprint=fingerprint)) # Append ssh config to linux machine config vm_config.ssh = ssh_config # Create network configuration network_config = ConfigurationSetInputEndpoints() network_config.configuration_set_type = 'NetworkConfiguration' network_config.subnet_names = [] network_config.public_ips = None for port in endpoints: network_config.input_endpoints.append(ConfigurationSetInputEndpoint(name='TCP-%s' % port, protocol='TCP', port=port, local_port=port)) # First determine where to store disk today = datetime.date.today().strftime('%Y-%m-%d') disk_prefix = u'%s-%s' % (name, name) media_link = u'http://%s.blob.core.windows.net/vhds/%s-%s.vhd' % (storage_account, disk_prefix, today) # Create system hard disk os_hd = OSVirtualHardDisk(image, media_link) # Spin up virtual machine try: result = azure.create_virtual_machine_deployment(service_name=name, deployment_name=name, deployment_slot='production', label=name, role_name=name, system_config=vm_config, network_config=network_config, os_virtual_hard_disk=os_hd, role_size=role_size, role_type='PersistentVMRole', virtual_network_name=virtual_network_name) _wait_for_completion(azure, result, wait_timeout, "create_virtual_machine_deployment") changed = True except WindowsAzureError, e: module.fail_json(msg="failed to create the new virtual machine, error was: %s" % str(e)) try: deployment = azure.get_deployment_by_name(service_name=name, deployment_name=name) return (changed, urlparse(deployment.url).hostname, deployment) except WindowsAzureError, e: module.fail_json(msg="failed to lookup the deployment information for %s, error was: %s" % (name, str(e))) def terminate_virtual_machine(module, azure): """ Terminates a virtual machine module : AnsibleModule object azure: authenticated azure ServiceManagementService object Returns: True if a new virtual machine was deleted, false otherwise """ # Whether to wait for termination to complete before returning wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) name = module.params.get('name') delete_empty_services = module.params.get('delete_empty_services') changed = False deployment = None public_dns_name = None disk_names = [] try: deployment = azure.get_deployment_by_name(service_name=name, deployment_name=name) except WindowsAzureMissingResourceError, e: pass # no such deployment or service except WindowsAzureError, e: module.fail_json(msg="failed to find the deployment, error was: %s" % str(e)) # Delete deployment if deployment: changed = True try: # gather disk info results = [] for role in deployment.role_list: role_props = azure.get_role(name, deployment.name, role.role_name) if role_props.os_virtual_hard_disk.disk_name not in disk_names: disk_names.append(role_props.os_virtual_hard_disk.disk_name) except WindowsAzureError, e: module.fail_json(msg="failed to get the role %s, error was: %s" % (role.role_name, str(e))) try: result = azure.delete_deployment(name, deployment.name) _wait_for_completion(azure, result, wait_timeout, "delete_deployment") except WindowsAzureError, e: module.fail_json(msg="failed to delete the deployment %s, error was: %s" % (deployment.name, str(e))) # It's unclear when disks associated with terminated deployment get detatched. # Thus, until the wait_timeout is reached, we continue to delete disks as they # become detatched by polling the list of remaining disks and examining the state. try: _delete_disks_when_detached(azure, wait_timeout, disk_names) except (WindowsAzureError, TimeoutError), e: module.fail_json(msg=str(e)) try: # Now that the vm is deleted, remove the cloud service result = azure.delete_hosted_service(service_name=name) _wait_for_completion(azure, result, wait_timeout, "delete_hosted_service") except WindowsAzureError, e: module.fail_json(msg="failed to delete the service %s, error was: %s" % (name, str(e))) public_dns_name = urlparse(deployment.url).hostname return changed, public_dns_name, deployment def get_azure_creds(module): # Check module args for credentials, then check environment vars subscription_id = module.params.get('subscription_id') if not subscription_id: subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID', None) if not subscription_id: module.fail_json(msg="No subscription_id provided. Please set 'AZURE_SUBSCRIPTION_ID' or use the 'subscription_id' parameter") management_cert_path = module.params.get('management_cert_path') if not management_cert_path: management_cert_path = os.environ.get('AZURE_CERT_PATH', None) if not management_cert_path: module.fail_json(msg="No management_cert_path provided. Please set 'AZURE_CERT_PATH' or use the 'management_cert_path' parameter") return subscription_id, management_cert_path def main(): module = AnsibleModule( argument_spec=dict( ssh_cert_path=dict(), name=dict(), hostname=dict(), os_type=dict(default='linux', choices=['linux', 'windows']), location=dict(choices=AZURE_LOCATIONS), role_size=dict(choices=AZURE_ROLE_SIZES), subscription_id=dict(no_log=True), storage_account=dict(), management_cert_path=dict(), endpoints=dict(default='22'), user=dict(), password=dict(), image=dict(), virtual_network_name=dict(default=None), state=dict(default='present'), wait=dict(type='bool', default=False), wait_timeout=dict(default=600), wait_timeout_redirects=dict(default=300), reset_pass_atlogon=dict(type='bool', default=False), auto_updates=dict(type='bool', default=False), enable_winrm=dict(type='bool', default=True), ) ) if not HAS_AZURE: module.fail_json(msg='azure python module required for this module') # create azure ServiceManagementService object subscription_id, management_cert_path = get_azure_creds(module) wait_timeout_redirects = int(module.params.get('wait_timeout_redirects')) if LooseVersion(windows_azure.__version__) <= "0.8.0": # wrapper for handling redirects which the sdk <= 0.8.0 is not following azure = Wrapper(ServiceManagementService(subscription_id, management_cert_path), wait_timeout_redirects) else: azure = ServiceManagementService(subscription_id, management_cert_path) cloud_service_raw = None if module.params.get('state') == 'absent': (changed, public_dns_name, deployment) = terminate_virtual_machine(module, azure) elif module.params.get('state') == 'present': # Changed is always set to true when provisioning new instances if not module.params.get('name'): module.fail_json(msg='name parameter is required for new instance') if not module.params.get('image'): module.fail_json(msg='image parameter is required for new instance') if not module.params.get('user'): module.fail_json(msg='user parameter is required for new instance') if not module.params.get('location'): module.fail_json(msg='location parameter is required for new instance') if not module.params.get('storage_account'): module.fail_json(msg='storage_account parameter is required for new instance') if not module.params.get('password'): module.fail_json(msg='password parameter is required for new instance') (changed, public_dns_name, deployment) = create_virtual_machine(module, azure) module.exit_json(changed=changed, public_dns_name=public_dns_name, deployment=json.loads(json.dumps(deployment, default=lambda o: o.__dict__))) class Wrapper(object): def __init__(self, obj, wait_timeout): self.other = obj self.wait_timeout = wait_timeout def __getattr__(self, name): if hasattr(self.other, name): func = getattr(self.other, name) return lambda *args, **kwargs: self._wrap(func, args, kwargs) raise AttributeError(name) def _wrap(self, func, args, kwargs): if type(func) == MethodType: result = self._handle_temporary_redirects(lambda: func(*args, **kwargs)) else: result = self._handle_temporary_redirects(lambda: func(self.other, *args, **kwargs)) return result def _handle_temporary_redirects(self, f): wait_timeout = time.time() + self.wait_timeout while wait_timeout > time.time(): try: return f() except WindowsAzureError, e: if not str(e).lower().find("temporary redirect") == -1: time.sleep(5) pass else: raise e # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
jswanljung/iris
lib/iris/tests/unit/fileformats/grib/load_convert/test_product_definition_template_31.py
2
4414
# (C) British Crown Copyright 2014 - 2016, Met Office # # This file is part of Iris. # # Iris 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. # # Iris 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 Iris. If not, see <http://www.gnu.org/licenses/>. """ Tests for `iris.fileformats.grib._load_convert.product_definition_template_31`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # import iris tests first so that some things can be initialised # before importing anything else. import iris.tests as tests from copy import deepcopy import warnings import numpy as np from iris.coords import AuxCoord from iris.fileformats.grib._load_convert import product_definition_template_31 from iris.tests import mock class Test(tests.IrisTest): def setUp(self): patch = mock.patch('warnings.warn') patch.start() self.addCleanup(patch.stop) self.metadata = {'factories': [], 'references': [], 'standard_name': None, 'long_name': None, 'units': None, 'attributes': None, 'cell_methods': [], 'dim_coords_and_dims': [], 'aux_coords_and_dims': []} def _check(self, request_warning=False, value=10, factor=1): # Prepare the arguments. series = mock.sentinel.satelliteSeries number = mock.sentinel.satelliteNumber instrument = mock.sentinel.instrumentType rt_coord = mock.sentinel.observation_time section = {'NB': 1, 'satelliteSeries': series, 'satelliteNumber': number, 'instrumentType': instrument, 'scaleFactorOfCentralWaveNumber': factor, 'scaledValueOfCentralWaveNumber': value} metadata = deepcopy(self.metadata) this = 'iris.fileformats.grib._load_convert.options' with mock.patch(this, warn_on_unsupported=request_warning): # The call being tested. product_definition_template_31(section, metadata, rt_coord) # Check the result. def unscale(v, f): return v / 10.0 ** f expected = deepcopy(self.metadata) coord = AuxCoord(series, long_name='satellite_series') expected['aux_coords_and_dims'].append((coord, None)) coord = AuxCoord(number, long_name='satellite_number') expected['aux_coords_and_dims'].append((coord, None)) coord = AuxCoord(instrument, long_name='instrument_type') expected['aux_coords_and_dims'].append((coord, None)) standard_name = 'sensor_band_central_radiation_wavenumber' coord = AuxCoord(unscale(value, factor), standard_name=standard_name, units='m-1') expected['aux_coords_and_dims'].append((coord, None)) expected['aux_coords_and_dims'].append((rt_coord, None)) self.assertEqual(metadata, expected) if request_warning: warn_msgs = [arg[1][0] for arg in warnings.warn.mock_calls] expected_msgs = ['type of generating process', 'observation generating process identifier'] for emsg in expected_msgs: matches = [wmsg for wmsg in warn_msgs if emsg in wmsg] self.assertEqual(len(matches), 1) warn_msgs.remove(matches[0]) else: self.assertEqual(len(warnings.warn.mock_calls), 0) def test_pdt_no_warn(self): self._check(request_warning=False) def test_pdt_warn(self): self._check(request_warning=True) def test_wavelength_array(self): value = np.array([1, 10, 100, 1000]) for i in range(value.size): factor = np.ones(value.shape) * i self._check(value=value, factor=factor) if __name__ == '__main__': tests.main()
lgpl-3.0
beedesk/django-tastypie
tests/core/tests/http.py
10
1911
# Basically just a sanity check to make sure things don't change from underneath us. from django.test import TestCase from tastypie.http import HttpAccepted, HttpBadRequest, HttpConflict,\ HttpCreated, HttpGone, HttpMethodNotAllowed, HttpNoContent, HttpNotFound,\ HttpNotImplemented, HttpNotModified, HttpSeeOther, HttpTooManyRequests,\ HttpUnauthorized class HttpTestCase(TestCase): def test_various_statuses(self): created = HttpCreated(location='http://example.com/thingy/1/') self.assertEqual(created.status_code, 201) self.assertEqual(created['Location'], 'http://example.com/thingy/1/') # Regression. created_2 = HttpCreated() self.assertEqual(created_2.status_code, 201) self.assertEqual(created_2['Location'], '') accepted = HttpAccepted() self.assertEqual(accepted.status_code, 202) no_content = HttpNoContent() self.assertEqual(no_content.status_code, 204) see_other = HttpSeeOther() self.assertEqual(see_other.status_code, 303) not_modified = HttpNotModified() self.assertEqual(not_modified.status_code, 304) bad_request = HttpBadRequest() self.assertEqual(bad_request.status_code, 400) unauthorized = HttpUnauthorized() self.assertEqual(unauthorized.status_code, 401) not_found = HttpNotFound() self.assertEqual(not_found.status_code, 404) not_allowed = HttpMethodNotAllowed() self.assertEqual(not_allowed.status_code, 405) conflict = HttpConflict() self.assertEqual(conflict.status_code, 409) gone = HttpGone() self.assertEqual(gone.status_code, 410) toomanyrequests = HttpTooManyRequests() self.assertEqual(toomanyrequests.status_code, 429) not_implemented = HttpNotImplemented() self.assertEqual(not_implemented.status_code, 501)
bsd-3-clause
exsodus3249/kite
src/back/tests/test_maildir.py
2
1429
import kite.maildir import unittest import types mockdata = {"from": {"address": "gerard", "name": ""}, "subject": "test", "contents": "empty", "to": "gerard", "date": "November 13, 2007"} class EmptyObject(object): """Empty class used by mocks. Required because python doesn't let us add attributes to an empty object()""" pass class MockMailItem(object): def __init__(self): self.fp = EmptyObject() self.fp.read = types.MethodType(lambda self: mockdata["contents"], self.fp) def getheaders(self, header): hd = header.lower() if hd in mockdata: return (mockdata[hd], "Nulltuple") class MockMailDir(object): def __init__(self): self.mi = MockMailItem() def iteritems(self): return [("randomId", self.mi)] def get(self, id): if id == "randomId": return self.mi # FIXME: write a better test #class TestMailDir(unittest.TestCase): # def test_extract_email(self): # mi = MockMailItem() # self.assertEqual(kite.maildir.extract_email(mi), mockdata) # # def test_get_emails(self): # md = MockMailDir() # parsedMaildir = kite.maildir.get_emails(md) # self.assertEqual(len(parsedMaildir), 1) # # def test_get_email(self): # md = MockMailDir() # parsedEmail = kite.maildir.get_email(md, "randomId") # self.assertEqual(parsedEmail, mockdata)
bsd-3-clause
KhasMek/kernel_matricom_mx2
tools/perf/python/twatch.py
3213
1338
#! /usr/bin/python # -*- python -*- # -*- coding: utf-8 -*- # twatch - Experimental use of the perf python interface # Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com> # # This application is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; version 2. # # This application 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. import perf def main(): cpus = perf.cpu_map() threads = perf.thread_map() evsel = perf.evsel(task = 1, comm = 1, mmap = 0, wakeup_events = 1, sample_period = 1, sample_id_all = 1, sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU | perf.SAMPLE_TID) evsel.open(cpus = cpus, threads = threads); evlist = perf.evlist(cpus, threads) evlist.add(evsel) evlist.mmap() while True: evlist.poll(timeout = -1) for cpu in cpus: event = evlist.read_on_cpu(cpu) if not event: continue print "cpu: %2d, pid: %4d, tid: %4d" % (event.sample_cpu, event.sample_pid, event.sample_tid), print event if __name__ == '__main__': main()
gpl-2.0
IanSav/enigma2
lib/python/Plugins/Extensions/DVDBurn/TitleProperties.py
2
7963
from Screens.Screen import Screen from Components.ActionMap import ActionMap from Components.Sources.List import List from Components.Sources.StaticText import StaticText from Components.Pixmap import Pixmap from enigma import ePicLoad from Components.config import config, getConfigListEntry, ConfigInteger from Components.ConfigList import ConfigListScreen from Components.AVSwitch import AVSwitch import DVDTitle class TitleProperties(Screen,ConfigListScreen): skin = """ <screen name="TitleProperties" position="center,center" size="560,445" title="Properties of current title" > <ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/blue.png" position="420,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;19" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;19" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;19" halign="center" valign="center" backgroundColor="#a08500" transparent="1" /> <widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;19" halign="center" valign="center" backgroundColor="#18188b" transparent="1" /> <widget source="serviceinfo" render="Label" position="10,46" size="350,144" font="Regular;18" /> <widget name="thumbnail" position="370,46" size="180,144" alphatest="on" /> <widget name="config" position="10,206" size="540,228" scrollbarMode="showOnDemand" /> </screen>""" def __init__(self, session, parent, project, title_idx): Screen.__init__(self, session) self.parent = parent self.project = project self.title_idx = title_idx self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("OK")) self["key_yellow"] = StaticText(_("Edit title")) self["key_blue"] = StaticText() self["serviceinfo"] = StaticText() self["thumbnail"] = Pixmap() self.picload = ePicLoad() self.picload.PictureData.get().append(self.paintThumbPixmapCB) self.properties = project.titles[title_idx].properties ConfigListScreen.__init__(self, []) self.properties.crop = DVDTitle.ConfigFixedText("crop") self.properties.autochapter.addNotifier(self.initConfigList) self.properties.aspect.addNotifier(self.initConfigList) for audiotrack in self.properties.audiotracks: audiotrack.active.addNotifier(self.initConfigList) self["setupActions"] = ActionMap(["SetupActions", "ColorActions"], { "green": self.exit, "red": self.cancel, "yellow": self.editTitle, "cancel": self.cancel, "ok": self.ok, }, -2) self.onShown.append(self.update) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(_("Properties of current title")) def initConfigList(self, element=None): try: self.properties.position = ConfigInteger(default = self.title_idx+1, limits = (1, len(self.project.titles))) title = self.project.titles[self.title_idx] self.list = [] self.list.append(getConfigListEntry("DVD " + _("Track"), self.properties.position)) self.list.append(getConfigListEntry("DVD " + _("Title"), self.properties.menutitle)) self.list.append(getConfigListEntry("DVD " + _("Description"), self.properties.menusubtitle)) if config.usage.setup_level.index >= 2: # expert+ for audiotrack in self.properties.audiotracks: DVB_aud = audiotrack.DVB_lang.getValue() or audiotrack.pid.getValue() self.list.append(getConfigListEntry(_("Burn audio track (%s)") % DVB_aud, audiotrack.active)) if audiotrack.active.getValue(): self.list.append(getConfigListEntry(_("Audio track (%s) format") % DVB_aud, audiotrack.format)) self.list.append(getConfigListEntry(_("Audio track (%s) language") % DVB_aud, audiotrack.language)) self.list.append(getConfigListEntry("DVD " + _("Aspect ratio"), self.properties.aspect)) if self.properties.aspect.getValue() == "16:9": self.list.append(getConfigListEntry("DVD " + "widescreen", self.properties.widescreen)) else: self.list.append(getConfigListEntry("DVD " + "widescreen", self.properties.crop)) if len(title.chaptermarks) == 0: self.list.append(getConfigListEntry(_("Auto chapter split every ? minutes (0=never)"), self.properties.autochapter)) infotext = "DVB " + _("Title") + ': ' + title.DVBname + "\n" + _("Description") + ': ' + title.DVBdescr + "\n" + _("Channel") + ': ' + title.DVBchannel + '\n' + _("Start time") + title.formatDVDmenuText(": $D.$M.$Y, $T\n", self.title_idx+1) chaptermarks = title.getChapterMarks(template="$h:$m:$s") chapters_count = len(chaptermarks) if chapters_count >= 1: infotext += str(chapters_count+1) + ' ' + _("chapters") + ': ' infotext += ' / '.join(chaptermarks) self["serviceinfo"].setText(infotext) self["config"].setList(self.list) except AttributeError: pass def editTitle(self): self.parent.editTitle() def update(self): print "[onShown]" self.initConfigList() self.loadThumb() def loadThumb(self): thumbfile = self.project.titles[self.title_idx].inputfile.rsplit('.',1)[0] + ".png" sc = AVSwitch().getFramebufferScale() self.picload.setPara((self["thumbnail"].instance.size().width(), self["thumbnail"].instance.size().height(), sc[0], sc[1], False, 1, "#00000000")) self.picload.startDecode(thumbfile) def paintThumbPixmapCB(self, picInfo=None): ptr = self.picload.getData() if ptr is not None: self["thumbnail"].instance.setPixmap(ptr.__deref__()) def changedConfigList(self): self.initConfigList() def exit(self): self.applySettings() self.close() def applySettings(self): for x in self["config"].list: x[1].save() current_pos = self.title_idx+1 new_pos = self.properties.position.getValue() if new_pos != current_pos: print "title got repositioned from ", current_pos, "to", new_pos swaptitle = self.project.titles.pop(current_pos-1) self.project.titles.insert(new_pos-1, swaptitle) def ok(self): #key = self.keydict[self["config"].getCurrent()[1]] #if key in self.project.filekeys: #self.session.openWithCallback(self.FileBrowserClosed, FileBrowser, key, self.settings) pass def cancel(self): self.close() from Tools.ISO639 import LanguageCodes class LanguageChoices(): def __init__(self): from Components.Language import language as syslanguage syslang = syslanguage.getLanguage()[:2] self.langdict = { } self.choices = [] for key, val in LanguageCodes.iteritems(): if len(key) == 2: self.langdict[key] = val[0] for key, val in self.langdict.iteritems(): if key not in (syslang, 'en'): self.langdict[key] = val self.choices.append((key, val)) self.choices.sort() self.choices.insert(0,("nolang", ("unspecified"))) self.choices.insert(1,(syslang, self.langdict[syslang])) if syslang != "en": self.choices.insert(2,("en", self.langdict["en"])) def getLanguage(self, DVB_lang): DVB_lang = DVB_lang.lower() for word in ("stereo", "audio", "description", "2ch", "dolby digital"): DVB_lang = DVB_lang.replace(word,"").strip() for key, val in LanguageCodes.iteritems(): if DVB_lang.find(key.lower()) == 0: if len(key) == 2: return key else: DVB_lang = (LanguageCodes[key])[0] elif DVB_lang.find(val[0].lower()) > -1: if len(key) == 2: return key else: DVB_lang = (LanguageCodes[key])[0] for key, val in self.langdict.iteritems(): if val == DVB_lang: return key return "nolang" languageChoices = LanguageChoices()
gpl-2.0
mauricioabreu/speakerfight
deck/models.py
1
12968
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ValidationError from django.core.mail import send_mail from django.core.urlresolvers import reverse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db import models, transaction from django.db.models import Count from django.db.models.aggregates import Sum from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from django.template.loader import render_to_string from django.utils.translation import ugettext as _ from django.utils import timezone, six from django.utils.encoding import python_2_unicode_compatible from django_extensions.db.fields import AutoSlugField from allauth.account.signals import user_signed_up from textwrap import dedent from jury.models import Jury class DeckBaseManager(models.QuerySet): def cached_authors(self): return super(DeckBaseManager, self).select_related('author') def published_ones(self): return self.cached_authors().filter(is_published=True) def upcoming(self, published_only=True): return self.filter(due_date__gte=timezone.now(), is_published=published_only) def order_by_never_voted(self, user_id): if self.model != Proposal: raise AttributeError( "%s object has no attribute %s" % ( self.model, 'order_by_never_voted')) order_by_criteria = dedent(""" SELECT 1 FROM deck_vote WHERE deck_vote.user_id = %s AND deck_vote.proposal_id = deck_proposal.activity_ptr_id LIMIT 1 """) new_ordering = ['-never_voted'] if settings.DATABASES['default'].get('ENGINE') == 'django.db.backends.sqlite3': new_ordering = ['never_voted'] new_ordering.extend(Proposal._meta.ordering) return self.extra( select=dict(never_voted=order_by_criteria % user_id), order_by=new_ordering ) @python_2_unicode_compatible class DeckBaseModel(models.Model): title = models.CharField(_('Title'), max_length=200) slug = AutoSlugField(populate_from='title', overwrite=True, max_length=200, unique=True, db_index=True) description = models.TextField( _('Description'), max_length=10000, blank=True) created_at = models.DateTimeField(_('Created At'), auto_now_add=True) is_published = models.BooleanField(_('Publish'), default=True) # relations author = models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='%(class)ss') # managers objects = DeckBaseManager.as_manager() class Meta: abstract = True def __str__(self): return six.text_type(self.title) @python_2_unicode_compatible class Vote(models.Model): ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4) VOTE_TITLES = dict( angry=_('Angry'), sad=_('Sad'), sleepy=_('Sleepy'), happy=_('Happy'), laughing=_('Laughing') ) VOTE_RATES = ((ANGRY, 'angry'), (SAD, 'sad'), (SLEEPY, 'sleepy'), (HAPPY, 'happy'), (LAUGHING, 'laughing')) rate = models.SmallIntegerField(_('Rate Index'), null=True, blank=True, choices=VOTE_RATES) # relations proposal = models.ForeignKey(to='deck.Proposal', related_name='votes') user = models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='votes') class Meta: verbose_name = _('Vote') verbose_name_plural = _('Votes') unique_together = (('proposal', 'user'),) def __str__(self): return six.text_type("{0.user}: {0.rate} in {0.proposal}".format(self)) def save(self, *args, **kwargs): validation_message = None user_is_in_jury = self.proposal.event.jury.users.filter( pk=self.user.pk).exists() if (self.user.is_superuser or user_is_in_jury): pass elif self.user == self.proposal.author: validation_message = _(u'You cannot Rate your own proposals.') elif not self.proposal.event.allow_public_voting: validation_message = _(u"Proposal doesn't accept Public Voting.") if validation_message: raise ValidationError(_(validation_message)) return super(Vote, self).save(*args, **kwargs) class Activity(DeckBaseModel): PROPOSAL = 'proposal' WORKSHOP = 'workshop' OPENNING = 'openning' COFFEEBREAK = 'coffee-break' LUNCH = 'lunch' LIGHTNINGTALKS = 'lightning-talks' ENDING = 'ending' ACTIVITY_TYPES = ( (PROPOSAL, _('Proposal')), (WORKSHOP, _('Workshop')), (OPENNING, _('Openning')), (COFFEEBREAK, _('Coffee Break')), (LUNCH, _('Lunch')), (LIGHTNINGTALKS, _('Lightning Talks')), (ENDING, _('Ending')), ) start_timetable = models.TimeField( _('Start Timetable'), null=True, blank=False) end_timetable = models.TimeField( _('End Timetable'), null=True, blank=False) track_order = models.SmallIntegerField(_('Order'), null=True, blank=True) activity_type = models.CharField( _('Type'), choices=ACTIVITY_TYPES, default=PROPOSAL, max_length=50) # relations track = models.ForeignKey(to='deck.Track', related_name='activities', null=True, blank=True) class Meta: ordering = ('track_order', 'start_timetable', 'pk') verbose_name = _('Activity') verbose_name_plural = _('Activities') @property def timetable(self): if all([self.start_timetable is None, self.end_timetable is None]): return '--:--' return '{0} - {1}'.format( self.start_timetable.strftime('%H:%M'), self.end_timetable.strftime('%H:%M') ) class Proposal(Activity): is_approved = models.BooleanField(_('Is approved'), default=False) more_information = models.TextField( _('More information'), max_length=10000, null=True, blank=True) # relations event = models.ForeignKey(to='deck.Event', related_name='proposals') class Meta: ordering = ['title'] verbose_name = _('Proposal') verbose_name_plural = _('Proposals') def save(self, *args, **kwargs): if not self.pk and self.event.due_date_is_passed: raise ValidationError( _("This Event doesn't accept Proposals anymore.")) return super(Proposal, self).save(*args, **kwargs) @property def get_rate(self): rate = None try: rate = self.votes__rate__sum except AttributeError: rate = self.votes.aggregate(Sum('rate'))['rate__sum'] finally: return rate or 0 def rate(self, user, rate): rate_int = [r[0] for r in Vote.VOTE_RATES if rate in r][0] with transaction.atomic(): self.votes.update_or_create(user=user, defaults={'rate': rate_int}) def user_already_voted(self, user): if isinstance(user, AnonymousUser): return False return self.votes.filter(user=user).exists() def user_can_vote(self, user): can_vote = False if self.author == user and not self.event.author == user: pass elif self.event.allow_public_voting: can_vote = True elif user.is_superuser: can_vote = True elif self.event.jury.users.filter(pk=user.pk).exists(): can_vote = True return can_vote def user_can_approve(self, user): can_approve = False if user.is_superuser: can_approve = True elif self.event.jury.users.filter(pk=user.pk).exists(): can_approve = True return can_approve def get_absolute_url(self): return reverse('view_event', kwargs={'slug': self.event.slug}) + \ '#' + self.slug def approve(self): if self.is_approved: raise ValidationError(_("This Proposal was already approved.")) self.is_approved = True self.save() def disapprove(self): if not self.is_approved: raise ValidationError(_("This Proposal was already disapproved.")) self.is_approved = False self.save() @python_2_unicode_compatible class Track(models.Model): title = models.CharField(_('Title'), max_length=200) slug = AutoSlugField(populate_from='title', overwrite=True, max_length=200, unique=True, db_index=True) # relations event = models.ForeignKey(to='deck.Event', related_name='tracks') class Meta: verbose_name = _('Track') verbose_name_plural = _('Tracks') def __str__(self): return six.text_type('Track for: "%s"' % self.event.title) @property def proposals(self): return Proposal.objects.filter( pk__in=self.activities.values_list('pk', flat=True) ) class Event(DeckBaseModel): allow_public_voting = models.BooleanField(_('Allow Public Voting'), default=True) due_date = models.DateTimeField(null=False, blank=False) slots = models.SmallIntegerField(_('Slots'), default=10) # relations jury = models.OneToOneField(to='jury.Jury', related_name='event', null=True, blank=True) anonymous_voting = models.BooleanField( _('Anonymous Voting?'), default=False) class Meta: ordering = ['-due_date', '-created_at'] verbose_name = _('Event') verbose_name_plural = _('Events') @property def due_date_is_passed(self): return timezone.now() > self.due_date @property def due_date_is_close(self): if self.due_date_is_passed: return False return timezone.now() > self.due_date - timezone.timedelta(days=7) def get_absolute_url(self): return reverse('view_event', kwargs={'slug': self.slug}) def user_can_see_proposals(self, user): can_see_proposals = False if user.is_superuser or self.author == user: can_see_proposals = True elif self.allow_public_voting: can_see_proposals = True elif (not user.is_anonymous() and self.jury.users.filter(pk=user.pk).exists()): can_see_proposals = True return can_see_proposals def get_proposers_count(self): return self.proposals.values_list( 'author', flat=True).distinct().count() def get_votes_count(self): return self.proposals.values_list('votes', flat=True).count() def get_votes_to_export(self): return self.proposals.values( 'id', 'title', 'author__username', 'author__email' ).annotate( Sum('votes__rate') ).annotate(Count('votes')) def get_schedule(self): schedule = Activity.objects.filter(track__event=self)\ .cached_authors()\ .annotate(Sum('proposal__votes__rate'))\ .extra(select=dict(track_isnull='track_id IS NULL'))\ .order_by('track_isnull', 'track_order', '-proposal__votes__rate__sum') return schedule def get_not_approved_schedule(self): return self.proposals\ .cached_authors()\ .filter( models.Q(is_approved=False) | models.Q(track__isnull=True)) @receiver(user_signed_up) def send_welcome_mail(request, user, **kwargs): if not settings.SEND_NOTIFICATIONS: return message = render_to_string('mailing/welcome.txt') subject = _(u'Welcome') recipients = [user.email] send_mail(subject, message, settings.NO_REPLY_EMAIL, recipients) @receiver(post_save, sender=Event) def create_initial_jury(sender, instance, signal, created, **kwargs): if not created: return jury = Jury() jury.save() jury.users.add(instance.author) instance.jury = jury instance.save() @receiver(post_save, sender=Event) def create_initial_track(sender, instance, signal, created, **kwargs): if not created: return Track.objects.create(event=instance) @receiver(post_delete, sender=Proposal) def send_proposal_deleted_mail(sender, instance, **kwargs): if not settings.SEND_NOTIFICATIONS: return context = {'event_title': instance.event.title, 'proposal_title': instance.title} message = render_to_string('mailing/jury_deleted_proposal.txt', context) subject = _(u'Proposal from %s just got deleted' % instance.event.title) recipients = instance.event.jury.users.values_list('email', flat=True) send_mail(subject, message, settings.NO_REPLY_EMAIL, recipients)
mit
40223117cda/w16cdaa
static/Brython3.1.0-20150301-090019/Lib/multiprocessing/dummy/__init__.py
693
4380
# # Support for the API of the multiprocessing package using threads # # multiprocessing/dummy/__init__.py # # Copyright (c) 2006-2008, R Oudkerk # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of author nor the names of any contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. # __all__ = [ 'Process', 'current_process', 'active_children', 'freeze_support', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event', 'Barrier', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue' ] # # Imports # import threading import sys import weakref #brython fix me #import array from multiprocessing.dummy.connection import Pipe from threading import Lock, RLock, Semaphore, BoundedSemaphore from threading import Event, Condition, Barrier from queue import Queue # # # class DummyProcess(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): threading.Thread.__init__(self, group, target, name, args, kwargs) self._pid = None self._children = weakref.WeakKeyDictionary() self._start_called = False self._parent = current_process() def start(self): assert self._parent is current_process() self._start_called = True if hasattr(self._parent, '_children'): self._parent._children[self] = None threading.Thread.start(self) @property def exitcode(self): if self._start_called and not self.is_alive(): return 0 else: return None # # # Process = DummyProcess current_process = threading.current_thread current_process()._children = weakref.WeakKeyDictionary() def active_children(): children = current_process()._children for p in list(children): if not p.is_alive(): children.pop(p, None) return list(children) def freeze_support(): pass # # # class Namespace(object): def __init__(self, **kwds): self.__dict__.update(kwds) def __repr__(self): items = list(self.__dict__.items()) temp = [] for name, value in items: if not name.startswith('_'): temp.append('%s=%r' % (name, value)) temp.sort() return 'Namespace(%s)' % str.join(', ', temp) dict = dict list = list #brython fix me #def Array(typecode, sequence, lock=True): # return array.array(typecode, sequence) class Value(object): def __init__(self, typecode, value, lock=True): self._typecode = typecode self._value = value def _get(self): return self._value def _set(self, value): self._value = value value = property(_get, _set) def __repr__(self): return '<%r(%r, %r)>'%(type(self).__name__,self._typecode,self._value) def Manager(): return sys.modules[__name__] def shutdown(): pass def Pool(processes=None, initializer=None, initargs=()): from multiprocessing.pool import ThreadPool return ThreadPool(processes, initializer, initargs) JoinableQueue = Queue
gpl-3.0
ryfeus/lambda-packs
Tensorflow_LightGBM_Scipy_nightly/source/tensorflow/python/estimator/inputs/queues/feeding_queue_runner.py
123
6899
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A `QueueRunner` that takes a feed function as an argument.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import threading from tensorflow.python.framework import errors from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import queue_runner as qr class _FeedingQueueRunner(qr.QueueRunner): """A queue runner that allows the feeding of values such as numpy arrays.""" def __init__(self, queue=None, enqueue_ops=None, close_op=None, cancel_op=None, feed_fns=None, queue_closed_exception_types=None): """Initialize the queue runner. For further documentation, see `queue_runner.py`. Note that `FeedingQueueRunner` does not support construction from protobuffer nor serialization to protobuffer. Args: queue: A `Queue`. enqueue_ops: List of enqueue ops to run in threads later. close_op: Op to close the queue. Pending enqueue ops are preserved. cancel_op: Op to close the queue and cancel pending enqueue ops. feed_fns: a list of functions that return a dictionary mapping fed `Tensor`s to values. Must be the same length as `enqueue_ops`. queue_closed_exception_types: Optional tuple of Exception types that indicate that the queue has been closed when raised during an enqueue operation. Defaults to `(tf.errors.OutOfRangeError, tf.errors.CancelledError)`. Raises: ValueError: `feed_fns` is not `None` and has different length than `enqueue_ops`. """ if queue_closed_exception_types is None: queue_closed_exception_types = ( errors.OutOfRangeError, errors.CancelledError) super(_FeedingQueueRunner, self).__init__( queue, enqueue_ops, close_op, cancel_op, queue_closed_exception_types=queue_closed_exception_types) if feed_fns is None: self._feed_fns = [None for _ in enqueue_ops] else: if len(feed_fns) != len(enqueue_ops): raise ValueError( "If feed_fns is not None, it must have the same length as " "enqueue_ops.") self._feed_fns = feed_fns # pylint: disable=broad-except def _run(self, sess, enqueue_op, feed_fn, coord=None): """Execute the enqueue op in a loop, close the queue in case of error. Args: sess: A `Session`. enqueue_op: The `Operation` to run. feed_fn: the feed function to pass to `sess.run`. coord: Optional `Coordinator` object for reporting errors and checking for stop conditions. """ # TODO(jamieas): Reduce code duplication with `QueueRunner`. if coord: coord.register_thread(threading.current_thread()) decremented = False try: while True: if coord and coord.should_stop(): break try: feed_dict = None if feed_fn is None else feed_fn() sess.run(enqueue_op, feed_dict=feed_dict) except (errors.OutOfRangeError, errors.CancelledError): # This exception indicates that a queue was closed. with self._lock: self._runs_per_session[sess] -= 1 decremented = True if self._runs_per_session[sess] == 0: try: sess.run(self._close_op) except Exception as e: # Intentionally ignore errors from close_op. logging.vlog(1, "Ignored exception: %s", str(e)) return except Exception as e: # This catches all other exceptions. if coord: coord.request_stop(e) else: logging.error("Exception in QueueRunner: %s", str(e)) with self._lock: self._exceptions_raised.append(e) raise finally: # Make sure we account for all terminations: normal or errors. if not decremented: with self._lock: self._runs_per_session[sess] -= 1 def create_threads(self, sess, coord=None, daemon=False, start=False): """Create threads to run the enqueue ops for the given session. This method requires a session in which the graph was launched. It creates a list of threads, optionally starting them. There is one thread for each op passed in `enqueue_ops`. The `coord` argument is an optional coordinator, that the threads will use to terminate together and report exceptions. If a coordinator is given, this method starts an additional thread to close the queue when the coordinator requests a stop. If previously created threads for the given session are still running, no new threads will be created. Args: sess: A `Session`. coord: Optional `Coordinator` object for reporting errors and checking stop conditions. daemon: Boolean. If `True` make the threads daemon threads. start: Boolean. If `True` starts the threads. If `False` the caller must call the `start()` method of the returned threads. Returns: A list of threads. """ with self._lock: try: if self._runs_per_session[sess] > 0: # Already started: no new threads to return. return [] except KeyError: # We haven't seen this session yet. pass self._runs_per_session[sess] = len(self._enqueue_ops) self._exceptions_raised = [] ret_threads = [threading.Thread(target=self._run, args=(sess, op, feed_fn, coord)) for op, feed_fn in zip(self._enqueue_ops, self._feed_fns)] if coord: ret_threads.append(threading.Thread(target=self._close_on_stop, args=(sess, self._cancel_op, coord))) for t in ret_threads: if daemon: t.daemon = True if start: t.start() return ret_threads def _init_from_proto(self, queue_runner_def): raise NotImplementedError( "{} does not support initialization from proto.".format(type( self).__name__)) def to_proto(self): raise NotImplementedError( "{} does not support serialization to proto.".format(type( self).__name__))
mit
jnerin/ansible
lib/ansible/plugins/connection/jail.py
52
8087
# Based on local.py by Michael DeHaan <michael.dehaan@gmail.com> # and chroot.py by Maykel Moya <mmoya@speedyrails.com> # Copyright (c) 2013, Michael Scherer <misc@zarb.org> # Copyright (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ author: Ansible Core Team connection: jail short_description: Run tasks in jails description: - Run commands or put/fetch files to an existing jail version_added: "2.0" options: remote_addr: description: - Path to the jail default: inventory_hostname vars: - name: ansible_host - name: ansible_jail_host remote_user: description: - User to execute as inside the jail vars: - name: ansible_user - name: ansible_jail_user """ import distutils.spawn import os import os.path import subprocess import traceback from ansible.errors import AnsibleError from ansible.module_utils.six.moves import shlex_quote from ansible.module_utils._text import to_bytes, to_native, to_text from ansible.plugins.connection import ConnectionBase, BUFSIZE try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() class Connection(ConnectionBase): ''' Local BSD Jail based connections ''' modified_jailname_key = 'conn_jail_name' transport = 'jail' # Pipelining may work. Someone needs to test by setting this to True and # having pipelining=True in their ansible.cfg has_pipelining = True # Some become_methods may work in v2 (sudo works for other chroot-based # plugins while su seems to be failing). If some work, check chroot.py to # see how to disable just some methods. become_methods = frozenset() def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.jail = self._play_context.remote_addr if self.modified_jailname_key in kwargs: self.jail = kwargs[self.modified_jailname_key] if os.geteuid() != 0: raise AnsibleError("jail connection requires running as root") self.jls_cmd = self._search_executable('jls') self.jexec_cmd = self._search_executable('jexec') if self.jail not in self.list_jails(): raise AnsibleError("incorrect jail name %s" % self.jail) @staticmethod def _search_executable(executable): cmd = distutils.spawn.find_executable(executable) if not cmd: raise AnsibleError("%s command not found in PATH" % executable) return cmd def list_jails(self): p = subprocess.Popen([self.jls_cmd, '-q', 'name'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() return to_text(stdout, errors='surrogate_or_strict').split() def _connect(self): ''' connect to the jail; nothing to do here ''' super(Connection, self)._connect() if not self._connected: display.vvv(u"ESTABLISH JAIL CONNECTION FOR USER: {0}".format(self._play_context.remote_user), host=self.jail) self._connected = True def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE): ''' run a command on the jail. This is only needed for implementing put_file() get_file() so that we don't have to read the whole file into memory. compared to exec_command() it looses some niceties like being able to return the process's exit code immediately. ''' local_cmd = [self.jexec_cmd] set_env = '' if self._play_context.remote_user is not None: local_cmd += ['-U', self._play_context.remote_user] # update HOME since -U does not update the jail environment set_env = 'HOME=~' + self._play_context.remote_user + ' ' local_cmd += [self.jail, self._play_context.executable, '-c', set_env + cmd] display.vvv("EXEC %s" % (local_cmd,), host=self.jail) local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd] p = subprocess.Popen(local_cmd, shell=False, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return p def exec_command(self, cmd, in_data=None, sudoable=False): ''' run a command on the jail ''' super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) p = self._buffered_exec_command(cmd) stdout, stderr = p.communicate(in_data) return (p.returncode, stdout, stderr) def _prefix_login_path(self, remote_path): ''' Make sure that we put files into a standard path If a path is relative, then we need to choose where to put it. ssh chooses $HOME but we aren't guaranteed that a home dir will exist in any given chroot. So for now we're choosing "/" instead. This also happens to be the former default. Can revisit using $HOME instead if it's a problem ''' if not remote_path.startswith(os.path.sep): remote_path = os.path.join(os.path.sep, remote_path) return os.path.normpath(remote_path) def put_file(self, in_path, out_path): ''' transfer a file from local to jail ''' super(Connection, self).put_file(in_path, out_path) display.vvv("PUT %s TO %s" % (in_path, out_path), host=self.jail) out_path = shlex_quote(self._prefix_login_path(out_path)) try: with open(to_bytes(in_path, errors='surrogate_or_strict'), 'rb') as in_file: try: p = self._buffered_exec_command('dd of=%s bs=%s' % (out_path, BUFSIZE), stdin=in_file) except OSError: raise AnsibleError("jail connection requires dd command in the jail") try: stdout, stderr = p.communicate() except: traceback.print_exc() raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path)) if p.returncode != 0: raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, to_native(stdout), to_native(stderr))) except IOError: raise AnsibleError("file or module does not exist at: %s" % in_path) def fetch_file(self, in_path, out_path): ''' fetch a file from jail to local ''' super(Connection, self).fetch_file(in_path, out_path) display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self.jail) in_path = shlex_quote(self._prefix_login_path(in_path)) try: p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE)) except OSError: raise AnsibleError("jail connection requires dd command in the jail") with open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb+') as out_file: try: chunk = p.stdout.read(BUFSIZE) while chunk: out_file.write(chunk) chunk = p.stdout.read(BUFSIZE) except: traceback.print_exc() raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path)) stdout, stderr = p.communicate() if p.returncode != 0: raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, to_native(stdout), to_native(stderr))) def close(self): ''' terminate the connection; nothing to do here ''' super(Connection, self).close() self._connected = False
gpl-3.0
martbhell/wasthereannhlgamelastnight
src/lib/requests/adapters.py
79
21344
# -*- coding: utf-8 -*- """ requests.adapters ~~~~~~~~~~~~~~~~~ This module contains the transport adapters that Requests uses to define and maintain connections. """ import os.path import socket from urllib3.poolmanager import PoolManager, proxy_from_url from urllib3.response import HTTPResponse from urllib3.util import parse_url from urllib3.util import Timeout as TimeoutSauce from urllib3.util.retry import Retry from urllib3.exceptions import ClosedPoolError from urllib3.exceptions import ConnectTimeoutError from urllib3.exceptions import HTTPError as _HTTPError from urllib3.exceptions import MaxRetryError from urllib3.exceptions import NewConnectionError from urllib3.exceptions import ProxyError as _ProxyError from urllib3.exceptions import ProtocolError from urllib3.exceptions import ReadTimeoutError from urllib3.exceptions import SSLError as _SSLError from urllib3.exceptions import ResponseError from urllib3.exceptions import LocationValueError from .models import Response from .compat import urlparse, basestring from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths, get_encoding_from_headers, prepend_scheme_if_needed, get_auth_from_url, urldefragauth, select_proxy) from .structures import CaseInsensitiveDict from .cookies import extract_cookies_to_jar from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError, ProxyError, RetryError, InvalidSchema, InvalidProxyURL, InvalidURL) from .auth import _basic_auth_str try: from urllib3.contrib.socks import SOCKSProxyManager except ImportError: def SOCKSProxyManager(*args, **kwargs): raise InvalidSchema("Missing dependencies for SOCKS support.") DEFAULT_POOLBLOCK = False DEFAULT_POOLSIZE = 10 DEFAULT_RETRIES = 0 DEFAULT_POOL_TIMEOUT = None class BaseAdapter(object): """The Base Transport Adapter""" def __init__(self): super(BaseAdapter, self).__init__() def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. """ raise NotImplementedError def close(self): """Cleans up adapter specific items.""" raise NotImplementedError class HTTPAdapter(BaseAdapter): """The built-in HTTP Adapter for urllib3. Provides a general-case interface for Requests sessions to contact HTTP and HTTPS urls by implementing the Transport Adapter interface. This class will usually be created by the :class:`Session <Session>` class under the covers. :param pool_connections: The number of urllib3 connection pools to cache. :param pool_maxsize: The maximum number of connections to save in the pool. :param max_retries: The maximum number of retries each connection should attempt. Note, this applies only to failed DNS lookups, socket connections and connection timeouts, never to requests where data has made it to the server. By default, Requests does not retry failed connections. If you need granular control over the conditions under which we retry a request, import urllib3's ``Retry`` class and pass that instead. :param pool_block: Whether the connection pool should block for connections. Usage:: >>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a) """ __attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize', '_pool_block'] def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK): if max_retries == DEFAULT_RETRIES: self.max_retries = Retry(0, read=False) else: self.max_retries = Retry.from_int(max_retries) self.config = {} self.proxy_manager = {} super(HTTPAdapter, self).__init__() self._pool_connections = pool_connections self._pool_maxsize = pool_maxsize self._pool_block = pool_block self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) def __getstate__(self): return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state): # Can't handle by adding 'proxy_manager' to self.__attrs__ because # self.poolmanager uses a lambda function, which isn't pickleable. self.proxy_manager = {} self.config = {} for attr, value in state.items(): setattr(self, attr, value) self.init_poolmanager(self._pool_connections, self._pool_maxsize, block=self._pool_block) def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs): """Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The maximum number of connections to save in the pool. :param block: Block when no free connections are available. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. """ # save these values for pickling self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, strict=True, **pool_kwargs) def proxy_manager_for(self, proxy, **proxy_kwargs): """Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: urllib3.ProxyManager """ if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] elif proxy.lower().startswith('socks'): username, password = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager( proxy, username=username, password=password, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs ) else: proxy_headers = self.proxy_headers(proxy) manager = self.proxy_manager[proxy] = proxy_from_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs) return manager def cert_verify(self, conn, url, verify, cert): """Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :param verify: Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: The SSL certificate to verify. """ if url.lower().startswith('https') and verify: cert_loc = None # Allow self-specified cert location. if verify is not True: cert_loc = verify if not cert_loc: cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) if not cert_loc or not os.path.exists(cert_loc): raise IOError("Could not find a suitable TLS CA certificate bundle, " "invalid path: {}".format(cert_loc)) conn.cert_reqs = 'CERT_REQUIRED' if not os.path.isdir(cert_loc): conn.ca_certs = cert_loc else: conn.ca_cert_dir = cert_loc else: conn.cert_reqs = 'CERT_NONE' conn.ca_certs = None conn.ca_cert_dir = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert conn.key_file = None if conn.cert_file and not os.path.exists(conn.cert_file): raise IOError("Could not find the TLS certificate file, " "invalid path: {}".format(conn.cert_file)) if conn.key_file and not os.path.exists(conn.key_file): raise IOError("Could not find the TLS key file, " "invalid path: {}".format(conn.key_file)) def build_response(self, req, resp): """Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response """ response = Response() # Fallback to None if there's no status_code, for whatever reason. response.status_code = getattr(resp, 'status', None) # Make headers case-insensitive. response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {})) # Set encoding. response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, bytes): response.url = req.url.decode('utf-8') else: response.url = req.url # Add new cookies from the server. extract_cookies_to_jar(response.cookies, req, resp) # Give the Response some context. response.request = req response.connection = self return response def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool """ proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL("Please check proxy URL. It is malformed" " and could be missing the host.") proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear() def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = (proxy and scheme != 'https') using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith('socks') url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url def add_headers(self, request, **kwargs): """Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send(). """ pass def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict """ headers = {} username, password = get_auth_from_url(proxy) if username: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return headers def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response """ try: conn = self.get_connection(request.url, proxies) except LocationValueError as e: raise InvalidURL(e, request=request) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies) chunked = not (request.body is None or 'Content-Length' in request.headers) if isinstance(timeout, tuple): try: connect, read = timeout timeout = TimeoutSauce(connect=connect, read=read) except ValueError as e: # this may raise a string formatting error. err = ("Invalid timeout {}. Pass a (connect, read) " "timeout tuple, or a single float to set " "both timeouts to the same value".format(timeout)) raise ValueError(err) elif isinstance(timeout, TimeoutSauce): pass else: timeout = TimeoutSauce(connect=timeout, read=timeout) try: if not chunked: resp = conn.urlopen( method=request.method, url=url, body=request.body, headers=request.headers, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, retries=self.max_retries, timeout=timeout ) # Send the request. else: if hasattr(conn, 'proxy_pool'): conn = conn.proxy_pool low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT) try: low_conn.putrequest(request.method, url, skip_accept_encoding=True) for header, value in request.headers.items(): low_conn.putheader(header, value) low_conn.endheaders() for i in request.body: low_conn.send(hex(len(i))[2:].encode('utf-8')) low_conn.send(b'\r\n') low_conn.send(i) low_conn.send(b'\r\n') low_conn.send(b'0\r\n\r\n') # Receive the response from the server try: # For Python 2.7, use buffering of HTTP responses r = low_conn.getresponse(buffering=True) except TypeError: # For compatibility with Python 3.3+ r = low_conn.getresponse() resp = HTTPResponse.from_httplib( r, pool=conn, connection=low_conn, preload_content=False, decode_content=False ) except: # If we hit any problems here, clean up the connection. # Then, reraise so that we can handle the actual exception. low_conn.close() raise except (ProtocolError, socket.error) as err: raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): # TODO: Remove this in 3.0.0: see #2811 if not isinstance(e.reason, NewConnectionError): raise ConnectTimeout(e, request=request) if isinstance(e.reason, ResponseError): raise RetryError(e, request=request) if isinstance(e.reason, _ProxyError): raise ProxyError(e, request=request) if isinstance(e.reason, _SSLError): # This branch is for urllib3 v1.22 and later. raise SSLError(e, request=request) raise ConnectionError(e, request=request) except ClosedPoolError as e: raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): # This branch is for urllib3 versions earlier than v1.22 raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) else: raise return self.build_response(request, resp)
mit
hn8841182/2015cd_0505
static/Brython3.1.1-20150328-091302/Lib/_csv.py
639
21705
"""CSV parsing and writing. [Copied from PyPy https://bitbucket-assetroot.s3.amazonaws.com/pypy/pypy/1400171824.19/641/_csv.py?Signature=cc%2Bc8m06cBMbsxt2e15XXXUDACk%3D&Expires=1404136251&AWSAccessKeyId=0EMWEFSGA12Z1HF1TZ82 and adapted to Python 3 syntax for Brython] This module provides classes that assist in the reading and writing of Comma Separated Value (CSV) files, and implements the interface described by PEP 305. Although many CSV files are simple to parse, the format is not formally defined by a stable specification and is subtle enough that parsing lines of a CSV file with something like line.split(\",\") is bound to fail. The module supports three basic APIs: reading, writing, and registration of dialects. DIALECT REGISTRATION: Readers and writers support a dialect argument, which is a convenient handle on a group of settings. When the dialect argument is a string, it identifies one of the dialects previously registered with the module. If it is a class or instance, the attributes of the argument are used as the settings for the reader or writer: class excel: delimiter = ',' quotechar = '\"' escapechar = None doublequote = True skipinitialspace = False lineterminator = '\\r\\n' quoting = QUOTE_MINIMAL SETTINGS: * quotechar - specifies a one-character string to use as the quoting character. It defaults to '\"'. * delimiter - specifies a one-character string to use as the field separator. It defaults to ','. * skipinitialspace - specifies how to interpret whitespace which immediately follows a delimiter. It defaults to False, which means that whitespace immediately following a delimiter is part of the following field. * lineterminator - specifies the character sequence which should terminate rows. * quoting - controls when quotes should be generated by the writer. It can take on any of the following module constants: csv.QUOTE_MINIMAL means only when required, for example, when a field contains either the quotechar or the delimiter csv.QUOTE_ALL means that quotes are always placed around fields. csv.QUOTE_NONNUMERIC means that quotes are always placed around fields which do not parse as integers or floating point numbers. csv.QUOTE_NONE means that quotes are never placed around fields. * escapechar - specifies a one-character string used to escape the delimiter when quoting is set to QUOTE_NONE. * doublequote - controls the handling of quotes inside fields. When True, two consecutive quotes are interpreted as one during read, and when writing, each quote character embedded in the data is written as two quotes. """ __version__ = "1.0" QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) _dialects = {} _field_limit = 128 * 1024 # max parsed field size class Error(Exception): pass class Dialect(object): """CSV dialect The Dialect type records CSV parsing and generation options.""" __slots__ = ["_delimiter", "_doublequote", "_escapechar", "_lineterminator", "_quotechar", "_quoting", "_skipinitialspace", "_strict"] def __new__(cls, dialect, **kwargs): for name in kwargs: if '_' + name not in Dialect.__slots__: raise TypeError("unexpected keyword argument '%s'" % (name,)) if dialect is not None: if isinstance(dialect, str): dialect = get_dialect(dialect) # Can we reuse this instance? if (isinstance(dialect, Dialect) and all(value is None for value in kwargs.values())): return dialect self = object.__new__(cls) def set_char(x): if x is None: return None if isinstance(x, str) and len(x) <= 1: return x raise TypeError("%r must be a 1-character string" % (name,)) def set_str(x): if isinstance(x, str): return x raise TypeError("%r must be a string" % (name,)) def set_quoting(x): if x in range(4): return x raise TypeError("bad 'quoting' value") attributes = {"delimiter": (',', set_char), "doublequote": (True, bool), "escapechar": (None, set_char), "lineterminator": ("\r\n", set_str), "quotechar": ('"', set_char), "quoting": (QUOTE_MINIMAL, set_quoting), "skipinitialspace": (False, bool), "strict": (False, bool), } # Copy attributes notset = object() for name in Dialect.__slots__: name = name[1:] value = notset if name in kwargs: value = kwargs[name] elif dialect is not None: value = getattr(dialect, name, notset) # mapping by name: (default, converter) if value is notset: value = attributes[name][0] if name == 'quoting' and not self.quotechar: value = QUOTE_NONE else: converter = attributes[name][1] if converter: value = converter(value) setattr(self, '_' + name, value) if not self.delimiter: raise TypeError("delimiter must be set") if self.quoting != QUOTE_NONE and not self.quotechar: raise TypeError("quotechar must be set if quoting enabled") if not self.lineterminator: raise TypeError("lineterminator must be set") return self delimiter = property(lambda self: self._delimiter) doublequote = property(lambda self: self._doublequote) escapechar = property(lambda self: self._escapechar) lineterminator = property(lambda self: self._lineterminator) quotechar = property(lambda self: self._quotechar) quoting = property(lambda self: self._quoting) skipinitialspace = property(lambda self: self._skipinitialspace) strict = property(lambda self: self._strict) def _call_dialect(dialect_inst, kwargs): return Dialect(dialect_inst, **kwargs) def register_dialect(name, dialect=None, **kwargs): """Create a mapping from a string name to a dialect class. dialect = csv.register_dialect(name, dialect)""" if not isinstance(name, str): raise TypeError("dialect name must be a string or unicode") dialect = _call_dialect(dialect, kwargs) _dialects[name] = dialect def unregister_dialect(name): """Delete the name/dialect mapping associated with a string name.\n csv.unregister_dialect(name)""" try: del _dialects[name] except KeyError: raise Error("unknown dialect") def get_dialect(name): """Return the dialect instance associated with name. dialect = csv.get_dialect(name)""" try: return _dialects[name] except KeyError: raise Error("unknown dialect") def list_dialects(): """Return a list of all know dialect names names = csv.list_dialects()""" return list(_dialects) class Reader(object): """CSV reader Reader objects are responsible for reading and parsing tabular data in CSV format.""" (START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, EAT_CRNL) = range(8) def __init__(self, iterator, dialect=None, **kwargs): self.dialect = _call_dialect(dialect, kwargs) # null characters are not allowed to be in the string so we can use # it as a fall back self._delimiter = self.dialect.delimiter if self.dialect.delimiter else '\0' self._quotechar = self.dialect.quotechar if self.dialect.quotechar else '\0' self._escapechar = self.dialect.escapechar if self.dialect.escapechar else '\0' self._doublequote = self.dialect.doublequote self._quoting = self.dialect.quoting self._skipinitialspace = self.dialect.skipinitialspace self._strict = self.dialect.strict self.input_iter = iter(iterator) self.line_num = 0 self._parse_reset() def _parse_reset(self): self.field = '' self.fields = [] self.state = self.START_RECORD self.numeric_field = False def __iter__(self): return self def __next__(self): self._parse_reset() while True: try: line = next(self.input_iter) except StopIteration: # End of input OR exception if len(self.field) > 0: raise Error("newline inside string") raise self.line_num += 1 if '\0' in line: raise Error("line contains NULL byte") self._parse_process_char(line) self._parse_eol() if self.state == self.START_RECORD: break fields = self.fields self.fields = [] return fields def _parse_process_char(self, line): pos = 0 while pos < len(line): if self.state == self.IN_FIELD: # in unquoted field and have already found one character when starting the field pos2 = pos while pos2 < len(line): if line[pos2] == '\n' or line[pos2] == '\r': # end of line - return [fields] if pos2 > pos: self._parse_add_str(line[pos:pos2]) pos = pos2 self._parse_save_field() self.state = self.EAT_CRNL break elif line[pos2] == self._escapechar[0]: # possible escaped character if pos2 > pos: self._parse_add_str(line[pos:pos2]) pos = pos2 self.state = self.ESCAPED_CHAR break elif line[pos2] == self._delimiter[0]: # save field - wait for new field if pos2 > pos: self._parse_add_str(line[pos:pos2]) pos = pos2 self._parse_save_field() self.state = self.START_FIELD break # normal character - save in field pos2 += 1 else: if pos2 > pos: self._parse_add_str(line[pos:pos2]) pos = pos2 continue elif self.state == self.START_RECORD: if line[pos] == '\n' or line[pos] == '\r': self.state = self.EAT_CRNL else: self.state = self.START_FIELD # restart process continue elif self.state == self.START_FIELD: if line[pos] == '\n' or line[pos] == '\r': # save empty field - return [fields] self._parse_save_field() self.state = self.EAT_CRNL elif (line[pos] == self._quotechar[0] and self._quoting != QUOTE_NONE): # start quoted field self.state = self.IN_QUOTED_FIELD elif line[pos] == self._escapechar[0]: # possible escaped character self.state = self.ESCAPED_CHAR elif self._skipinitialspace and line[pos] == ' ': # ignore space at start of field pass elif line[pos] == self._delimiter[0]: # save empty field self._parse_save_field() else: # begin new unquoted field if self._quoting == QUOTE_NONNUMERIC: self.numeric_field = True self.state = self.IN_FIELD continue elif self.state == self.ESCAPED_CHAR: self._parse_add_char(line[pos]) self.state = self.IN_FIELD elif self.state == self.IN_QUOTED_FIELD: if line[pos] == self._escapechar: # possible escape character self.state = self.ESCAPE_IN_QUOTED_FIELD elif (line[pos] == self._quotechar and self._quoting != QUOTE_NONE): if self._doublequote: # doublequote; " represented by "" self.state = self.QUOTE_IN_QUOTED_FIELD else: #end of quote part of field self.state = self.IN_FIELD else: # normal character - save in field self._parse_add_char(line[pos]) elif self.state == self.ESCAPE_IN_QUOTED_FIELD: self._parse_add_char(line[pos]) self.state = self.IN_QUOTED_FIELD elif self.state == self.QUOTE_IN_QUOTED_FIELD: # doublequote - seen a quote in a quoted field if (line[pos] == self._quotechar and self._quoting != QUOTE_NONE): # save "" as " self._parse_add_char(line[pos]) self.state = self.IN_QUOTED_FIELD elif line[pos] == self._delimiter[0]: # save field - wait for new field self._parse_save_field() self.state = self.START_FIELD elif line[pos] == '\r' or line[pos] == '\n': # end of line - return [fields] self._parse_save_field() self.state = self.EAT_CRNL elif not self._strict: self._parse_add_char(line[pos]) self.state = self.IN_FIELD else: raise Error("'%c' expected after '%c'" % (self._delimiter, self._quotechar)) elif self.state == self.EAT_CRNL: if line[pos] == '\r' or line[pos] == '\n': pass else: raise Error("new-line character seen in unquoted field - " "do you need to open the file " "in universal-newline mode?") else: raise RuntimeError("unknown state: %r" % (self.state,)) pos += 1 def _parse_eol(self): if self.state == self.EAT_CRNL: self.state = self.START_RECORD elif self.state == self.START_RECORD: # empty line - return [] pass elif self.state == self.IN_FIELD: # in unquoted field # end of line - return [fields] self._parse_save_field() self.state = self.START_RECORD elif self.state == self.START_FIELD: # save empty field - return [fields] self._parse_save_field() self.state = self.START_RECORD elif self.state == self.ESCAPED_CHAR: self._parse_add_char('\n') self.state = self.IN_FIELD elif self.state == self.IN_QUOTED_FIELD: pass elif self.state == self.ESCAPE_IN_QUOTED_FIELD: self._parse_add_char('\n') self.state = self.IN_QUOTED_FIELD elif self.state == self.QUOTE_IN_QUOTED_FIELD: # end of line - return [fields] self._parse_save_field() self.state = self.START_RECORD else: raise RuntimeError("unknown state: %r" % (self.state,)) def _parse_save_field(self): field, self.field = self.field, '' if self.numeric_field: self.numeric_field = False field = float(field) self.fields.append(field) def _parse_add_char(self, c): if len(self.field) + 1 > _field_limit: raise Error("field larget than field limit (%d)" % (_field_limit)) self.field += c def _parse_add_str(self, s): if len(self.field) + len(s) > _field_limit: raise Error("field larget than field limit (%d)" % (_field_limit)) self.field += s class Writer(object): """CSV writer Writer objects are responsible for generating tabular data in CSV format from sequence input.""" def __init__(self, file, dialect=None, **kwargs): if not (hasattr(file, 'write') and callable(file.write)): raise TypeError("argument 1 must have a 'write' method") self.writeline = file.write self.dialect = _call_dialect(dialect, kwargs) def _join_reset(self): self.rec = [] self.num_fields = 0 def _join_append(self, field, quoted, quote_empty): dialect = self.dialect # If this is not the first field we need a field separator if self.num_fields > 0: self.rec.append(dialect.delimiter) if dialect.quoting == QUOTE_NONE: need_escape = tuple(dialect.lineterminator) + ( dialect.escapechar, # escapechar always first dialect.delimiter, dialect.quotechar) else: for c in tuple(dialect.lineterminator) + ( dialect.delimiter, dialect.escapechar): if c and c in field: quoted = True need_escape = () if dialect.quotechar in field: if dialect.doublequote: field = field.replace(dialect.quotechar, dialect.quotechar * 2) quoted = True else: need_escape = (dialect.quotechar,) for c in need_escape: if c and c in field: if not dialect.escapechar: raise Error("need to escape, but no escapechar set") field = field.replace(c, dialect.escapechar + c) # If field is empty check if it needs to be quoted if field == '' and quote_empty: if dialect.quoting == QUOTE_NONE: raise Error("single empty field record must be quoted") quoted = 1 if quoted: field = dialect.quotechar + field + dialect.quotechar self.rec.append(field) self.num_fields += 1 def writerow(self, row): dialect = self.dialect try: rowlen = len(row) except TypeError: raise Error("sequence expected") # join all fields in internal buffer self._join_reset() for field in row: quoted = False if dialect.quoting == QUOTE_NONNUMERIC: try: float(field) except: quoted = True # This changed since 2.5: # quoted = not isinstance(field, (int, long, float)) elif dialect.quoting == QUOTE_ALL: quoted = True if field is None: self._join_append("", quoted, rowlen == 1) else: self._join_append(str(field), quoted, rowlen == 1) # add line terminator self.rec.append(dialect.lineterminator) self.writeline(''.join(self.rec)) def writerows(self, rows): for row in rows: self.writerow(row) def reader(*args, **kwargs): """ csv_reader = reader(iterable [, dialect='excel'] [optional keyword args]) for row in csv_reader: process(row) The "iterable" argument can be any object that returns a line of input for each iteration, such as a file object or a list. The optional \"dialect\" parameter is discussed below. The function also accepts optional keyword arguments which override settings provided by the dialect. The returned object is an iterator. Each iteration returns a row of the CSV file (which can span multiple input lines)""" return Reader(*args, **kwargs) def writer(*args, **kwargs): """ csv_writer = csv.writer(fileobj [, dialect='excel'] [optional keyword args]) for row in sequence: csv_writer.writerow(row) [or] csv_writer = csv.writer(fileobj [, dialect='excel'] [optional keyword args]) csv_writer.writerows(rows) The \"fileobj\" argument can be any object that supports the file API.""" return Writer(*args, **kwargs) undefined = object() def field_size_limit(limit=undefined): """Sets an upper limit on parsed fields. csv.field_size_limit([limit]) Returns old limit. If limit is not given, no new limit is set and the old limit is returned""" global _field_limit old_limit = _field_limit if limit is not undefined: if not isinstance(limit, (int, long)): raise TypeError("int expected, got %s" % (limit.__class__.__name__,)) _field_limit = limit return old_limit
agpl-3.0
mrquim/repository.mrquim
script.module.pycryptodome/lib/Crypto/SelfTest/Hash/common.py
5
8596
# -*- coding: utf-8 -*- # # SelfTest/Hash/common.py: Common code for Crypto.SelfTest.Hash # # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net> # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== """Self-testing for PyCrypto hash modules""" import sys import unittest import binascii import Crypto.Hash from Crypto.Util.py3compat import b, tobytes from Crypto.Util.strxor import strxor_c class HashDigestSizeSelfTest(unittest.TestCase): def __init__(self, hashmod, description, expected): unittest.TestCase.__init__(self) self.hashmod = hashmod self.expected = expected self.description = description def shortDescription(self): return self.description def runTest(self): self.failUnless(hasattr(self.hashmod, "digest_size")) self.assertEquals(self.hashmod.digest_size, self.expected) h = self.hashmod.new() self.failUnless(hasattr(h, "digest_size")) self.assertEquals(h.digest_size, self.expected) class HashSelfTest(unittest.TestCase): def __init__(self, hashmod, description, expected, input): unittest.TestCase.__init__(self) self.hashmod = hashmod self.expected = expected self.input = input self.description = description def shortDescription(self): return self.description def runTest(self): h = self.hashmod.new() h.update(self.input) out1 = binascii.b2a_hex(h.digest()) out2 = h.hexdigest() h = self.hashmod.new(self.input) out3 = h.hexdigest() out4 = binascii.b2a_hex(h.digest()) # PY3K: hexdigest() should return str(), and digest() bytes self.assertEqual(self.expected, out1) # h = .new(); h.update(data); h.digest() if sys.version_info[0] == 2: self.assertEqual(self.expected, out2) # h = .new(); h.update(data); h.hexdigest() self.assertEqual(self.expected, out3) # h = .new(data); h.hexdigest() else: self.assertEqual(self.expected.decode(), out2) # h = .new(); h.update(data); h.hexdigest() self.assertEqual(self.expected.decode(), out3) # h = .new(data); h.hexdigest() self.assertEqual(self.expected, out4) # h = .new(data); h.digest() # Verify that the .new() method produces a fresh hash object, except # for MD5 and SHA1, which are hashlib objects. (But test any .new() # method that does exist.) if self.hashmod.__name__ not in ('Crypto.Hash.MD5', 'Crypto.Hash.SHA1') or hasattr(h, 'new'): h2 = h.new() h2.update(self.input) out5 = binascii.b2a_hex(h2.digest()) self.assertEqual(self.expected, out5) class HashTestOID(unittest.TestCase): def __init__(self, hashmod, oid): unittest.TestCase.__init__(self) self.hashmod = hashmod self.oid = oid def runTest(self): h = self.hashmod.new() self.assertEqual(h.oid, self.oid) class HashDocStringTest(unittest.TestCase): def __init__(self, hashmod): unittest.TestCase.__init__(self) self.hashmod = hashmod def runTest(self): docstring = self.hashmod.__doc__ self.assert_(hasattr(self.hashmod, '__doc__')) self.assert_(isinstance(self.hashmod.__doc__, str)) class GenericHashConstructorTest(unittest.TestCase): def __init__(self, hashmod): unittest.TestCase.__init__(self) self.hashmod = hashmod def runTest(self): obj1 = self.hashmod.new("foo") obj2 = self.hashmod.new() obj3 = Crypto.Hash.new(obj1.name, "foo") obj4 = Crypto.Hash.new(obj1.name) obj5 = Crypto.Hash.new(obj1, "foo") obj6 = Crypto.Hash.new(obj1) self.assert_(isinstance(self.hashmod, obj1)) self.assert_(isinstance(self.hashmod, obj2)) self.assert_(isinstance(self.hashmod, obj3)) self.assert_(isinstance(self.hashmod, obj4)) self.assert_(isinstance(self.hashmod, obj5)) self.assert_(isinstance(self.hashmod, obj6)) class MACSelfTest(unittest.TestCase): def __init__(self, module, description, result, input, key, params): unittest.TestCase.__init__(self) self.module = module self.result = result self.input = input self.key = key self.params = params self.description = description def shortDescription(self): return self.description def runTest(self): key = binascii.a2b_hex(b(self.key)) data = binascii.a2b_hex(b(self.input)) # Strip whitespace from the expected string (which should be in lowercase-hex) expected = b("".join(self.result.split())) h = self.module.new(key, **self.params) h.update(data) out1_bin = h.digest() out1 = binascii.b2a_hex(h.digest()) out2 = h.hexdigest() # Verify that correct MAC does not raise any exception h.hexverify(out1) h.verify(out1_bin) # Verify that incorrect MAC does raise ValueError exception wrong_mac = strxor_c(out1_bin, 255) self.assertRaises(ValueError, h.verify, wrong_mac) self.assertRaises(ValueError, h.hexverify, "4556") h = self.module.new(key, data, **self.params) out3 = h.hexdigest() out4 = binascii.b2a_hex(h.digest()) # Test .copy() h2 = h.copy() h.update(b("blah blah blah")) # Corrupt the original hash object out5 = binascii.b2a_hex(h2.digest()) # The copied hash object should return the correct result # PY3K: Check that hexdigest() returns str and digest() returns bytes if sys.version_info[0] > 2: self.assertTrue(isinstance(h.digest(), type(b("")))) self.assertTrue(isinstance(h.hexdigest(), type(""))) # PY3K: Check that .hexverify() accepts bytes or str if sys.version_info[0] > 2: h.hexverify(h.hexdigest()) h.hexverify(h.hexdigest().encode('ascii')) # PY3K: hexdigest() should return str, and digest() should return bytes self.assertEqual(expected, out1) if sys.version_info[0] == 2: self.assertEqual(expected, out2) self.assertEqual(expected, out3) else: self.assertEqual(expected.decode(), out2) self.assertEqual(expected.decode(), out3) self.assertEqual(expected, out4) self.assertEqual(expected, out5) def make_hash_tests(module, module_name, test_data, digest_size, oid=None): tests = [] for i in range(len(test_data)): row = test_data[i] (expected, input) = map(tobytes,row[0:2]) if len(row) < 3: description = repr(input) else: description = row[2] name = "%s #%d: %s" % (module_name, i+1, description) tests.append(HashSelfTest(module, name, expected, input)) name = "%s #%d: digest_size" % (module_name, i+1) tests.append(HashDigestSizeSelfTest(module, name, digest_size)) if oid is not None: tests.append(HashTestOID(module, oid)) tests.append(HashDocStringTest(module)) if getattr(module, 'name', None) is not None: tests.append(GenericHashConstructorTest(module)) return tests def make_mac_tests(module, module_name, test_data): tests = [] for i in range(len(test_data)): row = test_data[i] (key, data, results, description, params) = row name = "%s #%d: %s" % (module_name, i+1, description) tests.append(MACSelfTest(module, name, results, data, key, params)) return tests # vim:set ts=4 sw=4 sts=4 expandtab:
gpl-2.0
qiankunshe/sky_engine
sky/tools/webkitpy/common/net/networktransaction.py
190
2926
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging import time import urllib2 _log = logging.getLogger(__name__) class NetworkTimeout(Exception): def __str__(self): return 'NetworkTimeout' class NetworkTransaction(object): def __init__(self, initial_backoff_seconds=10, grown_factor=1.5, timeout_seconds=(10 * 60), convert_404_to_None=False): self._initial_backoff_seconds = initial_backoff_seconds self._grown_factor = grown_factor self._timeout_seconds = timeout_seconds self._convert_404_to_None = convert_404_to_None def run(self, request): self._total_sleep = 0 self._backoff_seconds = self._initial_backoff_seconds while True: try: return request() except urllib2.HTTPError, e: if self._convert_404_to_None and e.code == 404: return None self._check_for_timeout() _log.warn("Received HTTP status %s loading \"%s\". Retrying in %s seconds..." % (e.code, e.filename, self._backoff_seconds)) self._sleep() def _check_for_timeout(self): if self._total_sleep + self._backoff_seconds > self._timeout_seconds: raise NetworkTimeout() def _sleep(self): time.sleep(self._backoff_seconds) self._total_sleep += self._backoff_seconds self._backoff_seconds *= self._grown_factor
bsd-3-clause
bdh1011/wau
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
238
13310
""" Wheel command-line utility. """ import os import hashlib import sys import json import wheel.paths from glob import iglob from .. import signatures from ..util import (urlsafe_b64decode, urlsafe_b64encode, native, binary, matches_requirement) from ..install import WheelFile def require_pkgresources(name): try: import pkg_resources except ImportError: raise RuntimeError("'{0}' needs pkg_resources (part of setuptools).".format(name)) import argparse class WheelError(Exception): pass # For testability def get_keyring(): try: from ..signatures import keys import keyring except ImportError: raise WheelError("Install wheel[signatures] (requires keyring, pyxdg) for signatures.") return keys.WheelKeys, keyring def keygen(get_keyring=get_keyring): """Generate a public/private key pair.""" WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wk = WheelKeys().load() keypair = ed25519ll.crypto_sign_keypair() vk = native(urlsafe_b64encode(keypair.vk)) sk = native(urlsafe_b64encode(keypair.sk)) kr = keyring.get_keyring() kr.set_password("wheel", vk, sk) sys.stdout.write("Created Ed25519 keypair with vk={0}\n".format(vk)) if isinstance(kr, keyring.backends.file.BaseKeyring): sys.stdout.write("in {0}\n".format(kr.file_path)) else: sys.stdout.write("in %r\n" % kr.__class__) sk2 = kr.get_password('wheel', vk) if sk2 != sk: raise WheelError("Keyring is broken. Could not retrieve secret key.") sys.stdout.write("Trusting {0} to sign and verify all packages.\n".format(vk)) wk.add_signer('+', vk) wk.trust('+', vk) wk.save() def sign(wheelfile, replace=False, get_keyring=get_keyring): """Sign a wheel""" WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wf = WheelFile(wheelfile, append=True) wk = WheelKeys().load() name = wf.parsed_filename.group('name') sign_with = wk.signers(name)[0] sys.stdout.write("Signing {0} with {1}\n".format(name, sign_with[1])) vk = sign_with[1] kr = keyring.get_keyring() sk = kr.get_password('wheel', vk) keypair = ed25519ll.Keypair(urlsafe_b64decode(binary(vk)), urlsafe_b64decode(binary(sk))) record_name = wf.distinfo_name + '/RECORD' sig_name = wf.distinfo_name + '/RECORD.jws' if sig_name in wf.zipfile.namelist(): raise WheelError("Wheel is already signed.") record_data = wf.zipfile.read(record_name) payload = {"hash":"sha256=" + native(urlsafe_b64encode(hashlib.sha256(record_data).digest()))} sig = signatures.sign(payload, keypair) wf.zipfile.writestr(sig_name, json.dumps(sig, sort_keys=True)) wf.zipfile.close() def unsign(wheelfile): """ Remove RECORD.jws from a wheel by truncating the zip file. RECORD.jws must be at the end of the archive. The zip file must be an ordinary archive, with the compressed files and the directory in the same order, and without any non-zip content after the truncation point. """ import wheel.install vzf = wheel.install.VerifyingZipFile(wheelfile, "a") info = vzf.infolist() if not (len(info) and info[-1].filename.endswith('/RECORD.jws')): raise WheelError("RECORD.jws not found at end of archive.") vzf.pop() vzf.close() def verify(wheelfile): """Verify a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel's own unpack/install commands verify the manifest against the signature and file contents. """ wf = WheelFile(wheelfile) sig_name = wf.distinfo_name + '/RECORD.jws' sig = json.loads(native(wf.zipfile.open(sig_name).read())) verified = signatures.verify(sig) sys.stderr.write("Signatures are internally consistent.\n") sys.stdout.write(json.dumps(verified, indent=2)) sys.stdout.write('\n') def unpack(wheelfile, dest='.'): """Unpack a wheel. Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} is the package name and {ver} its version. :param wheelfile: The path to the wheel. :param dest: Destination directory (default to current directory). """ wf = WheelFile(wheelfile) namever = wf.parsed_filename.group('namever') destination = os.path.join(dest, namever) sys.stderr.write("Unpacking to: %s\n" % (destination)) wf.zipfile.extractall(destination) wf.zipfile.close() def install(requirements, requirements_file=None, wheel_dirs=None, force=False, list_files=False, dry_run=False): """Install wheels. :param requirements: A list of requirements or wheel files to install. :param requirements_file: A file containing requirements to install. :param wheel_dirs: A list of directories to search for wheels. :param force: Install a wheel file even if it is not compatible. :param list_files: Only list the files to install, don't install them. :param dry_run: Do everything but the actual install. """ # If no wheel directories specified, use the WHEELPATH environment # variable, or the current directory if that is not set. if not wheel_dirs: wheelpath = os.getenv("WHEELPATH") if wheelpath: wheel_dirs = wheelpath.split(os.pathsep) else: wheel_dirs = [ os.path.curdir ] # Get a list of all valid wheels in wheel_dirs all_wheels = [] for d in wheel_dirs: for w in os.listdir(d): if w.endswith('.whl'): wf = WheelFile(os.path.join(d, w)) if wf.compatible: all_wheels.append(wf) # If there is a requirements file, add it to the list of requirements if requirements_file: # If the file doesn't exist, search for it in wheel_dirs # This allows standard requirements files to be stored with the # wheels. if not os.path.exists(requirements_file): for d in wheel_dirs: name = os.path.join(d, requirements_file) if os.path.exists(name): requirements_file = name break with open(requirements_file) as fd: requirements.extend(fd) to_install = [] for req in requirements: if req.endswith('.whl'): # Explicitly specified wheel filename if os.path.exists(req): wf = WheelFile(req) if wf.compatible or force: to_install.append(wf) else: msg = ("{0} is not compatible with this Python. " "--force to install anyway.".format(req)) raise WheelError(msg) else: # We could search on wheel_dirs, but it's probably OK to # assume the user has made an error. raise WheelError("No such wheel file: {}".format(req)) continue # We have a requirement spec # If we don't have pkg_resources, this will raise an exception matches = matches_requirement(req, all_wheels) if not matches: raise WheelError("No match for requirement {}".format(req)) to_install.append(max(matches)) # We now have a list of wheels to install if list_files: sys.stdout.write("Installing:\n") if dry_run: return for wf in to_install: if list_files: sys.stdout.write(" {0}\n".format(wf.filename)) continue wf.install(force=force) wf.zipfile.close() def install_scripts(distributions): """ Regenerate the entry_points console_scripts for the named distribution. """ try: from setuptools.command import easy_install import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") for dist in distributions: pkg_resources_dist = pkg_resources.get_distribution(dist) install = wheel.paths.get_install_command(dist) command = easy_install.easy_install(install.distribution) command.args = ['wheel'] # dummy argument command.finalize_options() command.install_egg_scripts(pkg_resources_dist) def convert(installers, dest_dir, verbose): require_pkgresources('wheel convert') # Only support wheel convert if pkg_resources is present from ..wininst2wheel import bdist_wininst2wheel from ..egg2wheel import egg2wheel for pat in installers: for installer in iglob(pat): if os.path.splitext(installer)[1] == '.egg': conv = egg2wheel else: conv = bdist_wininst2wheel if verbose: sys.stdout.write("{0}... ".format(installer)) sys.stdout.flush() conv(installer, dest_dir) if verbose: sys.stdout.write("OK\n") def parser(): p = argparse.ArgumentParser() s = p.add_subparsers(help="commands") def keygen_f(args): keygen() keygen_parser = s.add_parser('keygen', help='Generate signing key') keygen_parser.set_defaults(func=keygen_f) def sign_f(args): sign(args.wheelfile) sign_parser = s.add_parser('sign', help='Sign wheel') sign_parser.add_argument('wheelfile', help='Wheel file') sign_parser.set_defaults(func=sign_f) def unsign_f(args): unsign(args.wheelfile) unsign_parser = s.add_parser('unsign', help=unsign.__doc__) unsign_parser.add_argument('wheelfile', help='Wheel file') unsign_parser.set_defaults(func=unsign_f) def verify_f(args): verify(args.wheelfile) verify_parser = s.add_parser('verify', help=verify.__doc__) verify_parser.add_argument('wheelfile', help='Wheel file') verify_parser.set_defaults(func=verify_f) def unpack_f(args): unpack(args.wheelfile, args.dest) unpack_parser = s.add_parser('unpack', help='Unpack wheel') unpack_parser.add_argument('--dest', '-d', help='Destination directory', default='.') unpack_parser.add_argument('wheelfile', help='Wheel file') unpack_parser.set_defaults(func=unpack_f) def install_f(args): install(args.requirements, args.requirements_file, args.wheel_dirs, args.force, args.list_files) install_parser = s.add_parser('install', help='Install wheels') install_parser.add_argument('requirements', nargs='*', help='Requirements to install.') install_parser.add_argument('--force', default=False, action='store_true', help='Install incompatible wheel files.') install_parser.add_argument('--wheel-dir', '-d', action='append', dest='wheel_dirs', help='Directories containing wheels.') install_parser.add_argument('--requirements-file', '-r', help="A file containing requirements to " "install.") install_parser.add_argument('--list', '-l', default=False, dest='list_files', action='store_true', help="List wheels which would be installed, " "but don't actually install anything.") install_parser.set_defaults(func=install_f) def install_scripts_f(args): install_scripts(args.distributions) install_scripts_parser = s.add_parser('install-scripts', help='Install console_scripts') install_scripts_parser.add_argument('distributions', nargs='*', help='Regenerate console_scripts for these distributions') install_scripts_parser.set_defaults(func=install_scripts_f) def convert_f(args): convert(args.installers, args.dest_dir, args.verbose) convert_parser = s.add_parser('convert', help='Convert egg or wininst to wheel') convert_parser.add_argument('installers', nargs='*', help='Installers to convert') convert_parser.add_argument('--dest-dir', '-d', default=os.path.curdir, help="Directory to store wheels (default %(default)s)") convert_parser.add_argument('--verbose', '-v', action='store_true') convert_parser.set_defaults(func=convert_f) def version_f(args): from .. import __version__ sys.stdout.write("wheel %s\n" % __version__) version_parser = s.add_parser('version', help='Print version and exit') version_parser.set_defaults(func=version_f) def help_f(args): p.print_help() help_parser = s.add_parser('help', help='Show this help') help_parser.set_defaults(func=help_f) return p def main(): p = parser() args = p.parse_args() if not hasattr(args, 'func'): p.print_help() else: # XXX on Python 3.3 we get 'args has no func' rather than short help. try: args.func(args) return 0 except WheelError as e: sys.stderr.write(e.message + "\n") return 1
mit
pistruiatul/hartapoliticii
python/src/ro/vivi/youtube_crawler/gdata/tlslite/utils/Cryptlib_TripleDES.py
359
1408
"""Cryptlib 3DES implementation.""" from cryptomath import * from TripleDES import * if cryptlibpyLoaded: def new(key, mode, IV): return Cryptlib_TripleDES(key, mode, IV) class Cryptlib_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "cryptlib") self.context = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_3DES) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_MODE, cryptlib_py.CRYPT_MODE_CBC) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key)) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_IV, IV) def __del__(self): cryptlib_py.cryptDestroyContext(self.context) def encrypt(self, plaintext): TripleDES.encrypt(self, plaintext) bytes = stringToBytes(plaintext) cryptlib_py.cryptEncrypt(self.context, bytes) return bytesToString(bytes) def decrypt(self, ciphertext): TripleDES.decrypt(self, ciphertext) bytes = stringToBytes(ciphertext) cryptlib_py.cryptDecrypt(self.context, bytes) return bytesToString(bytes)
agpl-3.0
thomas-bottesch/fcl
python/utils/create_pca_vectors_from_dataset.py
1
2284
from __future__ import print_function import fcl import os import time from os.path import abspath, join, dirname, isfile from fcl import kmeans from fcl.datasets import load_sector_dataset, load_usps_dataset from fcl.matrix.csr_matrix import get_csr_matrix_from_object, csr_matrix_to_libsvm_string from sklearn.decomposition import TruncatedSVD, PCA from scipy.sparse import csr_matrix from sklearn.datasets import dump_svmlight_file import numpy as np import argparse def get_pca_projection_csrmatrix(fcl_csr_input_matrix, component_ratio): n_components = int(fcl_csr_input_matrix.annz * component_ratio) p = TruncatedSVD(n_components = n_components) start = time.time() p.fit(fcl_csr_input_matrix.to_numpy()) # convert to millis fin = (time.time() - start) * 1000 (n_samples, n_dim) = fcl_csr_input_matrix.shape print("Truncated SVD took %.3fs to retrieve %s components for input_matrix with n_samples %d, n_dim %d" % (fin/1000.0, str(n_components), n_samples, n_dim)) return get_csr_matrix_from_object(p.components_) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Create a pca matrix from an input matrix with given component ratio.') parser.add_argument('path_input_dataset', type=str, help='Path to the input libsvm dataset') parser.add_argument('path_output_dataset', type=str, help='Path to the input libsvm dataset') parser.add_argument('--component_ratio', default=0.1, type=float, help='Percentage of the average non zero values of the input dataset to use as components.') args = parser.parse_args() if not isfile(args.path_input_dataset): raise Exception("Unable to find path_input_dataset: %s" % args.path_input_dataset) print("Loading data from %s" % args.path_input_dataset) fcl_mtrx_input_dataset = get_csr_matrix_from_object(args.path_input_dataset) print("Retrieving the pca projection matrix") pca_mtrx = get_pca_projection_csrmatrix(fcl_mtrx_input_dataset, args.component_ratio) print("Convert pca projection matrix to libsvm string") pca_mtrx_lsvm_str = csr_matrix_to_libsvm_string(pca_mtrx) print("Writing pca projection matrix libsvm string to file %s" % args.path_output_dataset) with open(args.path_output_dataset, 'w') as f: f.write(pca_mtrx_lsvm_str)
mit
ask/celery
celery/utils/__init__.py
2
5421
# -*- coding: utf-8 -*- """ celery.utils ~~~~~~~~~~~~ Utility functions. :copyright: (c) 2009 - 2012 by Ask Solem. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from __future__ import with_statement import operator import sys import threading import traceback import warnings from functools import partial, wraps from inspect import getargspec from pprint import pprint from celery.exceptions import CPendingDeprecationWarning, CDeprecationWarning from .compat import StringIO from .functional import noop PENDING_DEPRECATION_FMT = """ %(description)s is scheduled for deprecation in \ version %(deprecation)s and removal in version v%(removal)s. \ %(alternative)s """ DEPRECATION_FMT = """ %(description)s is deprecated and scheduled for removal in version %(removal)s. %(alternative)s """ def warn_deprecated(description=None, deprecation=None, removal=None, alternative=None): ctx = {"description": description, "deprecation": deprecation, "removal": removal, "alternative": alternative} if deprecation is not None: w = CPendingDeprecationWarning(PENDING_DEPRECATION_FMT % ctx) else: w = CDeprecationWarning(DEPRECATION_FMT % ctx) warnings.warn(w) def deprecated(description=None, deprecation=None, removal=None, alternative=None): def _inner(fun): @wraps(fun) def __inner(*args, **kwargs): from .imports import qualname warn_deprecated(description=description or qualname(fun), deprecation=deprecation, removal=removal, alternative=alternative) return fun(*args, **kwargs) return __inner return _inner def lpmerge(L, R): """In place left precedent dictionary merge. Keeps values from `L`, if the value in `R` is :const:`None`.""" set = L.__setitem__ [set(k, v) for k, v in R.iteritems() if v is not None] return L def is_iterable(obj): try: iter(obj) except TypeError: return False return True def fun_takes_kwargs(fun, kwlist=[]): """With a function, and a list of keyword arguments, returns arguments in the list which the function takes. If the object has an `argspec` attribute that is used instead of using the :meth:`inspect.getargspec` introspection. :param fun: The function to inspect arguments of. :param kwlist: The list of keyword arguments. Examples >>> def foo(self, x, y, logfile=None, loglevel=None): ... return x * y >>> fun_takes_kwargs(foo, ["logfile", "loglevel", "task_id"]) ["logfile", "loglevel"] >>> def foo(self, x, y, **kwargs): >>> fun_takes_kwargs(foo, ["logfile", "loglevel", "task_id"]) ["logfile", "loglevel", "task_id"] """ argspec = getattr(fun, "argspec", getargspec(fun)) args, _varargs, keywords, _defaults = argspec if keywords != None: return kwlist return filter(partial(operator.contains, args), kwlist) def isatty(fh): # Fixes bug with mod_wsgi: # mod_wsgi.Log object has no attribute isatty. return getattr(fh, "isatty", None) and fh.isatty() def cry(): # pragma: no cover """Return stacktrace of all active threads. From https://gist.github.com/737056 """ tmap = {} main_thread = None # get a map of threads by their ID so we can print their names # during the traceback dump for t in threading.enumerate(): if getattr(t, "ident", None): tmap[t.ident] = t else: main_thread = t out = StringIO() sep = "=" * 49 + "\n" for tid, frame in sys._current_frames().iteritems(): thread = tmap.get(tid, main_thread) if not thread: # skip old junk (left-overs from a fork) continue out.write("%s\n" % (thread.getName(), )) out.write(sep) traceback.print_stack(frame, file=out) out.write(sep) out.write("LOCAL VARIABLES\n") out.write(sep) pprint(frame.f_locals, stream=out) out.write("\n\n") return out.getvalue() def maybe_reraise(): """Reraise if an exception is currently being handled, or return otherwise.""" exc_info = sys.exc_info() try: if exc_info[2]: raise exc_info[0], exc_info[1], exc_info[2] finally: # see http://docs.python.org/library/sys.html#sys.exc_info del(exc_info) def strtobool(term, table={"false": False, "no": False, "0": False, "true": True, "yes": True, "1": True, "on": True, "off": False}): if isinstance(term, basestring): try: return table[term.lower()] except KeyError: raise TypeError("Can't coerce %r to type bool" % (term, )) return term # ------------------------------------------------------------------------ # # > XXX Compat from .log import LOG_LEVELS # noqa from .imports import ( # noqa qualname as get_full_cls_name, symbol_by_name as get_cls_by_name, instantiate, import_from_cwd ) from .functional import chunks, noop # noqa from kombu.utils import cached_property, kwdict, uuid # noqa gen_unique_id = uuid
bsd-3-clause
fbradyirl/home-assistant
homeassistant/components/fleetgo/device_tracker.py
4
2778
"""Support for FleetGO Platform.""" import logging import requests import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.device_tracker import PLATFORM_SCHEMA from homeassistant.const import CONF_USERNAME, CONF_PASSWORD from homeassistant.helpers.event import track_utc_time_change _LOGGER = logging.getLogger(__name__) CONF_CLIENT_ID = "client_id" CONF_CLIENT_SECRET = "client_secret" CONF_INCLUDE = "include" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_CLIENT_ID): cv.string, vol.Required(CONF_CLIENT_SECRET): cv.string, vol.Optional(CONF_INCLUDE, default=[]): vol.All(cv.ensure_list, [cv.string]), } ) def setup_scanner(hass, config: dict, see, discovery_info=None): """Set up the DeviceScanner and check if login is valid.""" scanner = FleetGoDeviceScanner(config, see) if not scanner.login(hass): _LOGGER.error("FleetGO authentication failed") return False return True class FleetGoDeviceScanner: """Define a scanner for the FleetGO platform.""" def __init__(self, config, see): """Initialize FleetGoDeviceScanner.""" from ritassist import API self._include = config.get(CONF_INCLUDE) self._see = see self._api = API( config.get(CONF_CLIENT_ID), config.get(CONF_CLIENT_SECRET), config.get(CONF_USERNAME), config.get(CONF_PASSWORD), ) def setup(self, hass): """Set up a timer and start gathering devices.""" self._refresh() track_utc_time_change( hass, lambda now: self._refresh(), second=range(0, 60, 30) ) def login(self, hass): """Perform a login on the FleetGO API.""" if self._api.login(): self.setup(hass) return True return False def _refresh(self) -> None: """Refresh device information from the platform.""" try: devices = self._api.get_devices() for device in devices: if not self._include or device.license_plate in self._include: if device.active or device.current_address is None: device.get_map_details() self._see( dev_id=device.plate_as_id, gps=(device.latitude, device.longitude), attributes=device.state_attributes, icon="mdi:car", ) except requests.exceptions.ConnectionError: _LOGGER.error("ConnectionError: Could not connect to FleetGO")
apache-2.0
skycucumber/Messaging-Gateway
webapp/venv/lib/python2.7/site-packages/setuptools/command/alias.py
285
2486
import distutils, os from setuptools import Command from distutils.util import convert_path from distutils import log from distutils.errors import * from setuptools.command.setopt import edit_config, option_base, config_file def shquote(arg): """Quote an argument for later parsing by shlex.split()""" for c in '"', "'", "\\", "#": if c in arg: return repr(arg) if arg.split() != [arg]: return repr(arg) return arg class alias(option_base): """Define a shortcut that invokes one or more commands""" description = "define a shortcut to invoke one or more commands" command_consumes_arguments = True user_options = [ ('remove', 'r', 'remove (unset) the alias'), ] + option_base.user_options boolean_options = option_base.boolean_options + ['remove'] def initialize_options(self): option_base.initialize_options(self) self.args = None self.remove = None def finalize_options(self): option_base.finalize_options(self) if self.remove and len(self.args) != 1: raise DistutilsOptionError( "Must specify exactly one argument (the alias name) when " "using --remove" ) def run(self): aliases = self.distribution.get_option_dict('aliases') if not self.args: print("Command Aliases") print("---------------") for alias in aliases: print("setup.py alias", format_alias(alias, aliases)) return elif len(self.args)==1: alias, = self.args if self.remove: command = None elif alias in aliases: print("setup.py alias", format_alias(alias, aliases)) return else: print("No alias definition found for %r" % alias) return else: alias = self.args[0] command = ' '.join(map(shquote,self.args[1:])) edit_config(self.filename, {'aliases': {alias:command}}, self.dry_run) def format_alias(name, aliases): source, command = aliases[name] if source == config_file('global'): source = '--global-config ' elif source == config_file('user'): source = '--user-config ' elif source == config_file('local'): source = '' else: source = '--filename=%r' % source return source+name+' '+command
gpl-2.0
morissette/devopsdays-hackathon-2016
venv/lib/python2.7/site-packages/botocore/vendored/requests/packages/chardet/chardetect.py
1786
2504
#!/usr/bin/env python """ Script which takes one or more file paths and reports on their detected encodings Example:: % chardetect somefile someotherfile somefile: windows-1252 with confidence 0.5 someotherfile: ascii with confidence 1.0 If no paths are provided, it takes its input from stdin. """ from __future__ import absolute_import, print_function, unicode_literals import argparse import sys from io import open from chardet import __version__ from chardet.universaldetector import UniversalDetector def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = UniversalDetector() for line in lines: u.feed(line) u.close() result = u.result if result['encoding']: return '{0}: {1} with confidence {2}'.format(name, result['encoding'], result['confidence']) else: return '{0}: no result'.format(name) def main(argv=None): ''' Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str ''' # Get command line arguments parser = argparse.ArgumentParser( description="Takes one or more file paths and reports their detected \ encodings", formatter_class=argparse.ArgumentDefaultsHelpFormatter, conflict_handler='resolve') parser.add_argument('input', help='File whose encoding we would like to determine.', type=argparse.FileType('rb'), nargs='*', default=[sys.stdin]) parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(__version__)) args = parser.parse_args(argv) for f in args.input: if f.isatty(): print("You are running chardetect interactively. Press " + "CTRL-D twice at the start of a blank line to signal the " + "end of your input. If you want help, run chardetect " + "--help\n", file=sys.stderr) print(description_of(f, f.name)) if __name__ == '__main__': main()
gpl-3.0
gabelula/b-counted
django/contrib/localflavor/id/id_choices.py
65
3089
from django.utils.translation import ugettext_lazy as _ # Reference: http://id.wikipedia.org/wiki/Daftar_provinsi_Indonesia # Indonesia does not have an official Province code standard. # I decided to use unambiguous and consistent (some are common) 3-letter codes. PROVINCE_CHOICES = ( ('BLI', _('Bali')), ('BTN', _('Banten')), ('BKL', _('Bengkulu')), ('DIY', _('Yogyakarta')), ('JKT', _('Jakarta')), ('GOR', _('Gorontalo')), ('JMB', _('Jambi')), ('JBR', _('Jawa Barat')), ('JTG', _('Jawa Tengah')), ('JTM', _('Jawa Timur')), ('KBR', _('Kalimantan Barat')), ('KSL', _('Kalimantan Selatan')), ('KTG', _('Kalimantan Tengah')), ('KTM', _('Kalimantan Timur')), ('BBL', _('Kepulauan Bangka-Belitung')), ('KRI', _('Kepulauan Riau')), ('LPG', _('Lampung')), ('MLK', _('Maluku')), ('MUT', _('Maluku Utara')), ('NAD', _('Nanggroe Aceh Darussalam')), ('NTB', _('Nusa Tenggara Barat')), ('NTT', _('Nusa Tenggara Timur')), ('PPA', _('Papua')), ('PPB', _('Papua Barat')), ('RIU', _('Riau')), ('SLB', _('Sulawesi Barat')), ('SLS', _('Sulawesi Selatan')), ('SLT', _('Sulawesi Tengah')), ('SLR', _('Sulawesi Tenggara')), ('SLU', _('Sulawesi Utara')), ('SMB', _('Sumatera Barat')), ('SMS', _('Sumatera Selatan')), ('SMU', _('Sumatera Utara')), ) LICENSE_PLATE_PREFIX_CHOICES = ( ('A', _('Banten')), ('AA', _('Magelang')), ('AB', _('Yogyakarta')), ('AD', _('Surakarta - Solo')), ('AE', _('Madiun')), ('AG', _('Kediri')), ('B', _('Jakarta')), ('BA', _('Sumatera Barat')), ('BB', _('Tapanuli')), ('BD', _('Bengkulu')), ('BE', _('Lampung')), ('BG', _('Sumatera Selatan')), ('BH', _('Jambi')), ('BK', _('Sumatera Utara')), ('BL', _('Nanggroe Aceh Darussalam')), ('BM', _('Riau')), ('BN', _('Kepulauan Bangka Belitung')), ('BP', _('Kepulauan Riau')), ('CC', _('Corps Consulate')), ('CD', _('Corps Diplomatic')), ('D', _('Bandung')), ('DA', _('Kalimantan Selatan')), ('DB', _('Sulawesi Utara Daratan')), ('DC', _('Sulawesi Barat')), ('DD', _('Sulawesi Selatan')), ('DE', _('Maluku')), ('DG', _('Maluku Utara')), ('DH', _('NTT - Timor')), ('DK', _('Bali')), ('DL', _('Sulawesi Utara Kepulauan')), ('DM', _('Gorontalo')), ('DN', _('Sulawesi Tengah')), ('DR', _('NTB - Lombok')), ('DS', _('Papua dan Papua Barat')), ('DT', _('Sulawesi Tenggara')), ('E', _('Cirebon')), ('EA', _('NTB - Sumbawa')), ('EB', _('NTT - Flores')), ('ED', _('NTT - Sumba')), ('F', _('Bogor')), ('G', _('Pekalongan')), ('H', _('Semarang')), ('K', _('Pati')), ('KB', _('Kalimantan Barat')), ('KH', _('Kalimantan Tengah')), ('KT', _('Kalimantan Timur')), ('L', _('Surabaya')), ('M', _('Madura')), ('N', _('Malang')), ('P', _('Jember')), ('R', _('Banyumas')), ('RI', _('Federal Government')), ('S', _('Bojonegoro')), ('T', _('Purwakarta')), ('W', _('Sidoarjo')), ('Z', _('Garut')), )
apache-2.0
Dhivyap/ansible
test/units/mock/vault_helper.py
206
1559
# 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.module_utils._text import to_bytes from ansible.parsing.vault import VaultSecret class TextVaultSecret(VaultSecret): '''A secret piece of text. ie, a password. Tracks text encoding. The text encoding of the text may not be the default text encoding so we keep track of the encoding so we encode it to the same bytes.''' def __init__(self, text, encoding=None, errors=None, _bytes=None): super(TextVaultSecret, self).__init__() self.text = text self.encoding = encoding or 'utf-8' self._bytes = _bytes self.errors = errors or 'strict' @property def bytes(self): '''The text encoded with encoding, unless we specifically set _bytes.''' return self._bytes or to_bytes(self.text, encoding=self.encoding, errors=self.errors)
gpl-3.0
chris-chris/tensorflow
tensorflow/contrib/layers/python/layers/target_column.py
125
18698
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """TargetColumn abstract a single head in the model. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from tensorflow.contrib.framework import deprecated from tensorflow.contrib.losses.python.losses import loss_ops from tensorflow.contrib.metrics.python.ops import metric_ops from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") def regression_target(label_name=None, weight_column_name=None, label_dimension=1): """Creates a _TargetColumn for linear regression. Args: label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. label_dimension: dimension of the target for multilabels. Returns: An instance of _TargetColumn """ return _RegressionTargetColumn( loss_fn=_mean_squared_loss, label_name=label_name, weight_column_name=weight_column_name, label_dimension=label_dimension) # TODO(zakaria): Add logistic_regression_target @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") def multi_class_target(n_classes, label_name=None, weight_column_name=None): """Creates a _TargetColumn for multi class single label classification. The target column uses softmax cross entropy loss. Args: n_classes: Integer, number of classes, must be >= 2 label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. Returns: An instance of _MultiClassTargetColumn. Raises: ValueError: if n_classes is < 2 """ if n_classes < 2: raise ValueError("n_classes must be > 1 for classification.") if n_classes == 2: loss_fn = _log_loss_with_two_classes else: loss_fn = _softmax_cross_entropy_loss return _MultiClassTargetColumn( loss_fn=loss_fn, n_classes=n_classes, label_name=label_name, weight_column_name=weight_column_name) @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") def binary_svm_target(label_name=None, weight_column_name=None): """Creates a _TargetColumn for binary classification with SVMs. The target column uses binary hinge loss. Args: label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. Returns: An instance of _TargetColumn. """ return _BinarySvmTargetColumn( label_name=label_name, weight_column_name=weight_column_name) @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") class ProblemType(object): UNSPECIFIED = 0 CLASSIFICATION = 1 LINEAR_REGRESSION = 2 LOGISTIC_REGRESSION = 3 class _TargetColumn(object): """_TargetColumn is the abstraction for a single head in a model. Args: loss_fn: a function that returns the loss tensor. num_label_columns: Integer, number of label columns. label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. Raises: ValueError: if loss_fn or n_classes are missing. """ def __init__(self, loss_fn, num_label_columns, label_name, weight_column_name, problem_type): if not loss_fn: raise ValueError("loss_fn must be provided") if num_label_columns is None: # n_classes can be 0 raise ValueError("num_label_columns must be provided") self._loss_fn = loss_fn self._num_label_columns = num_label_columns self._label_name = label_name self._weight_column_name = weight_column_name self._problem_type = problem_type def logits_to_predictions(self, logits, proba=False): # Abstrat, Subclasses must implement. raise NotImplementedError() def get_eval_ops(self, features, logits, labels, metrics=None): """Returns eval op.""" raise NotImplementedError @property def label_name(self): return self._label_name @property def weight_column_name(self): return self._weight_column_name @property def num_label_columns(self): return self._num_label_columns def get_weight_tensor(self, features): if not self._weight_column_name: return None else: return array_ops.reshape( math_ops.to_float(features[self._weight_column_name]), shape=(-1,)) @property def problem_type(self): return self._problem_type def _weighted_loss(self, loss, weight_tensor): """Returns cumulative weighted loss.""" unweighted_loss = array_ops.reshape(loss, shape=(-1,)) weighted_loss = math_ops.multiply(unweighted_loss, array_ops.reshape( weight_tensor, shape=(-1,))) return weighted_loss def training_loss(self, logits, target, features, name="training_loss"): """Returns training loss tensor for this head. Training loss is different from the loss reported on the tensorboard as we should respect the example weights when computing the gradient. L = sum_{i} w_{i} * l_{i} / B where B is the number of examples in the batch, l_{i}, w_{i} are individual losses, and example weight. Args: logits: logits, a float tensor. target: either a tensor for labels or in multihead case, a dict of string to target tensor. features: features dict. name: Op name. Returns: Loss tensor. """ target = target[self.name] if isinstance(target, dict) else target loss_unweighted = self._loss_fn(logits, target) weight_tensor = self.get_weight_tensor(features) if weight_tensor is None: return math_ops.reduce_mean(loss_unweighted, name=name) loss_weighted = self._weighted_loss(loss_unweighted, weight_tensor) return math_ops.reduce_mean(loss_weighted, name=name) def loss(self, logits, target, features): """Returns loss tensor for this head. The loss returned is the weighted average. L = sum_{i} w_{i} * l_{i} / sum_{i} w_{i} Args: logits: logits, a float tensor. target: either a tensor for labels or in multihead case, a dict of string to target tensor. features: features dict. Returns: Loss tensor. """ target = target[self.name] if isinstance(target, dict) else target loss_unweighted = self._loss_fn(logits, target) weight_tensor = self.get_weight_tensor(features) if weight_tensor is None: return math_ops.reduce_mean(loss_unweighted, name="loss") loss_weighted = self._weighted_loss(loss_unweighted, weight_tensor) return math_ops.div(math_ops.reduce_sum(loss_weighted), math_ops.to_float(math_ops.reduce_sum(weight_tensor)), name="loss") class _RegressionTargetColumn(_TargetColumn): """_TargetColumn for regression.""" def __init__(self, loss_fn, label_name, weight_column_name, label_dimension): super(_RegressionTargetColumn, self).__init__( loss_fn=loss_fn, num_label_columns=label_dimension, label_name=label_name, weight_column_name=weight_column_name, problem_type=ProblemType.LINEAR_REGRESSION) def logits_to_predictions(self, logits, proba=False): if self.num_label_columns == 1: return array_ops.squeeze(logits, squeeze_dims=[1]) return logits def get_eval_ops(self, features, logits, labels, metrics=None): loss = self.loss(logits, labels, features) result = {"loss": metric_ops.streaming_mean(loss)} if metrics: predictions = self.logits_to_predictions(logits, proba=False) result.update( _run_metrics(predictions, labels, metrics, self.get_weight_tensor(features))) return result class _MultiClassTargetColumn(_TargetColumn): """_TargetColumn for classification.""" # TODO(zakaria): support multilabel. def __init__(self, loss_fn, n_classes, label_name, weight_column_name): if n_classes < 2: raise ValueError("n_classes must be >= 2") super(_MultiClassTargetColumn, self).__init__( loss_fn=loss_fn, num_label_columns=1 if n_classes == 2 else n_classes, label_name=label_name, weight_column_name=weight_column_name, problem_type=ProblemType.CLASSIFICATION) def logits_to_predictions(self, logits, proba=False): if self.num_label_columns == 1: logits = array_ops.concat([array_ops.zeros_like(logits), logits], 1) if proba: return nn.softmax(logits) else: return math_ops.argmax(logits, 1) def _default_eval_metrics(self): if self._num_label_columns == 1: return get_default_binary_metrics_for_eval(thresholds=[.5]) return {} def get_eval_ops(self, features, logits, labels, metrics=None): loss = self.loss(logits, labels, features) result = {"loss": metric_ops.streaming_mean(loss)} # Adds default metrics. if metrics is None: # TODO(b/29366811): This currently results in both an "accuracy" and an # "accuracy/threshold_0.500000_mean" metric for binary classification. metrics = {("accuracy", "classes"): metric_ops.streaming_accuracy} predictions = math_ops.sigmoid(logits) labels_float = math_ops.to_float(labels) default_metrics = self._default_eval_metrics() for metric_name, metric_op in default_metrics.items(): result[metric_name] = metric_op(predictions, labels_float) class_metrics = {} proba_metrics = {} for name, metric_op in six.iteritems(metrics): if isinstance(name, tuple): if len(name) != 2: raise ValueError("Ignoring metric {}. It returned a tuple with " "len {}, expected 2.".format(name, len(name))) else: if name[1] not in ["classes", "probabilities"]: raise ValueError("Ignoring metric {}. The 2nd element of its " "name should be either 'classes' or " "'probabilities'.".format(name)) elif name[1] == "classes": class_metrics[name[0]] = metric_op else: proba_metrics[name[0]] = metric_op elif isinstance(name, str): class_metrics[name] = metric_op else: raise ValueError("Ignoring metric {}. Its name is not in the correct " "form.".format(name)) if class_metrics: class_predictions = self.logits_to_predictions(logits, proba=False) result.update( _run_metrics(class_predictions, labels, class_metrics, self.get_weight_tensor(features))) if proba_metrics: predictions = self.logits_to_predictions(logits, proba=True) result.update( _run_metrics(predictions, labels, proba_metrics, self.get_weight_tensor(features))) return result class _BinarySvmTargetColumn(_MultiClassTargetColumn): """_TargetColumn for binary classification using SVMs.""" def __init__(self, label_name, weight_column_name): def loss_fn(logits, target): check_shape_op = control_flow_ops.Assert( math_ops.less_equal(array_ops.rank(target), 2), ["target's shape should be either [batch_size, 1] or [batch_size]"]) with ops.control_dependencies([check_shape_op]): target = array_ops.reshape( target, shape=[array_ops.shape(target)[0], 1]) return loss_ops.hinge_loss(logits, target) super(_BinarySvmTargetColumn, self).__init__( loss_fn=loss_fn, n_classes=2, label_name=label_name, weight_column_name=weight_column_name) def logits_to_predictions(self, logits, proba=False): if proba: raise ValueError( "logits to probabilities is not supported for _BinarySvmTargetColumn") logits = array_ops.concat([array_ops.zeros_like(logits), logits], 1) return math_ops.argmax(logits, 1) # TODO(zakaria): use contrib losses. def _mean_squared_loss(logits, target): # To prevent broadcasting inside "-". if len(target.get_shape()) == 1: target = array_ops.expand_dims(target, dim=[1]) logits.get_shape().assert_is_compatible_with(target.get_shape()) return math_ops.square(logits - math_ops.to_float(target)) def _log_loss_with_two_classes(logits, target): # sigmoid_cross_entropy_with_logits requires [batch_size, 1] target. if len(target.get_shape()) == 1: target = array_ops.expand_dims(target, dim=[1]) loss_vec = nn.sigmoid_cross_entropy_with_logits( labels=math_ops.to_float(target), logits=logits) return loss_vec def _softmax_cross_entropy_loss(logits, target): # Check that we got integer for classification. if not target.dtype.is_integer: raise ValueError("Target's dtype should be integer " "Instead got %s." % target.dtype) # sparse_softmax_cross_entropy_with_logits requires [batch_size] target. if len(target.get_shape()) == 2: target = array_ops.squeeze(target, squeeze_dims=[1]) loss_vec = nn.sparse_softmax_cross_entropy_with_logits( labels=target, logits=logits) return loss_vec def _run_metrics(predictions, labels, metrics, weights): result = {} labels = math_ops.cast(labels, predictions.dtype) for name, metric in six.iteritems(metrics or {}): if weights is not None: result[name] = metric(predictions, labels, weights=weights) else: result[name] = metric(predictions, labels) return result @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") def get_default_binary_metrics_for_eval(thresholds): """Returns a dictionary of basic metrics for logistic regression. Args: thresholds: List of floating point thresholds to use for accuracy, precision, and recall metrics. If None, defaults to [0.5]. Returns: Dictionary mapping metrics string names to metrics functions. """ metrics = {} metrics[_MetricKeys.PREDICTION_MEAN] = _predictions_streaming_mean metrics[_MetricKeys.TARGET_MEAN] = _labels_streaming_mean # Also include the streaming mean of the label as an accuracy baseline, as # a reminder to users. metrics[_MetricKeys.ACCURACY_BASELINE] = _labels_streaming_mean metrics[_MetricKeys.AUC] = _streaming_auc for threshold in thresholds: metrics[_MetricKeys.ACCURACY_MEAN % threshold] = _accuracy_at_threshold(threshold) # Precision for positive examples. metrics[_MetricKeys.PRECISION_MEAN % threshold] = _streaming_at_threshold( metric_ops.streaming_precision_at_thresholds, threshold) # Recall for positive examples. metrics[_MetricKeys.RECALL_MEAN % threshold] = _streaming_at_threshold( metric_ops.streaming_recall_at_thresholds, threshold) return metrics def _float_weights_or_none(weights): if weights is None: return None return math_ops.to_float(weights) def _labels_streaming_mean(unused_predictions, labels, weights=None): return metric_ops.streaming_mean(labels, weights=weights) def _predictions_streaming_mean(predictions, unused_labels, weights=None): return metric_ops.streaming_mean(predictions, weights=weights) def _streaming_auc(predictions, labels, weights=None): return metric_ops.streaming_auc( predictions, labels, weights=_float_weights_or_none(weights)) def _accuracy_at_threshold(threshold): def _accuracy_metric(predictions, labels, weights=None): threshold_predictions = math_ops.to_float( math_ops.greater_equal(predictions, threshold)) return metric_ops.streaming_accuracy( predictions=threshold_predictions, labels=labels, weights=weights) return _accuracy_metric def _streaming_at_threshold(streaming_metrics_fn, threshold): def _streaming_metrics(predictions, labels, weights=None): precision_tensor, update_op = streaming_metrics_fn( predictions, labels=labels, thresholds=[threshold], weights=_float_weights_or_none(weights)) return array_ops.squeeze(precision_tensor), update_op return _streaming_metrics class _MetricKeys(object): AUC = "auc" PREDICTION_MEAN = "labels/prediction_mean" TARGET_MEAN = "labels/actual_target_mean" ACCURACY_BASELINE = "accuracy/baseline_target_mean" ACCURACY_MEAN = "accuracy/threshold_%f_mean" PRECISION_MEAN = "precision/positive_threshold_%f_mean" RECALL_MEAN = "recall/positive_threshold_%f_mean"
apache-2.0
MooglyGuy/mame
scripts/minimaws/minimaws.py
29
6527
#!/usr/bin/python ## ## license:BSD-3-Clause ## copyright-holders:Vas Crabb ## ## Demonstrates use of MAME's XML system information output ## ## This script requires Python 2.7 or Python 3.4, and SQLite 3.6.19 at ## the very least. Help is provided for all command-line options (use ## -h or --help). ## ## Before you can use the scripts, you need to load MAME system ## information into a database: ## ## $ python minimaws.py load --executable path/to/mame ## ## (The script uses the name "minimaws.sqlite3" for the database by ## default, but you can override this with the --database option.) ## ## After you've loaded the database, you can use query commands. Most ## of the query commands behave similarly to MAME's auxiliary verbs but ## case-sensitive and with better globbing (output not shown for ## brevity): ## ## $ python minimaws.py listfull "unkch*" ## $ python minimaws.py listclones "unkch*" ## $ python minimaws.py listbrothers superx ## ## The romident command does not support archives or software lists, but ## it's far faster than using MAME as it has optimised indexes, and ## results are grouped by machine rather than by file: ## ## $ python minimaws.py romident 27c64.bin dump-dir ## ## One more sophisticated query command is provided that MAME has no ## equivalent for. The listaffected command shows all runnable machines ## that reference devices defined in specified source files: ## ## $ python minimaws.py listaffected "src/devices/cpu/m6805/*" src/devices/cpu/mcs40/mcs40.cpp ## ## This script can also run a local web server allowing you to explore ## systems, devices and source files: ## ## $ python minimaws.py serve ## ## The default TCP port is 8080 but if desired, this can be changed with ## the --port option. The web service is implemented using WSGI, so it ## can be run in a web server if desired (e.g. using Apache mod_wsgi). ## It uses get queries and provides cacheable reponses, so it should ## work behind a caching proxy (e.g. squid or nginx). Although the ## service is written to avoid SQL injected and directory traversal ## attacks, and it avoids common sources of security issues, it has not ## been audited for vulnerabilities and is not recommended for use on ## public web sites. ## ## To use the web service, you need to know the short name of a device/ ## system, or the name of a source file containing a system: ## ## http://localhost:8080/machine/intlc440 ## http://localhost:8080/machine/a2mouse ## http://localhost:8080/sourcefile/src/devices/cpu/m68000/m68kcpu.cpp ## ## You can also start with a list of all source files containing machine ## definitions, but this is quite a large page and may perform poorly: ## ## http://localhost:8080/sourcefile/ ## ## One feature that may be of iterest to front-end authors or users of ## computer emulation is the ability to show available slot options and ## update live as changes are made. This can be seen in action on ## computer systems: ## ## http://localhost:8080/machine/ibm5150 ## http://localhost:8080/machine/apple2e ## http://localhost:8080/machine/ti82 ## ## On any of these, and many other systems, you can select slot options ## and see dependent slots update. Required command-line arguments to ## produce the selected configuration are also displayed. if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--database', metavar='<dbfile>', default='minimaws.sqlite3', help='SQLite 3 info database file (defaults to minimaws.sqlite3)') subparsers = parser.add_subparsers(title='commands', dest='command', metavar='<command>') subparser = subparsers.add_parser('listfull', help='list short names and full names') subparser.add_argument('pattern', nargs='?', metavar='<pat>', help='short name glob pattern') subparser = subparsers.add_parser('listsource', help='list short names and source files') subparser.add_argument('pattern', nargs='?', metavar='<pat>', help='short name glob pattern') subparser = subparsers.add_parser('listclones', help='show clones') subparser.add_argument('pattern', nargs='?', metavar='<pat>', help='short name/parent glob pattern') subparser = subparsers.add_parser('listbrothers', help='show drivers from the same source file(s)') subparser.add_argument('pattern', nargs='?', metavar='<pat>', help='short name glob pattern') subparser = subparsers.add_parser('listaffected', help='show drivers affected by source change(s)') subparser.add_argument('pattern', nargs='+', metavar='<pat>', help='source file glob pattern') subparser = subparsers.add_parser('romident', help='identify ROM dump(s)') subparser.add_argument('path', nargs='+', metavar='<path>', help='ROM dump file/directory path') subparser = subparsers.add_parser('serve', help='serve over HTTP') subparser.add_argument('--port', metavar='<port>', default=8080, type=int, help='server TCP port') subparser.add_argument('--host', metavar='<host>', default='', help='server TCP hostname') subparser = subparsers.add_parser('load', help='load machine information') group = subparser.add_mutually_exclusive_group(required=True) group.add_argument('--executable', metavar='<exe>', help='emulator executable') group.add_argument('--file', metavar='<xmlfile>', help='XML machine information file') subparser.add_argument('--softwarepath', required=True, action='append', metavar='<path>', help='Software list directory path') options = parser.parse_args() import lib.auxverbs if options.command == 'listfull': lib.auxverbs.do_listfull(options) elif options.command == 'listsource': lib.auxverbs.do_listsource(options) elif options.command == 'listclones': lib.auxverbs.do_listclones(options) elif options.command == 'listbrothers': lib.auxverbs.do_listbrothers(options) elif options.command == 'listaffected': lib.auxverbs.do_listaffected(options) elif options.command == 'romident': lib.auxverbs.do_romident(options) elif options.command == 'serve': import wsgiref.simple_server import lib.wsgiserve application = lib.wsgiserve.MiniMawsApp(options.database) server = wsgiref.simple_server.make_server(options.host, options.port, application) try: server.serve_forever() except KeyboardInterrupt: pass elif options.command == 'load': import lib.lxparse lib.lxparse.load_info(options)
gpl-2.0
tareqalayan/ansible
test/units/modules/network/iosxr/test_iosxr_command.py
45
4152
# (c) 2016 Red Hat Inc. # # 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.compat.tests.mock import patch from ansible.modules.network.iosxr import iosxr_command from units.modules.utils import set_module_args from .iosxr_module import TestIosxrModule, load_fixture class TestIosxrCommandModule(TestIosxrModule): module = iosxr_command def setUp(self): super(TestIosxrCommandModule, self).setUp() self.mock_run_command = patch('ansible.modules.network.iosxr.iosxr_command.run_command') self.run_command = self.mock_run_command.start() def tearDown(self): super(TestIosxrCommandModule, self).tearDown() self.mock_run_command.stop() def load_fixtures(self, commands=None): def load_from_file(*args, **kwargs): module, commands = args output = list() for item in commands: try: command = item['command'] except Exception: command = item filename = str(command).replace(' ', '_') output.append(load_fixture(filename)) return output self.run_command.side_effect = load_from_file def test_iosxr_command_simple(self): set_module_args(dict(commands=['show version'])) result = self.execute_module() self.assertEqual(len(result['stdout']), 1) self.assertTrue(result['stdout'][0].startswith('Cisco IOS XR Software')) def test_iosxr_command_multiple(self): set_module_args(dict(commands=['show version', 'show version'])) result = self.execute_module() self.assertEqual(len(result['stdout']), 2) self.assertTrue(result['stdout'][0].startswith('Cisco IOS XR Software')) def test_iosxr_command_wait_for(self): wait_for = 'result[0] contains "Cisco IOS"' set_module_args(dict(commands=['show version'], wait_for=wait_for)) self.execute_module() def test_iosxr_command_wait_for_fails(self): wait_for = 'result[0] contains "test string"' set_module_args(dict(commands=['show version'], wait_for=wait_for)) self.execute_module(failed=True) self.assertEqual(self.run_command.call_count, 10) def test_iosxr_command_retries(self): wait_for = 'result[0] contains "test string"' set_module_args(dict(commands=['show version'], wait_for=wait_for, retries=2)) self.execute_module(failed=True) self.assertEqual(self.run_command.call_count, 2) def test_iosxr_command_match_any(self): wait_for = ['result[0] contains "Cisco IOS"', 'result[0] contains "test string"'] set_module_args(dict(commands=['show version'], wait_for=wait_for, match='any')) self.execute_module() def test_iosxr_command_match_all(self): wait_for = ['result[0] contains "Cisco IOS"', 'result[0] contains "XR Software"'] set_module_args(dict(commands=['show version'], wait_for=wait_for, match='all')) self.execute_module() def test_iosxr_command_match_all_failure(self): wait_for = ['result[0] contains "Cisco IOS"', 'result[0] contains "test string"'] commands = ['show version', 'show version'] set_module_args(dict(commands=commands, wait_for=wait_for, match='all')) self.execute_module(failed=True)
gpl-3.0
flexVDI/cerbero
cerbero/packages/android.py
5
3864
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 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 # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. import os import tarfile from cerbero.config import Architecture from cerbero.packages import PackageType, PackagerBase from cerbero.packages.disttarball import DistTarball from cerbero.errors import UsageError class AndroidPackager(DistTarball): ''' Creates a distribution tarball for Android ''' def __init__(self, config, package, store): DistTarball.__init__(self, config, package, store) def files_list(self, package_type, force): if self.config.target_arch != Architecture.UNIVERSAL: # Nothing special to do for normal arches, just chain up return PackagerBase.files_list(self, package_type, force) else: # For the universal architecture, collect files from each # sub-archtecture if package_type == PackageType.DEVEL: files = self.package.devel_files_list() else: files = self.package.files_list() all_files = [] if isinstance(self.config.universal_archs, list): archs = self.config.universal_archs elif isinstance(self.config.universal_archs, dict): archs = self.config.universal_archs.keys() else: raise ConfigurationError('universal_archs must be a list or a dict') for arch in archs: all_files += [os.path.join(str(arch), f) for f in files] return all_files def _create_tarball(self, output_dir, package_type, files, force, package_prefix): filenames = [] # Filter out some unwanted directories for the development package if package_type == PackageType.DEVEL: for filt in ['bin/', 'share/aclocal']: files = [x for x in files if not x.startswith(filt)] # Create the bz2 file first filename = os.path.join(output_dir, self._get_name(package_type)) if os.path.exists(filename): if force: os.remove(filename) else: raise UsageError("File %s already exists" % filename) tar = tarfile.open(filename, "w:bz2") for f in files: filepath = os.path.join(self.prefix, f) tar.add(filepath, os.path.join(package_prefix, f)) tar.close() filenames.append(filename) return ' '.join(filenames) def _get_name(self, package_type, ext='tar.bz2'): if package_type == PackageType.DEVEL: package_type = '' elif package_type == PackageType.RUNTIME: package_type = '-runtime' return "%s%s-%s-%s-%s%s.%s" % (self.package_prefix, self.package.name, self.config.target_platform, self.config.target_arch, self.package.version, package_type, ext) def register(): from cerbero.packages.packager import register_packager from cerbero.config import Distro register_packager(Distro.ANDROID, AndroidPackager)
lgpl-2.1
KohlsTechnology/ansible
lib/ansible/modules/cloud/amazon/sns.py
32
7273
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Michael J. Schultz <mjschultz@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ module: sns short_description: Send Amazon Simple Notification Service (SNS) messages description: - The C(sns) module sends notifications to a topic on your Amazon SNS account version_added: 1.6 author: "Michael J. Schultz (@mjschultz)" options: msg: description: - Default message to send. required: true aliases: [ "default" ] subject: description: - Subject line for email delivery. topic: description: - The topic you want to publish to. required: true email: description: - Message to send to email-only subscription sqs: description: - Message to send to SQS-only subscription sms: description: - Message to send to SMS-only subscription http: description: - Message to send to HTTP-only subscription https: description: - Message to send to HTTPS-only subscription aws_secret_key: description: - AWS secret key. If not set then the value of the AWS_SECRET_KEY environment variable is used. aliases: ['ec2_secret_key', 'secret_key'] aws_access_key: description: - AWS access key. If not set then the value of the AWS_ACCESS_KEY environment variable is used. aliases: ['ec2_access_key', 'access_key'] region: description: - The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used. aliases: ['aws_region', 'ec2_region'] message_attributes: description: - Dictionary of message attributes. These are optional structured data entries to be sent along to the endpoint. - This is in AWS's distinct Name/Type/Value format; see example below. message_structure: description: - The payload format to use for the message. - This must be 'json' to support non-default messages (`http`, `https`, `email`, `sms`, `sqs`). It must be 'string' to support message_attributes. required: true default: json choices: ['json', 'string'] extends_documentation_fragment: - ec2 - aws requirements: - "boto" """ EXAMPLES = """ - name: Send default notification message via SNS sns: msg: '{{ inventory_hostname }} has completed the play.' subject: Deploy complete! topic: deploy delegate_to: localhost - name: Send notification messages via SNS with short message for SMS sns: msg: '{{ inventory_hostname }} has completed the play.' sms: deployed! subject: Deploy complete! topic: deploy delegate_to: localhost - name: Send message with message_attributes sns: topic: "deploy" msg: "message with extra details!" message_attributes: channel: data_type: String string_value: "mychannel" color: data_type: String string_value: "green" delegate_to: localhost """ import json import traceback try: import boto import boto.ec2 import boto.sns HAS_BOTO = True except ImportError: HAS_BOTO = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import ec2_argument_spec, connect_to_aws, get_aws_connection_info from ansible.module_utils._text import to_native def arn_topic_lookup(connection, short_topic): response = connection.get_all_topics() result = response[u'ListTopicsResponse'][u'ListTopicsResult'] # topic names cannot have colons, so this captures the full topic name lookup_topic = ':{}'.format(short_topic) for topic in result[u'Topics']: if topic[u'TopicArn'].endswith(lookup_topic): return topic[u'TopicArn'] return None def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( msg=dict(type='str', required=True, aliases=['default']), subject=dict(type='str', default=None), topic=dict(type='str', required=True), email=dict(type='str', default=None), sqs=dict(type='str', default=None), sms=dict(type='str', default=None), http=dict(type='str', default=None), https=dict(type='str', default=None), message_attributes=dict(type='dict', default=None), message_structure=dict(type='str', choices=['json', 'string'], default='json'), ) ) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto required for this module') msg = module.params['msg'] subject = module.params['subject'] topic = module.params['topic'] email = module.params['email'] sqs = module.params['sqs'] sms = module.params['sms'] http = module.params['http'] https = module.params['https'] message_attributes = module.params['message_attributes'] message_structure = module.params['message_structure'] region, ec2_url, aws_connect_params = get_aws_connection_info(module) if not region: module.fail_json(msg="region must be specified") try: connection = connect_to_aws(boto.sns, region, **aws_connect_params) except boto.exception.NoAuthHandlerFound as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) if not message_structure == 'string' and message_attributes: module.fail_json(msg="when specifying message_attributes, the message_structure must be set to 'string'; otherwise the attributes will not be sent.") elif message_structure == 'string' and (email or sqs or sms or http or https): module.fail_json(msg="do not specify non-default message formats when using the 'string' message_structure. they can only be used with " "the 'json' message_structure.") # .publish() takes full ARN topic id, but I'm lazy and type shortnames # so do a lookup (topics cannot contain ':', so that's the decider) if ':' in topic: arn_topic = topic else: arn_topic = arn_topic_lookup(connection, topic) if not arn_topic: module.fail_json(msg='Could not find topic: {}'.format(topic)) dict_msg = {'default': msg} if email: dict_msg.update(email=email) if sqs: dict_msg.update(sqs=sqs) if sms: dict_msg.update(sms=sms) if http: dict_msg.update(http=http) if https: dict_msg.update(https=https) if not message_structure == 'json': json_msg = msg else: json_msg = json.dumps(dict_msg) try: connection.publish(topic=arn_topic, subject=subject, message_structure=message_structure, message=json_msg, message_attributes=message_attributes) except boto.exception.BotoServerError as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) module.exit_json(msg="OK") if __name__ == '__main__': main()
gpl-3.0
k3nnyfr/s2a_fr-nsis
s2a/Python/Lib/test/test_cookielib.py
9
72203
# -*- coding: latin-1 -*- """Tests for cookielib.py.""" import cookielib import os import re import time from unittest import TestCase from test import test_support class DateTimeTests(TestCase): def test_time2isoz(self): from cookielib import time2isoz base = 1019227000 day = 24*3600 self.assertEqual(time2isoz(base), "2002-04-19 14:36:40Z") self.assertEqual(time2isoz(base+day), "2002-04-20 14:36:40Z") self.assertEqual(time2isoz(base+2*day), "2002-04-21 14:36:40Z") self.assertEqual(time2isoz(base+3*day), "2002-04-22 14:36:40Z") az = time2isoz() bz = time2isoz(500000) for text in (az, bz): self.assertTrue(re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$", text), "bad time2isoz format: %s %s" % (az, bz)) def test_http2time(self): from cookielib import http2time def parse_date(text): return time.gmtime(http2time(text))[:6] self.assertEqual(parse_date("01 Jan 2001"), (2001, 1, 1, 0, 0, 0.0)) # this test will break around year 2070 self.assertEqual(parse_date("03-Feb-20"), (2020, 2, 3, 0, 0, 0.0)) # this test will break around year 2048 self.assertEqual(parse_date("03-Feb-98"), (1998, 2, 3, 0, 0, 0.0)) def test_http2time_formats(self): from cookielib import http2time, time2isoz # test http2time for supported dates. Test cases with 2 digit year # will probably break in year 2044. tests = [ 'Thu, 03 Feb 1994 00:00:00 GMT', # proposed new HTTP format 'Thursday, 03-Feb-94 00:00:00 GMT', # old rfc850 HTTP format 'Thursday, 03-Feb-1994 00:00:00 GMT', # broken rfc850 HTTP format '03 Feb 1994 00:00:00 GMT', # HTTP format (no weekday) '03-Feb-94 00:00:00 GMT', # old rfc850 (no weekday) '03-Feb-1994 00:00:00 GMT', # broken rfc850 (no weekday) '03-Feb-1994 00:00 GMT', # broken rfc850 (no weekday, no seconds) '03-Feb-1994 00:00', # broken rfc850 (no weekday, no seconds, no tz) '03-Feb-94', # old rfc850 HTTP format (no weekday, no time) '03-Feb-1994', # broken rfc850 HTTP format (no weekday, no time) '03 Feb 1994', # proposed new HTTP format (no weekday, no time) # A few tests with extra space at various places ' 03 Feb 1994 0:00 ', ' 03-Feb-1994 ', ] test_t = 760233600 # assume broken POSIX counting of seconds result = time2isoz(test_t) expected = "1994-02-03 00:00:00Z" self.assertEqual(result, expected, "%s => '%s' (%s)" % (test_t, result, expected)) for s in tests: t = http2time(s) t2 = http2time(s.lower()) t3 = http2time(s.upper()) self.assertTrue(t == t2 == t3 == test_t, "'%s' => %s, %s, %s (%s)" % (s, t, t2, t3, test_t)) def test_http2time_garbage(self): from cookielib import http2time for test in [ '', 'Garbage', 'Mandag 16. September 1996', '01-00-1980', '01-13-1980', '00-01-1980', '32-01-1980', '01-01-1980 25:00:00', '01-01-1980 00:61:00', '01-01-1980 00:00:62', ]: self.assertTrue(http2time(test) is None, "http2time(%s) is not None\n" "http2time(test) %s" % (test, http2time(test)) ) class HeaderTests(TestCase): def test_parse_ns_headers_expires(self): from cookielib import parse_ns_headers # quotes should be stripped expected = [[('foo', 'bar'), ('expires', 2209069412L), ('version', '0')]] for hdr in [ 'foo=bar; expires=01 Jan 2040 22:23:32 GMT', 'foo=bar; expires="01 Jan 2040 22:23:32 GMT"', ]: self.assertEqual(parse_ns_headers([hdr]), expected) def test_parse_ns_headers_version(self): from cookielib import parse_ns_headers # quotes should be stripped expected = [[('foo', 'bar'), ('version', '1')]] for hdr in [ 'foo=bar; version="1"', 'foo=bar; Version="1"', ]: self.assertEqual(parse_ns_headers([hdr]), expected) def test_parse_ns_headers_special_names(self): # names such as 'expires' are not special in first name=value pair # of Set-Cookie: header from cookielib import parse_ns_headers # Cookie with name 'expires' hdr = 'expires=01 Jan 2040 22:23:32 GMT' expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]] self.assertEqual(parse_ns_headers([hdr]), expected) def test_join_header_words(self): from cookielib import join_header_words joined = join_header_words([[("foo", None), ("bar", "baz")]]) self.assertEqual(joined, "foo; bar=baz") self.assertEqual(join_header_words([[]]), "") def test_split_header_words(self): from cookielib import split_header_words tests = [ ("foo", [[("foo", None)]]), ("foo=bar", [[("foo", "bar")]]), (" foo ", [[("foo", None)]]), (" foo= ", [[("foo", "")]]), (" foo=", [[("foo", "")]]), (" foo= ; ", [[("foo", "")]]), (" foo= ; bar= baz ", [[("foo", ""), ("bar", "baz")]]), ("foo=bar bar=baz", [[("foo", "bar"), ("bar", "baz")]]), # doesn't really matter if this next fails, but it works ATM ("foo= bar=baz", [[("foo", "bar=baz")]]), ("foo=bar;bar=baz", [[("foo", "bar"), ("bar", "baz")]]), ('foo bar baz', [[("foo", None), ("bar", None), ("baz", None)]]), ("a, b, c", [[("a", None)], [("b", None)], [("c", None)]]), (r'foo; bar=baz, spam=, foo="\,\;\"", bar= ', [[("foo", None), ("bar", "baz")], [("spam", "")], [("foo", ',;"')], [("bar", "")]]), ] for arg, expect in tests: try: result = split_header_words([arg]) except: import traceback, StringIO f = StringIO.StringIO() traceback.print_exc(None, f) result = "(error -- traceback follows)\n\n%s" % f.getvalue() self.assertEqual(result, expect, """ When parsing: '%s' Expected: '%s' Got: '%s' """ % (arg, expect, result)) def test_roundtrip(self): from cookielib import split_header_words, join_header_words tests = [ ("foo", "foo"), ("foo=bar", "foo=bar"), (" foo ", "foo"), ("foo=", 'foo=""'), ("foo=bar bar=baz", "foo=bar; bar=baz"), ("foo=bar;bar=baz", "foo=bar; bar=baz"), ('foo bar baz', "foo; bar; baz"), (r'foo="\"" bar="\\"', r'foo="\""; bar="\\"'), ('foo,,,bar', 'foo, bar'), ('foo=bar,bar=baz', 'foo=bar, bar=baz'), ('text/html; charset=iso-8859-1', 'text/html; charset="iso-8859-1"'), ('foo="bar"; port="80,81"; discard, bar=baz', 'foo=bar; port="80,81"; discard, bar=baz'), (r'Basic realm="\"foo\\\\bar\""', r'Basic; realm="\"foo\\\\bar\""') ] for arg, expect in tests: input = split_header_words([arg]) res = join_header_words(input) self.assertEqual(res, expect, """ When parsing: '%s' Expected: '%s' Got: '%s' Input was: '%s' """ % (arg, expect, res, input)) class FakeResponse: def __init__(self, headers=[], url=None): """ headers: list of RFC822-style 'Key: value' strings """ import mimetools, StringIO f = StringIO.StringIO("\n".join(headers)) self._headers = mimetools.Message(f) self._url = url def info(self): return self._headers def interact_2965(cookiejar, url, *set_cookie_hdrs): return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie2") def interact_netscape(cookiejar, url, *set_cookie_hdrs): return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie") def _interact(cookiejar, url, set_cookie_hdrs, hdr_name): """Perform a single request / response cycle, returning Cookie: header.""" from urllib2 import Request req = Request(url) cookiejar.add_cookie_header(req) cookie_hdr = req.get_header("Cookie", "") headers = [] for hdr in set_cookie_hdrs: headers.append("%s: %s" % (hdr_name, hdr)) res = FakeResponse(headers, url) cookiejar.extract_cookies(res, req) return cookie_hdr class FileCookieJarTests(TestCase): def test_lwp_valueless_cookie(self): # cookies with no value should be saved and loaded consistently from cookielib import LWPCookieJar filename = test_support.TESTFN c = LWPCookieJar() interact_netscape(c, "http://www.acme.com/", 'boo') self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None) try: c.save(filename, ignore_discard=True) c = LWPCookieJar() c.load(filename, ignore_discard=True) finally: try: os.unlink(filename) except OSError: pass self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None) def test_bad_magic(self): from cookielib import LWPCookieJar, MozillaCookieJar, LoadError # IOErrors (eg. file doesn't exist) are allowed to propagate filename = test_support.TESTFN for cookiejar_class in LWPCookieJar, MozillaCookieJar: c = cookiejar_class() try: c.load(filename="for this test to work, a file with this " "filename should not exist") except IOError, exc: # exactly IOError, not LoadError self.assertEqual(exc.__class__, IOError) else: self.fail("expected IOError for invalid filename") # Invalid contents of cookies file (eg. bad magic string) # causes a LoadError. try: f = open(filename, "w") f.write("oops\n") for cookiejar_class in LWPCookieJar, MozillaCookieJar: c = cookiejar_class() self.assertRaises(LoadError, c.load, filename) finally: try: os.unlink(filename) except OSError: pass class CookieTests(TestCase): # XXX # Get rid of string comparisons where not actually testing str / repr. # .clear() etc. # IP addresses like 50 (single number, no dot) and domain-matching # functions (and is_HDN)? See draft RFC 2965 errata. # Strictness switches # is_third_party() # unverifiability / third-party blocking # Netscape cookies work the same as RFC 2965 with regard to port. # Set-Cookie with negative max age. # If turn RFC 2965 handling off, Set-Cookie2 cookies should not clobber # Set-Cookie cookies. # Cookie2 should be sent if *any* cookies are not V1 (ie. V0 OR V2 etc.). # Cookies (V1 and V0) with no expiry date should be set to be discarded. # RFC 2965 Quoting: # Should accept unquoted cookie-attribute values? check errata draft. # Which are required on the way in and out? # Should always return quoted cookie-attribute values? # Proper testing of when RFC 2965 clobbers Netscape (waiting for errata). # Path-match on return (same for V0 and V1). # RFC 2965 acceptance and returning rules # Set-Cookie2 without version attribute is rejected. # Netscape peculiarities list from Ronald Tschalar. # The first two still need tests, the rest are covered. ## - Quoting: only quotes around the expires value are recognized as such ## (and yes, some folks quote the expires value); quotes around any other ## value are treated as part of the value. ## - White space: white space around names and values is ignored ## - Default path: if no path parameter is given, the path defaults to the ## path in the request-uri up to, but not including, the last '/'. Note ## that this is entirely different from what the spec says. ## - Commas and other delimiters: Netscape just parses until the next ';'. ## This means it will allow commas etc inside values (and yes, both ## commas and equals are commonly appear in the cookie value). This also ## means that if you fold multiple Set-Cookie header fields into one, ## comma-separated list, it'll be a headache to parse (at least my head ## starts hurting every time I think of that code). ## - Expires: You'll get all sorts of date formats in the expires, ## including emtpy expires attributes ("expires="). Be as flexible as you ## can, and certainly don't expect the weekday to be there; if you can't ## parse it, just ignore it and pretend it's a session cookie. ## - Domain-matching: Netscape uses the 2-dot rule for _all_ domains, not ## just the 7 special TLD's listed in their spec. And folks rely on ## that... def test_domain_return_ok(self): # test optimization: .domain_return_ok() should filter out most # domains in the CookieJar before we try to access them (because that # may require disk access -- in particular, with MSIECookieJar) # This is only a rough check for performance reasons, so it's not too # critical as long as it's sufficiently liberal. import cookielib, urllib2 pol = cookielib.DefaultCookiePolicy() for url, domain, ok in [ ("http://foo.bar.com/", "blah.com", False), ("http://foo.bar.com/", "rhubarb.blah.com", False), ("http://foo.bar.com/", "rhubarb.foo.bar.com", False), ("http://foo.bar.com/", ".foo.bar.com", True), ("http://foo.bar.com/", "foo.bar.com", True), ("http://foo.bar.com/", ".bar.com", True), ("http://foo.bar.com/", "com", True), ("http://foo.com/", "rhubarb.foo.com", False), ("http://foo.com/", ".foo.com", True), ("http://foo.com/", "foo.com", True), ("http://foo.com/", "com", True), ("http://foo/", "rhubarb.foo", False), ("http://foo/", ".foo", True), ("http://foo/", "foo", True), ("http://foo/", "foo.local", True), ("http://foo/", ".local", True), ]: request = urllib2.Request(url) r = pol.domain_return_ok(domain, request) if ok: self.assertTrue(r) else: self.assertTrue(not r) def test_missing_value(self): from cookielib import MozillaCookieJar, lwp_cookie_str # missing = sign in Cookie: header is regarded by Mozilla as a missing # name, and by cookielib as a missing value filename = test_support.TESTFN c = MozillaCookieJar(filename) interact_netscape(c, "http://www.acme.com/", 'eggs') interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/') cookie = c._cookies["www.acme.com"]["/"]["eggs"] self.assertTrue(cookie.value is None) self.assertEqual(cookie.name, "eggs") cookie = c._cookies["www.acme.com"]['/foo/']['"spam"'] self.assertTrue(cookie.value is None) self.assertEqual(cookie.name, '"spam"') self.assertEqual(lwp_cookie_str(cookie), ( r'"spam"; path="/foo/"; domain="www.acme.com"; ' 'path_spec; discard; version=0')) old_str = repr(c) c.save(ignore_expires=True, ignore_discard=True) try: c = MozillaCookieJar(filename) c.revert(ignore_expires=True, ignore_discard=True) finally: os.unlink(c.filename) # cookies unchanged apart from lost info re. whether path was specified self.assertEqual( repr(c), re.sub("path_specified=%s" % True, "path_specified=%s" % False, old_str) ) self.assertEqual(interact_netscape(c, "http://www.acme.com/foo/"), '"spam"; eggs') def test_rfc2109_handling(self): # RFC 2109 cookies are handled as RFC 2965 or Netscape cookies, # dependent on policy settings from cookielib import CookieJar, DefaultCookiePolicy for rfc2109_as_netscape, rfc2965, version in [ # default according to rfc2965 if not explicitly specified (None, False, 0), (None, True, 1), # explicit rfc2109_as_netscape (False, False, None), # version None here means no cookie stored (False, True, 1), (True, False, 0), (True, True, 0), ]: policy = DefaultCookiePolicy( rfc2109_as_netscape=rfc2109_as_netscape, rfc2965=rfc2965) c = CookieJar(policy) interact_netscape(c, "http://www.example.com/", "ni=ni; Version=1") try: cookie = c._cookies["www.example.com"]["/"]["ni"] except KeyError: self.assertTrue(version is None) # didn't expect a stored cookie else: self.assertEqual(cookie.version, version) # 2965 cookies are unaffected interact_2965(c, "http://www.example.com/", "foo=bar; Version=1") if rfc2965: cookie2965 = c._cookies["www.example.com"]["/"]["foo"] self.assertEqual(cookie2965.version, 1) def test_ns_parser(self): from cookielib import CookieJar, DEFAULT_HTTP_PORT c = CookieJar() interact_netscape(c, "http://www.acme.com/", 'spam=eggs; DoMain=.acme.com; port; blArgh="feep"') interact_netscape(c, "http://www.acme.com/", 'ni=ni; port=80,8080') interact_netscape(c, "http://www.acme.com:80/", 'nini=ni') interact_netscape(c, "http://www.acme.com:80/", 'foo=bar; expires=') interact_netscape(c, "http://www.acme.com:80/", 'spam=eggs; ' 'expires="Foo Bar 25 33:22:11 3022"') cookie = c._cookies[".acme.com"]["/"]["spam"] self.assertEqual(cookie.domain, ".acme.com") self.assertTrue(cookie.domain_specified) self.assertEqual(cookie.port, DEFAULT_HTTP_PORT) self.assertTrue(not cookie.port_specified) # case is preserved self.assertTrue(cookie.has_nonstandard_attr("blArgh") and not cookie.has_nonstandard_attr("blargh")) cookie = c._cookies["www.acme.com"]["/"]["ni"] self.assertEqual(cookie.domain, "www.acme.com") self.assertTrue(not cookie.domain_specified) self.assertEqual(cookie.port, "80,8080") self.assertTrue(cookie.port_specified) cookie = c._cookies["www.acme.com"]["/"]["nini"] self.assertTrue(cookie.port is None) self.assertTrue(not cookie.port_specified) # invalid expires should not cause cookie to be dropped foo = c._cookies["www.acme.com"]["/"]["foo"] spam = c._cookies["www.acme.com"]["/"]["foo"] self.assertTrue(foo.expires is None) self.assertTrue(spam.expires is None) def test_ns_parser_special_names(self): # names such as 'expires' are not special in first name=value pair # of Set-Cookie: header from cookielib import CookieJar c = CookieJar() interact_netscape(c, "http://www.acme.com/", 'expires=eggs') interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs') cookies = c._cookies["www.acme.com"]["/"] self.assertTrue('expires' in cookies) self.assertTrue('version' in cookies) def test_expires(self): from cookielib import time2netscape, CookieJar # if expires is in future, keep cookie... c = CookieJar() future = time2netscape(time.time()+3600) interact_netscape(c, "http://www.acme.com/", 'spam="bar"; expires=%s' % future) self.assertEqual(len(c), 1) now = time2netscape(time.time()-1) # ... and if in past or present, discard it interact_netscape(c, "http://www.acme.com/", 'foo="eggs"; expires=%s' % now) h = interact_netscape(c, "http://www.acme.com/") self.assertEqual(len(c), 1) self.assertTrue('spam="bar"' in h and "foo" not in h) # max-age takes precedence over expires, and zero max-age is request to # delete both new cookie and any old matching cookie interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; expires=%s' % future) interact_netscape(c, "http://www.acme.com/", 'bar="bar"; expires=%s' % future) self.assertEqual(len(c), 3) interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; ' 'expires=%s; max-age=0' % future) interact_netscape(c, "http://www.acme.com/", 'bar="bar"; ' 'max-age=0; expires=%s' % future) h = interact_netscape(c, "http://www.acme.com/") self.assertEqual(len(c), 1) # test expiry at end of session for cookies with no expires attribute interact_netscape(c, "http://www.rhubarb.net/", 'whum="fizz"') self.assertEqual(len(c), 2) c.clear_session_cookies() self.assertEqual(len(c), 1) self.assertIn('spam="bar"', h) # XXX RFC 2965 expiry rules (some apply to V0 too) def test_default_path(self): from cookielib import CookieJar, DefaultCookiePolicy # RFC 2965 pol = DefaultCookiePolicy(rfc2965=True) c = CookieJar(pol) interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"') self.assertIn("/", c._cookies["www.acme.com"]) c = CookieJar(pol) interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"') self.assertIn("/", c._cookies["www.acme.com"]) c = CookieJar(pol) interact_2965(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"; Version="1"') self.assertIn("/blah/", c._cookies["www.acme.com"]) c = CookieJar(pol) interact_2965(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"; Version="1"') self.assertIn("/blah/rhubarb/", c._cookies["www.acme.com"]) # Netscape c = CookieJar() interact_netscape(c, "http://www.acme.com/", 'spam="bar"') self.assertIn("/", c._cookies["www.acme.com"]) c = CookieJar() interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"') self.assertIn("/", c._cookies["www.acme.com"]) c = CookieJar() interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"') self.assertIn("/blah", c._cookies["www.acme.com"]) c = CookieJar() interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"') self.assertIn("/blah/rhubarb", c._cookies["www.acme.com"]) def test_default_path_with_query(self): cj = cookielib.CookieJar() uri = "http://example.com/?spam/eggs" value = 'eggs="bar"' interact_netscape(cj, uri, value) # default path does not include query, so is "/", not "/?spam" self.assertIn("/", cj._cookies["example.com"]) # cookie is sent back to the same URI self.assertEqual(interact_netscape(cj, uri), value) def test_escape_path(self): from cookielib import escape_path cases = [ # quoted safe ("/foo%2f/bar", "/foo%2F/bar"), ("/foo%2F/bar", "/foo%2F/bar"), # quoted % ("/foo%%/bar", "/foo%%/bar"), # quoted unsafe ("/fo%19o/bar", "/fo%19o/bar"), ("/fo%7do/bar", "/fo%7Do/bar"), # unquoted safe ("/foo/bar&", "/foo/bar&"), ("/foo//bar", "/foo//bar"), ("\176/foo/bar", "\176/foo/bar"), # unquoted unsafe ("/foo\031/bar", "/foo%19/bar"), ("/\175foo/bar", "/%7Dfoo/bar"), # unicode (u"/foo/bar\uabcd", "/foo/bar%EA%AF%8D"), # UTF-8 encoded ] for arg, result in cases: self.assertEqual(escape_path(arg), result) def test_request_path(self): from urllib2 import Request from cookielib import request_path # with parameters req = Request("http://www.example.com/rheum/rhaponticum;" "foo=bar;sing=song?apples=pears&spam=eggs#ni") self.assertEqual(request_path(req), "/rheum/rhaponticum;foo=bar;sing=song") # without parameters req = Request("http://www.example.com/rheum/rhaponticum?" "apples=pears&spam=eggs#ni") self.assertEqual(request_path(req), "/rheum/rhaponticum") # missing final slash req = Request("http://www.example.com") self.assertEqual(request_path(req), "/") def test_request_port(self): from urllib2 import Request from cookielib import request_port, DEFAULT_HTTP_PORT req = Request("http://www.acme.com:1234/", headers={"Host": "www.acme.com:4321"}) self.assertEqual(request_port(req), "1234") req = Request("http://www.acme.com/", headers={"Host": "www.acme.com:4321"}) self.assertEqual(request_port(req), DEFAULT_HTTP_PORT) def test_request_host(self): from urllib2 import Request from cookielib import request_host # this request is illegal (RFC2616, 14.2.3) req = Request("http://1.1.1.1/", headers={"Host": "www.acme.com:80"}) # libwww-perl wants this response, but that seems wrong (RFC 2616, # section 5.2, point 1., and RFC 2965 section 1, paragraph 3) #self.assertEqual(request_host(req), "www.acme.com") self.assertEqual(request_host(req), "1.1.1.1") req = Request("http://www.acme.com/", headers={"Host": "irrelevant.com"}) self.assertEqual(request_host(req), "www.acme.com") # not actually sure this one is valid Request object, so maybe should # remove test for no host in url in request_host function? req = Request("/resource.html", headers={"Host": "www.acme.com"}) self.assertEqual(request_host(req), "www.acme.com") # port shouldn't be in request-host req = Request("http://www.acme.com:2345/resource.html", headers={"Host": "www.acme.com:5432"}) self.assertEqual(request_host(req), "www.acme.com") def test_is_HDN(self): from cookielib import is_HDN self.assertTrue(is_HDN("foo.bar.com")) self.assertTrue(is_HDN("1foo2.3bar4.5com")) self.assertTrue(not is_HDN("192.168.1.1")) self.assertTrue(not is_HDN("")) self.assertTrue(not is_HDN(".")) self.assertTrue(not is_HDN(".foo.bar.com")) self.assertTrue(not is_HDN("..foo")) self.assertTrue(not is_HDN("foo.")) def test_reach(self): from cookielib import reach self.assertEqual(reach("www.acme.com"), ".acme.com") self.assertEqual(reach("acme.com"), "acme.com") self.assertEqual(reach("acme.local"), ".local") self.assertEqual(reach(".local"), ".local") self.assertEqual(reach(".com"), ".com") self.assertEqual(reach("."), ".") self.assertEqual(reach(""), "") self.assertEqual(reach("192.168.0.1"), "192.168.0.1") def test_domain_match(self): from cookielib import domain_match, user_domain_match self.assertTrue(domain_match("192.168.1.1", "192.168.1.1")) self.assertTrue(not domain_match("192.168.1.1", ".168.1.1")) self.assertTrue(domain_match("x.y.com", "x.Y.com")) self.assertTrue(domain_match("x.y.com", ".Y.com")) self.assertTrue(not domain_match("x.y.com", "Y.com")) self.assertTrue(domain_match("a.b.c.com", ".c.com")) self.assertTrue(not domain_match(".c.com", "a.b.c.com")) self.assertTrue(domain_match("example.local", ".local")) self.assertTrue(not domain_match("blah.blah", "")) self.assertTrue(not domain_match("", ".rhubarb.rhubarb")) self.assertTrue(domain_match("", "")) self.assertTrue(user_domain_match("acme.com", "acme.com")) self.assertTrue(not user_domain_match("acme.com", ".acme.com")) self.assertTrue(user_domain_match("rhubarb.acme.com", ".acme.com")) self.assertTrue(user_domain_match("www.rhubarb.acme.com", ".acme.com")) self.assertTrue(user_domain_match("x.y.com", "x.Y.com")) self.assertTrue(user_domain_match("x.y.com", ".Y.com")) self.assertTrue(not user_domain_match("x.y.com", "Y.com")) self.assertTrue(user_domain_match("y.com", "Y.com")) self.assertTrue(not user_domain_match(".y.com", "Y.com")) self.assertTrue(user_domain_match(".y.com", ".Y.com")) self.assertTrue(user_domain_match("x.y.com", ".com")) self.assertTrue(not user_domain_match("x.y.com", "com")) self.assertTrue(not user_domain_match("x.y.com", "m")) self.assertTrue(not user_domain_match("x.y.com", ".m")) self.assertTrue(not user_domain_match("x.y.com", "")) self.assertTrue(not user_domain_match("x.y.com", ".")) self.assertTrue(user_domain_match("192.168.1.1", "192.168.1.1")) # not both HDNs, so must string-compare equal to match self.assertTrue(not user_domain_match("192.168.1.1", ".168.1.1")) self.assertTrue(not user_domain_match("192.168.1.1", ".")) # empty string is a special case self.assertTrue(not user_domain_match("192.168.1.1", "")) def test_wrong_domain(self): # Cookies whose effective request-host name does not domain-match the # domain are rejected. # XXX far from complete from cookielib import CookieJar c = CookieJar() interact_2965(c, "http://www.nasty.com/", 'foo=bar; domain=friendly.org; Version="1"') self.assertEqual(len(c), 0) def test_strict_domain(self): # Cookies whose domain is a country-code tld like .co.uk should # not be set if CookiePolicy.strict_domain is true. from cookielib import CookieJar, DefaultCookiePolicy cp = DefaultCookiePolicy(strict_domain=True) cj = CookieJar(policy=cp) interact_netscape(cj, "http://example.co.uk/", 'no=problemo') interact_netscape(cj, "http://example.co.uk/", 'okey=dokey; Domain=.example.co.uk') self.assertEqual(len(cj), 2) for pseudo_tld in [".co.uk", ".org.za", ".tx.us", ".name.us"]: interact_netscape(cj, "http://example.%s/" % pseudo_tld, 'spam=eggs; Domain=.co.uk') self.assertEqual(len(cj), 2) def test_two_component_domain_ns(self): # Netscape: .www.bar.com, www.bar.com, .bar.com, bar.com, no domain # should all get accepted, as should .acme.com, acme.com and no domain # for 2-component domains like acme.com. from cookielib import CookieJar, DefaultCookiePolicy c = CookieJar() # two-component V0 domain is OK interact_netscape(c, "http://foo.net/", 'ns=bar') self.assertEqual(len(c), 1) self.assertEqual(c._cookies["foo.net"]["/"]["ns"].value, "bar") self.assertEqual(interact_netscape(c, "http://foo.net/"), "ns=bar") # *will* be returned to any other domain (unlike RFC 2965)... self.assertEqual(interact_netscape(c, "http://www.foo.net/"), "ns=bar") # ...unless requested otherwise pol = DefaultCookiePolicy( strict_ns_domain=DefaultCookiePolicy.DomainStrictNonDomain) c.set_policy(pol) self.assertEqual(interact_netscape(c, "http://www.foo.net/"), "") # unlike RFC 2965, even explicit two-component domain is OK, # because .foo.net matches foo.net interact_netscape(c, "http://foo.net/foo/", 'spam1=eggs; domain=foo.net') # even if starts with a dot -- in NS rules, .foo.net matches foo.net! interact_netscape(c, "http://foo.net/foo/bar/", 'spam2=eggs; domain=.foo.net') self.assertEqual(len(c), 3) self.assertEqual(c._cookies[".foo.net"]["/foo"]["spam1"].value, "eggs") self.assertEqual(c._cookies[".foo.net"]["/foo/bar"]["spam2"].value, "eggs") self.assertEqual(interact_netscape(c, "http://foo.net/foo/bar/"), "spam2=eggs; spam1=eggs; ns=bar") # top-level domain is too general interact_netscape(c, "http://foo.net/", 'nini="ni"; domain=.net') self.assertEqual(len(c), 3) ## # Netscape protocol doesn't allow non-special top level domains (such ## # as co.uk) in the domain attribute unless there are at least three ## # dots in it. # Oh yes it does! Real implementations don't check this, and real # cookies (of course) rely on that behaviour. interact_netscape(c, "http://foo.co.uk", 'nasty=trick; domain=.co.uk') ## self.assertEqual(len(c), 2) self.assertEqual(len(c), 4) def test_two_component_domain_rfc2965(self): from cookielib import CookieJar, DefaultCookiePolicy pol = DefaultCookiePolicy(rfc2965=True) c = CookieJar(pol) # two-component V1 domain is OK interact_2965(c, "http://foo.net/", 'foo=bar; Version="1"') self.assertEqual(len(c), 1) self.assertEqual(c._cookies["foo.net"]["/"]["foo"].value, "bar") self.assertEqual(interact_2965(c, "http://foo.net/"), "$Version=1; foo=bar") # won't be returned to any other domain (because domain was implied) self.assertEqual(interact_2965(c, "http://www.foo.net/"), "") # unless domain is given explicitly, because then it must be # rewritten to start with a dot: foo.net --> .foo.net, which does # not domain-match foo.net interact_2965(c, "http://foo.net/foo", 'spam=eggs; domain=foo.net; path=/foo; Version="1"') self.assertEqual(len(c), 1) self.assertEqual(interact_2965(c, "http://foo.net/foo"), "$Version=1; foo=bar") # explicit foo.net from three-component domain www.foo.net *does* get # set, because .foo.net domain-matches .foo.net interact_2965(c, "http://www.foo.net/foo/", 'spam=eggs; domain=foo.net; Version="1"') self.assertEqual(c._cookies[".foo.net"]["/foo/"]["spam"].value, "eggs") self.assertEqual(len(c), 2) self.assertEqual(interact_2965(c, "http://foo.net/foo/"), "$Version=1; foo=bar") self.assertEqual(interact_2965(c, "http://www.foo.net/foo/"), '$Version=1; spam=eggs; $Domain="foo.net"') # top-level domain is too general interact_2965(c, "http://foo.net/", 'ni="ni"; domain=".net"; Version="1"') self.assertEqual(len(c), 2) # RFC 2965 doesn't require blocking this interact_2965(c, "http://foo.co.uk/", 'nasty=trick; domain=.co.uk; Version="1"') self.assertEqual(len(c), 3) def test_domain_allow(self): from cookielib import CookieJar, DefaultCookiePolicy from urllib2 import Request c = CookieJar(policy=DefaultCookiePolicy( blocked_domains=["acme.com"], allowed_domains=["www.acme.com"])) req = Request("http://acme.com/") headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"] res = FakeResponse(headers, "http://acme.com/") c.extract_cookies(res, req) self.assertEqual(len(c), 0) req = Request("http://www.acme.com/") res = FakeResponse(headers, "http://www.acme.com/") c.extract_cookies(res, req) self.assertEqual(len(c), 1) req = Request("http://www.coyote.com/") res = FakeResponse(headers, "http://www.coyote.com/") c.extract_cookies(res, req) self.assertEqual(len(c), 1) # set a cookie with non-allowed domain... req = Request("http://www.coyote.com/") res = FakeResponse(headers, "http://www.coyote.com/") cookies = c.make_cookies(res, req) c.set_cookie(cookies[0]) self.assertEqual(len(c), 2) # ... and check is doesn't get returned c.add_cookie_header(req) self.assertTrue(not req.has_header("Cookie")) def test_domain_block(self): from cookielib import CookieJar, DefaultCookiePolicy from urllib2 import Request pol = DefaultCookiePolicy( rfc2965=True, blocked_domains=[".acme.com"]) c = CookieJar(policy=pol) headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"] req = Request("http://www.acme.com/") res = FakeResponse(headers, "http://www.acme.com/") c.extract_cookies(res, req) self.assertEqual(len(c), 0) p = pol.set_blocked_domains(["acme.com"]) c.extract_cookies(res, req) self.assertEqual(len(c), 1) c.clear() req = Request("http://www.roadrunner.net/") res = FakeResponse(headers, "http://www.roadrunner.net/") c.extract_cookies(res, req) self.assertEqual(len(c), 1) req = Request("http://www.roadrunner.net/") c.add_cookie_header(req) self.assertTrue((req.has_header("Cookie") and req.has_header("Cookie2"))) c.clear() pol.set_blocked_domains([".acme.com"]) c.extract_cookies(res, req) self.assertEqual(len(c), 1) # set a cookie with blocked domain... req = Request("http://www.acme.com/") res = FakeResponse(headers, "http://www.acme.com/") cookies = c.make_cookies(res, req) c.set_cookie(cookies[0]) self.assertEqual(len(c), 2) # ... and check is doesn't get returned c.add_cookie_header(req) self.assertTrue(not req.has_header("Cookie")) def test_secure(self): from cookielib import CookieJar, DefaultCookiePolicy for ns in True, False: for whitespace in " ", "": c = CookieJar() if ns: pol = DefaultCookiePolicy(rfc2965=False) int = interact_netscape vs = "" else: pol = DefaultCookiePolicy(rfc2965=True) int = interact_2965 vs = "; Version=1" c.set_policy(pol) url = "http://www.acme.com/" int(c, url, "foo1=bar%s%s" % (vs, whitespace)) int(c, url, "foo2=bar%s; secure%s" % (vs, whitespace)) self.assertTrue( not c._cookies["www.acme.com"]["/"]["foo1"].secure, "non-secure cookie registered secure") self.assertTrue( c._cookies["www.acme.com"]["/"]["foo2"].secure, "secure cookie registered non-secure") def test_quote_cookie_value(self): from cookielib import CookieJar, DefaultCookiePolicy c = CookieJar(policy=DefaultCookiePolicy(rfc2965=True)) interact_2965(c, "http://www.acme.com/", r'foo=\b"a"r; Version=1') h = interact_2965(c, "http://www.acme.com/") self.assertEqual(h, r'$Version=1; foo=\\b\"a\"r') def test_missing_final_slash(self): # Missing slash from request URL's abs_path should be assumed present. from cookielib import CookieJar, DefaultCookiePolicy from urllib2 import Request url = "http://www.acme.com" c = CookieJar(DefaultCookiePolicy(rfc2965=True)) interact_2965(c, url, "foo=bar; Version=1") req = Request(url) self.assertEqual(len(c), 1) c.add_cookie_header(req) self.assertTrue(req.has_header("Cookie")) def test_domain_mirror(self): from cookielib import CookieJar, DefaultCookiePolicy pol = DefaultCookiePolicy(rfc2965=True) c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, "spam=eggs; Version=1") h = interact_2965(c, url) self.assertNotIn("Domain", h, "absent domain returned with domain present") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com') h = interact_2965(c, url) self.assertIn('$Domain=".bar.com"', h, "domain not returned") c = CookieJar(pol) url = "http://foo.bar.com/" # note missing initial dot in Domain interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com') h = interact_2965(c, url) self.assertIn('$Domain="bar.com"', h, "domain not returned") def test_path_mirror(self): from cookielib import CookieJar, DefaultCookiePolicy pol = DefaultCookiePolicy(rfc2965=True) c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, "spam=eggs; Version=1") h = interact_2965(c, url) self.assertNotIn("Path", h, "absent path returned with path present") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, 'spam=eggs; Version=1; Path=/') h = interact_2965(c, url) self.assertIn('$Path="/"', h, "path not returned") def test_port_mirror(self): from cookielib import CookieJar, DefaultCookiePolicy pol = DefaultCookiePolicy(rfc2965=True) c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, "spam=eggs; Version=1") h = interact_2965(c, url) self.assertNotIn("Port", h, "absent port returned with port present") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, "spam=eggs; Version=1; Port") h = interact_2965(c, url) self.assertTrue(re.search("\$Port([^=]|$)", h), "port with no value not returned with no value") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, 'spam=eggs; Version=1; Port="80"') h = interact_2965(c, url) self.assertIn('$Port="80"', h, "port with single value not returned with single value") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"') h = interact_2965(c, url) self.assertIn('$Port="80,8080"', h, "port with multiple values not returned with multiple " "values") def test_no_return_comment(self): from cookielib import CookieJar, DefaultCookiePolicy c = CookieJar(DefaultCookiePolicy(rfc2965=True)) url = "http://foo.bar.com/" interact_2965(c, url, 'spam=eggs; Version=1; ' 'Comment="does anybody read these?"; ' 'CommentURL="http://foo.bar.net/comment.html"') h = interact_2965(c, url) self.assertTrue( "Comment" not in h, "Comment or CommentURL cookie-attributes returned to server") def test_Cookie_iterator(self): from cookielib import CookieJar, Cookie, DefaultCookiePolicy cs = CookieJar(DefaultCookiePolicy(rfc2965=True)) # add some random cookies interact_2965(cs, "http://blah.spam.org/", 'foo=eggs; Version=1; ' 'Comment="does anybody read these?"; ' 'CommentURL="http://foo.bar.net/comment.html"') interact_netscape(cs, "http://www.acme.com/blah/", "spam=bar; secure") interact_2965(cs, "http://www.acme.com/blah/", "foo=bar; secure; Version=1") interact_2965(cs, "http://www.acme.com/blah/", "foo=bar; path=/; Version=1") interact_2965(cs, "http://www.sol.no", r'bang=wallop; version=1; domain=".sol.no"; ' r'port="90,100, 80,8080"; ' r'max-age=100; Comment = "Just kidding! (\"|\\\\) "') versions = [1, 1, 1, 0, 1] names = ["bang", "foo", "foo", "spam", "foo"] domains = [".sol.no", "blah.spam.org", "www.acme.com", "www.acme.com", "www.acme.com"] paths = ["/", "/", "/", "/blah", "/blah/"] for i in range(4): i = 0 for c in cs: self.assertIsInstance(c, Cookie) self.assertEqual(c.version, versions[i]) self.assertEqual(c.name, names[i]) self.assertEqual(c.domain, domains[i]) self.assertEqual(c.path, paths[i]) i = i + 1 def test_parse_ns_headers(self): from cookielib import parse_ns_headers # missing domain value (invalid cookie) self.assertEqual( parse_ns_headers(["foo=bar; path=/; domain"]), [[("foo", "bar"), ("path", "/"), ("domain", None), ("version", "0")]] ) # invalid expires value self.assertEqual( parse_ns_headers(["foo=bar; expires=Foo Bar 12 33:22:11 2000"]), [[("foo", "bar"), ("expires", None), ("version", "0")]] ) # missing cookie value (valid cookie) self.assertEqual( parse_ns_headers(["foo"]), [[("foo", None), ("version", "0")]] ) # shouldn't add version if header is empty self.assertEqual(parse_ns_headers([""]), []) def test_bad_cookie_header(self): def cookiejar_from_cookie_headers(headers): from cookielib import CookieJar from urllib2 import Request c = CookieJar() req = Request("http://www.example.com/") r = FakeResponse(headers, "http://www.example.com/") c.extract_cookies(r, req) return c # none of these bad headers should cause an exception to be raised for headers in [ ["Set-Cookie: "], # actually, nothing wrong with this ["Set-Cookie2: "], # ditto # missing domain value ["Set-Cookie2: a=foo; path=/; Version=1; domain"], # bad max-age ["Set-Cookie: b=foo; max-age=oops"], # bad version ["Set-Cookie: b=foo; version=spam"], ]: c = cookiejar_from_cookie_headers(headers) # these bad cookies shouldn't be set self.assertEqual(len(c), 0) # cookie with invalid expires is treated as session cookie headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"] c = cookiejar_from_cookie_headers(headers) cookie = c._cookies["www.example.com"]["/"]["c"] self.assertTrue(cookie.expires is None) class LWPCookieTests(TestCase): # Tests taken from libwww-perl, with a few modifications and additions. def test_netscape_example_1(self): from cookielib import CookieJar, DefaultCookiePolicy from urllib2 import Request #------------------------------------------------------------------- # First we check that it works for the original example at # http://www.netscape.com/newsref/std/cookie_spec.html # Client requests a document, and receives in the response: # # Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT # # When client requests a URL in path "/" on this server, it sends: # # Cookie: CUSTOMER=WILE_E_COYOTE # # Client requests a document, and receives in the response: # # Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/ # # When client requests a URL in path "/" on this server, it sends: # # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001 # # Client receives: # # Set-Cookie: SHIPPING=FEDEX; path=/fo # # When client requests a URL in path "/" on this server, it sends: # # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001 # # When client requests a URL in path "/foo" on this server, it sends: # # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX # # The last Cookie is buggy, because both specifications say that the # most specific cookie must be sent first. SHIPPING=FEDEX is the # most specific and should thus be first. year_plus_one = time.localtime()[0] + 1 headers = [] c = CookieJar(DefaultCookiePolicy(rfc2965 = True)) #req = Request("http://1.1.1.1/", # headers={"Host": "www.acme.com:80"}) req = Request("http://www.acme.com:80/", headers={"Host": "www.acme.com:80"}) headers.append( "Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/ ; " "expires=Wednesday, 09-Nov-%d 23:12:40 GMT" % year_plus_one) res = FakeResponse(headers, "http://www.acme.com/") c.extract_cookies(res, req) req = Request("http://www.acme.com/") c.add_cookie_header(req) self.assertEqual(req.get_header("Cookie"), "CUSTOMER=WILE_E_COYOTE") self.assertEqual(req.get_header("Cookie2"), '$Version="1"') headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/") res = FakeResponse(headers, "http://www.acme.com/") c.extract_cookies(res, req) req = Request("http://www.acme.com/foo/bar") c.add_cookie_header(req) h = req.get_header("Cookie") self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h) self.assertIn("CUSTOMER=WILE_E_COYOTE", h) headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo') res = FakeResponse(headers, "http://www.acme.com") c.extract_cookies(res, req) req = Request("http://www.acme.com/") c.add_cookie_header(req) h = req.get_header("Cookie") self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h) self.assertIn("CUSTOMER=WILE_E_COYOTE", h) self.assertNotIn("SHIPPING=FEDEX", h) req = Request("http://www.acme.com/foo/") c.add_cookie_header(req) h = req.get_header("Cookie") self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h) self.assertIn("CUSTOMER=WILE_E_COYOTE", h) self.assertTrue(h.startswith("SHIPPING=FEDEX;")) def test_netscape_example_2(self): from cookielib import CookieJar from urllib2 import Request # Second Example transaction sequence: # # Assume all mappings from above have been cleared. # # Client receives: # # Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/ # # When client requests a URL in path "/" on this server, it sends: # # Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001 # # Client receives: # # Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo # # When client requests a URL in path "/ammo" on this server, it sends: # # Cookie: PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001 # # NOTE: There are two name/value pairs named "PART_NUMBER" due to # the inheritance of the "/" mapping in addition to the "/ammo" mapping. c = CookieJar() headers = [] req = Request("http://www.acme.com/") headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/") res = FakeResponse(headers, "http://www.acme.com/") c.extract_cookies(res, req) req = Request("http://www.acme.com/") c.add_cookie_header(req) self.assertEqual(req.get_header("Cookie"), "PART_NUMBER=ROCKET_LAUNCHER_0001") headers.append( "Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo") res = FakeResponse(headers, "http://www.acme.com/") c.extract_cookies(res, req) req = Request("http://www.acme.com/ammo") c.add_cookie_header(req) self.assertTrue(re.search(r"PART_NUMBER=RIDING_ROCKET_0023;\s*" "PART_NUMBER=ROCKET_LAUNCHER_0001", req.get_header("Cookie"))) def test_ietf_example_1(self): from cookielib import CookieJar, DefaultCookiePolicy #------------------------------------------------------------------- # Then we test with the examples from draft-ietf-http-state-man-mec-03.txt # # 5. EXAMPLES c = CookieJar(DefaultCookiePolicy(rfc2965=True)) # # 5.1 Example 1 # # Most detail of request and response headers has been omitted. Assume # the user agent has no stored cookies. # # 1. User Agent -> Server # # POST /acme/login HTTP/1.1 # [form data] # # User identifies self via a form. # # 2. Server -> User Agent # # HTTP/1.1 200 OK # Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme" # # Cookie reflects user's identity. cookie = interact_2965( c, 'http://www.acme.com/acme/login', 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"') self.assertTrue(not cookie) # # 3. User Agent -> Server # # POST /acme/pickitem HTTP/1.1 # Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme" # [form data] # # User selects an item for ``shopping basket.'' # # 4. Server -> User Agent # # HTTP/1.1 200 OK # Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1"; # Path="/acme" # # Shopping basket contains an item. cookie = interact_2965(c, 'http://www.acme.com/acme/pickitem', 'Part_Number="Rocket_Launcher_0001"; ' 'Version="1"; Path="/acme"'); self.assertTrue(re.search( r'^\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \$Path="/acme"$', cookie)) # # 5. User Agent -> Server # # POST /acme/shipping HTTP/1.1 # Cookie: $Version="1"; # Customer="WILE_E_COYOTE"; $Path="/acme"; # Part_Number="Rocket_Launcher_0001"; $Path="/acme" # [form data] # # User selects shipping method from form. # # 6. Server -> User Agent # # HTTP/1.1 200 OK # Set-Cookie2: Shipping="FedEx"; Version="1"; Path="/acme" # # New cookie reflects shipping method. cookie = interact_2965(c, "http://www.acme.com/acme/shipping", 'Shipping="FedEx"; Version="1"; Path="/acme"') self.assertTrue(re.search(r'^\$Version="?1"?;', cookie)) self.assertTrue(re.search(r'Part_Number="?Rocket_Launcher_0001"?;' '\s*\$Path="\/acme"', cookie)) self.assertTrue(re.search(r'Customer="?WILE_E_COYOTE"?;\s*\$Path="\/acme"', cookie)) # # 7. User Agent -> Server # # POST /acme/process HTTP/1.1 # Cookie: $Version="1"; # Customer="WILE_E_COYOTE"; $Path="/acme"; # Part_Number="Rocket_Launcher_0001"; $Path="/acme"; # Shipping="FedEx"; $Path="/acme" # [form data] # # User chooses to process order. # # 8. Server -> User Agent # # HTTP/1.1 200 OK # # Transaction is complete. cookie = interact_2965(c, "http://www.acme.com/acme/process") self.assertTrue( re.search(r'Shipping="?FedEx"?;\s*\$Path="\/acme"', cookie) and "WILE_E_COYOTE" in cookie) # # The user agent makes a series of requests on the origin server, after # each of which it receives a new cookie. All the cookies have the same # Path attribute and (default) domain. Because the request URLs all have # /acme as a prefix, and that matches the Path attribute, each request # contains all the cookies received so far. def test_ietf_example_2(self): from cookielib import CookieJar, DefaultCookiePolicy # 5.2 Example 2 # # This example illustrates the effect of the Path attribute. All detail # of request and response headers has been omitted. Assume the user agent # has no stored cookies. c = CookieJar(DefaultCookiePolicy(rfc2965=True)) # Imagine the user agent has received, in response to earlier requests, # the response headers # # Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1"; # Path="/acme" # # and # # Set-Cookie2: Part_Number="Riding_Rocket_0023"; Version="1"; # Path="/acme/ammo" interact_2965( c, "http://www.acme.com/acme/ammo/specific", 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"', 'Part_Number="Riding_Rocket_0023"; Version="1"; Path="/acme/ammo"') # A subsequent request by the user agent to the (same) server for URLs of # the form /acme/ammo/... would include the following request header: # # Cookie: $Version="1"; # Part_Number="Riding_Rocket_0023"; $Path="/acme/ammo"; # Part_Number="Rocket_Launcher_0001"; $Path="/acme" # # Note that the NAME=VALUE pair for the cookie with the more specific Path # attribute, /acme/ammo, comes before the one with the less specific Path # attribute, /acme. Further note that the same cookie name appears more # than once. cookie = interact_2965(c, "http://www.acme.com/acme/ammo/...") self.assertTrue( re.search(r"Riding_Rocket_0023.*Rocket_Launcher_0001", cookie)) # A subsequent request by the user agent to the (same) server for a URL of # the form /acme/parts/ would include the following request header: # # Cookie: $Version="1"; Part_Number="Rocket_Launcher_0001"; $Path="/acme" # # Here, the second cookie's Path attribute /acme/ammo is not a prefix of # the request URL, /acme/parts/, so the cookie does not get forwarded to # the server. cookie = interact_2965(c, "http://www.acme.com/acme/parts/") self.assertIn("Rocket_Launcher_0001", cookie) self.assertNotIn("Riding_Rocket_0023", cookie) def test_rejection(self): # Test rejection of Set-Cookie2 responses based on domain, path, port. from cookielib import DefaultCookiePolicy, LWPCookieJar pol = DefaultCookiePolicy(rfc2965=True) c = LWPCookieJar(policy=pol) max_age = "max-age=3600" # illegal domain (no embedded dots) cookie = interact_2965(c, "http://www.acme.com", 'foo=bar; domain=".com"; version=1') self.assertTrue(not c) # legal domain cookie = interact_2965(c, "http://www.acme.com", 'ping=pong; domain="acme.com"; version=1') self.assertEqual(len(c), 1) # illegal domain (host prefix "www.a" contains a dot) cookie = interact_2965(c, "http://www.a.acme.com", 'whiz=bang; domain="acme.com"; version=1') self.assertEqual(len(c), 1) # legal domain cookie = interact_2965(c, "http://www.a.acme.com", 'wow=flutter; domain=".a.acme.com"; version=1') self.assertEqual(len(c), 2) # can't partially match an IP-address cookie = interact_2965(c, "http://125.125.125.125", 'zzzz=ping; domain="125.125.125"; version=1') self.assertEqual(len(c), 2) # illegal path (must be prefix of request path) cookie = interact_2965(c, "http://www.sol.no", 'blah=rhubarb; domain=".sol.no"; path="/foo"; ' 'version=1') self.assertEqual(len(c), 2) # legal path cookie = interact_2965(c, "http://www.sol.no/foo/bar", 'bing=bong; domain=".sol.no"; path="/foo"; ' 'version=1') self.assertEqual(len(c), 3) # illegal port (request-port not in list) cookie = interact_2965(c, "http://www.sol.no", 'whiz=ffft; domain=".sol.no"; port="90,100"; ' 'version=1') self.assertEqual(len(c), 3) # legal port cookie = interact_2965( c, "http://www.sol.no", r'bang=wallop; version=1; domain=".sol.no"; ' r'port="90,100, 80,8080"; ' r'max-age=100; Comment = "Just kidding! (\"|\\\\) "') self.assertEqual(len(c), 4) # port attribute without any value (current port) cookie = interact_2965(c, "http://www.sol.no", 'foo9=bar; version=1; domain=".sol.no"; port; ' 'max-age=100;') self.assertEqual(len(c), 5) # encoded path # LWP has this test, but unescaping allowed path characters seems # like a bad idea, so I think this should fail: ## cookie = interact_2965(c, "http://www.sol.no/foo/", ## r'foo8=bar; version=1; path="/%66oo"') # but this is OK, because '<' is not an allowed HTTP URL path # character: cookie = interact_2965(c, "http://www.sol.no/<oo/", r'foo8=bar; version=1; path="/%3coo"') self.assertEqual(len(c), 6) # save and restore filename = test_support.TESTFN try: c.save(filename, ignore_discard=True) old = repr(c) c = LWPCookieJar(policy=pol) c.load(filename, ignore_discard=True) finally: try: os.unlink(filename) except OSError: pass self.assertEqual(old, repr(c)) def test_url_encoding(self): # Try some URL encodings of the PATHs. # (the behaviour here has changed from libwww-perl) from cookielib import CookieJar, DefaultCookiePolicy c = CookieJar(DefaultCookiePolicy(rfc2965=True)) interact_2965(c, "http://www.acme.com/foo%2f%25/%3c%3c%0Anew%E5/%E5", "foo = bar; version = 1") cookie = interact_2965( c, "http://www.acme.com/foo%2f%25/<<%0anewå/æøå", 'bar=baz; path="/foo/"; version=1'); version_re = re.compile(r'^\$version=\"?1\"?', re.I) self.assertTrue("foo=bar" in cookie and version_re.search(cookie)) cookie = interact_2965( c, "http://www.acme.com/foo/%25/<<%0anewå/æøå") self.assertTrue(not cookie) # unicode URL doesn't raise exception cookie = interact_2965(c, u"http://www.acme.com/\xfc") def test_mozilla(self): # Save / load Mozilla/Netscape cookie file format. from cookielib import MozillaCookieJar, DefaultCookiePolicy year_plus_one = time.localtime()[0] + 1 filename = test_support.TESTFN c = MozillaCookieJar(filename, policy=DefaultCookiePolicy(rfc2965=True)) interact_2965(c, "http://www.acme.com/", "foo1=bar; max-age=100; Version=1") interact_2965(c, "http://www.acme.com/", 'foo2=bar; port="80"; max-age=100; Discard; Version=1') interact_2965(c, "http://www.acme.com/", "foo3=bar; secure; Version=1") expires = "expires=09-Nov-%d 23:12:40 GMT" % (year_plus_one,) interact_netscape(c, "http://www.foo.com/", "fooa=bar; %s" % expires) interact_netscape(c, "http://www.foo.com/", "foob=bar; Domain=.foo.com; %s" % expires) interact_netscape(c, "http://www.foo.com/", "fooc=bar; Domain=www.foo.com; %s" % expires) def save_and_restore(cj, ignore_discard): try: cj.save(ignore_discard=ignore_discard) new_c = MozillaCookieJar(filename, DefaultCookiePolicy(rfc2965=True)) new_c.load(ignore_discard=ignore_discard) finally: try: os.unlink(filename) except OSError: pass return new_c new_c = save_and_restore(c, True) self.assertEqual(len(new_c), 6) # none discarded self.assertIn("name='foo1', value='bar'", repr(new_c)) new_c = save_and_restore(c, False) self.assertEqual(len(new_c), 4) # 2 of them discarded on save self.assertIn("name='foo1', value='bar'", repr(new_c)) def test_netscape_misc(self): # Some additional Netscape cookies tests. from cookielib import CookieJar from urllib2 import Request c = CookieJar() headers = [] req = Request("http://foo.bar.acme.com/foo") # Netscape allows a host part that contains dots headers.append("Set-Cookie: Customer=WILE_E_COYOTE; domain=.acme.com") res = FakeResponse(headers, "http://www.acme.com/foo") c.extract_cookies(res, req) # and that the domain is the same as the host without adding a leading # dot to the domain. Should not quote even if strange chars are used # in the cookie value. headers.append("Set-Cookie: PART_NUMBER=3,4; domain=foo.bar.acme.com") res = FakeResponse(headers, "http://www.acme.com/foo") c.extract_cookies(res, req) req = Request("http://foo.bar.acme.com/foo") c.add_cookie_header(req) self.assertTrue( "PART_NUMBER=3,4" in req.get_header("Cookie") and "Customer=WILE_E_COYOTE" in req.get_header("Cookie")) def test_intranet_domains_2965(self): # Test handling of local intranet hostnames without a dot. from cookielib import CookieJar, DefaultCookiePolicy c = CookieJar(DefaultCookiePolicy(rfc2965=True)) interact_2965(c, "http://example/", "foo1=bar; PORT; Discard; Version=1;") cookie = interact_2965(c, "http://example/", 'foo2=bar; domain=".local"; Version=1') self.assertIn("foo1=bar", cookie) interact_2965(c, "http://example/", 'foo3=bar; Version=1') cookie = interact_2965(c, "http://example/") self.assertIn("foo2=bar", cookie) self.assertEqual(len(c), 3) def test_intranet_domains_ns(self): from cookielib import CookieJar, DefaultCookiePolicy c = CookieJar(DefaultCookiePolicy(rfc2965 = False)) interact_netscape(c, "http://example/", "foo1=bar") cookie = interact_netscape(c, "http://example/", 'foo2=bar; domain=.local') self.assertEqual(len(c), 2) self.assertIn("foo1=bar", cookie) cookie = interact_netscape(c, "http://example/") self.assertIn("foo2=bar", cookie) self.assertEqual(len(c), 2) def test_empty_path(self): from cookielib import CookieJar, DefaultCookiePolicy from urllib2 import Request # Test for empty path # Broken web-server ORION/1.3.38 returns to the client response like # # Set-Cookie: JSESSIONID=ABCDERANDOM123; Path= # # ie. with Path set to nothing. # In this case, extract_cookies() must set cookie to / (root) c = CookieJar(DefaultCookiePolicy(rfc2965 = True)) headers = [] req = Request("http://www.ants.com/") headers.append("Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=") res = FakeResponse(headers, "http://www.ants.com/") c.extract_cookies(res, req) req = Request("http://www.ants.com/") c.add_cookie_header(req) self.assertEqual(req.get_header("Cookie"), "JSESSIONID=ABCDERANDOM123") self.assertEqual(req.get_header("Cookie2"), '$Version="1"') # missing path in the request URI req = Request("http://www.ants.com:8080") c.add_cookie_header(req) self.assertEqual(req.get_header("Cookie"), "JSESSIONID=ABCDERANDOM123") self.assertEqual(req.get_header("Cookie2"), '$Version="1"') def test_session_cookies(self): from cookielib import CookieJar from urllib2 import Request year_plus_one = time.localtime()[0] + 1 # Check session cookies are deleted properly by # CookieJar.clear_session_cookies method req = Request('http://www.perlmeister.com/scripts') headers = [] headers.append("Set-Cookie: s1=session;Path=/scripts") headers.append("Set-Cookie: p1=perm; Domain=.perlmeister.com;" "Path=/;expires=Fri, 02-Feb-%d 23:24:20 GMT" % year_plus_one) headers.append("Set-Cookie: p2=perm;Path=/;expires=Fri, " "02-Feb-%d 23:24:20 GMT" % year_plus_one) headers.append("Set-Cookie: s2=session;Path=/scripts;" "Domain=.perlmeister.com") headers.append('Set-Cookie2: s3=session;Version=1;Discard;Path="/"') res = FakeResponse(headers, 'http://www.perlmeister.com/scripts') c = CookieJar() c.extract_cookies(res, req) # How many session/permanent cookies do we have? counter = {"session_after": 0, "perm_after": 0, "session_before": 0, "perm_before": 0} for cookie in c: key = "%s_before" % cookie.value counter[key] = counter[key] + 1 c.clear_session_cookies() # How many now? for cookie in c: key = "%s_after" % cookie.value counter[key] = counter[key] + 1 self.assertTrue(not ( # a permanent cookie got lost accidentally counter["perm_after"] != counter["perm_before"] or # a session cookie hasn't been cleared counter["session_after"] != 0 or # we didn't have session cookies in the first place counter["session_before"] == 0)) def test_main(verbose=None): test_support.run_unittest( DateTimeTests, HeaderTests, CookieTests, FileCookieJarTests, LWPCookieTests, ) if __name__ == "__main__": test_main(verbose=True)
gpl-3.0
Chenmxs/pyspider
pyspider/message_queue/rabbitmq.py
53
8696
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<17175297.hk@gmail.com> # http://binux.me # Created on 2012-11-15 17:27:54 import time import socket import select import logging import umsgpack import threading import amqp from six.moves import queue as BaseQueue from six.moves.urllib.parse import unquote try: from urllib import parse as urlparse except ImportError: import urlparse def catch_error(func): """Catch errors of rabbitmq then reconnect""" import amqp try: import pika.exceptions connect_exceptions = ( pika.exceptions.ConnectionClosed, pika.exceptions.AMQPConnectionError, ) except ImportError: connect_exceptions = () connect_exceptions += ( select.error, socket.error, amqp.ConnectionError ) def wrap(self, *args, **kwargs): try: return func(self, *args, **kwargs) except connect_exceptions as e: logging.error('RabbitMQ error: %r, reconnect.', e) self.reconnect() return func(self, *args, **kwargs) return wrap class PikaQueue(object): """ A Queue like rabbitmq connector """ Empty = BaseQueue.Empty Full = BaseQueue.Full max_timeout = 0.3 def __init__(self, name, amqp_url='amqp://guest:guest@localhost:5672/%2F', maxsize=0, lazy_limit=True): """ Constructor for a PikaQueue. Not works with python 3. Default for python 2. amqp_url: https://www.rabbitmq.com/uri-spec.html maxsize: an integer that sets the upperbound limit on the number of items that can be placed in the queue. lazy_limit: as rabbitmq is shared between multipul instance, for a strict limit on the number of items in the queue. PikaQueue have to update current queue size before every put operation. When `lazy_limit` is enabled, PikaQueue will check queue size every max_size / 10 put operation for better performace. """ self.name = name self.amqp_url = amqp_url self.maxsize = maxsize self.lock = threading.RLock() self.lazy_limit = lazy_limit if self.lazy_limit and self.maxsize: self.qsize_diff_limit = int(self.maxsize * 0.1) else: self.qsize_diff_limit = 0 self.qsize_diff = 0 self.reconnect() def reconnect(self): """Reconnect to rabbitmq server""" import pika import pika.exceptions self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url)) self.channel = self.connection.channel() try: self.channel.queue_declare(self.name) except pika.exceptions.ChannelClosed: self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url)) self.channel = self.connection.channel() #self.channel.queue_purge(self.name) @catch_error def qsize(self): with self.lock: ret = self.channel.queue_declare(self.name, passive=True) return ret.method.message_count def empty(self): if self.qsize() == 0: return True else: return False def full(self): if self.maxsize and self.qsize() >= self.maxsize: return True else: return False @catch_error def put(self, obj, block=True, timeout=None): if not block: return self.put_nowait() start_time = time.time() while True: try: return self.put_nowait(obj) except BaseQueue.Full: if timeout: lasted = time.time() - start_time if timeout > lasted: time.sleep(min(self.max_timeout, timeout - lasted)) else: raise else: time.sleep(self.max_timeout) @catch_error def put_nowait(self, obj): if self.lazy_limit and self.qsize_diff < self.qsize_diff_limit: pass elif self.full(): raise BaseQueue.Full else: self.qsize_diff = 0 with self.lock: self.qsize_diff += 1 return self.channel.basic_publish("", self.name, umsgpack.packb(obj)) @catch_error def get(self, block=True, timeout=None, ack=False): if not block: return self.get_nowait() start_time = time.time() while True: try: return self.get_nowait(ack) except BaseQueue.Empty: if timeout: lasted = time.time() - start_time if timeout > lasted: time.sleep(min(self.max_timeout, timeout - lasted)) else: raise else: time.sleep(self.max_timeout) @catch_error def get_nowait(self, ack=False): with self.lock: method_frame, header_frame, body = self.channel.basic_get(self.name, not ack) if method_frame is None: raise BaseQueue.Empty if ack: self.channel.basic_ack(method_frame.delivery_tag) return umsgpack.unpackb(body) @catch_error def delete(self): with self.lock: return self.channel.queue_delete(queue=self.name) class AmqpQueue(PikaQueue): Empty = BaseQueue.Empty Full = BaseQueue.Full max_timeout = 0.3 def __init__(self, name, amqp_url='amqp://guest:guest@localhost:5672/%2F', maxsize=0, lazy_limit=True): """ Constructor for a AmqpQueue. Default for python 3. amqp_url: https://www.rabbitmq.com/uri-spec.html maxsize: an integer that sets the upperbound limit on the number of items that can be placed in the queue. lazy_limit: as rabbitmq is shared between multipul instance, for a strict limit on the number of items in the queue. PikaQueue have to update current queue size before every put operation. When `lazy_limit` is enabled, PikaQueue will check queue size every max_size / 10 put operation for better performace. """ self.name = name self.amqp_url = amqp_url self.maxsize = maxsize self.lock = threading.RLock() self.lazy_limit = lazy_limit if self.lazy_limit and self.maxsize: self.qsize_diff_limit = int(self.maxsize * 0.1) else: self.qsize_diff_limit = 0 self.qsize_diff = 0 self.reconnect() def reconnect(self): """Reconnect to rabbitmq server""" parsed = urlparse.urlparse(self.amqp_url) port = parsed.port or 5672 self.connection = amqp.Connection(host="%s:%s" % (parsed.hostname, port), userid=parsed.username or 'guest', password=parsed.password or 'guest', virtual_host=unquote( parsed.path.lstrip('/') or '%2F')) self.channel = self.connection.channel() try: self.channel.queue_declare(self.name) except amqp.exceptions.PreconditionFailed: pass #self.channel.queue_purge(self.name) @catch_error def qsize(self): with self.lock: name, message_count, consumer_count = self.channel.queue_declare( self.name, passive=True) return message_count @catch_error def put_nowait(self, obj): if self.lazy_limit and self.qsize_diff < self.qsize_diff_limit: pass elif self.full(): raise BaseQueue.Full else: self.qsize_diff = 0 with self.lock: self.qsize_diff += 1 msg = amqp.Message(umsgpack.packb(obj)) return self.channel.basic_publish(msg, exchange="", routing_key=self.name) @catch_error def get_nowait(self, ack=False): with self.lock: message = self.channel.basic_get(self.name, not ack) if message is None: raise BaseQueue.Empty if ack: self.channel.basic_ack(message.delivery_tag) return umsgpack.unpackb(message.body) Queue = AmqpQueue
apache-2.0
nitinitprof/odoo
addons/stock_account/__openerp__.py
269
2348
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'WMS Accounting', 'version': '1.1', 'author': 'OpenERP SA', 'summary': 'Inventory, Logistic, Valuation, Accounting', 'description': """ WMS Accounting module ====================== This module makes the link between the 'stock' and 'account' modules and allows you to create accounting entries to value your stock movements Key Features ------------ * Stock Valuation (periodical or automatic) * Invoice from Picking Dashboard / Reports for Warehouse Management includes: ------------------------------------------------------ * Stock Inventory Value at given date (support dates in the past) """, 'website': 'https://www.odoo.com/page/warehouse', 'depends': ['stock', 'account'], 'category': 'Hidden', 'sequence': 16, 'demo': [ 'stock_account_demo.xml' ], 'data': [ 'security/stock_account_security.xml', 'security/ir.model.access.csv', 'stock_account_data.xml', 'wizard/stock_change_standard_price_view.xml', 'wizard/stock_invoice_onshipping_view.xml', 'wizard/stock_valuation_history_view.xml', 'wizard/stock_return_picking_view.xml', 'product_data.xml', 'product_view.xml', 'stock_account_view.xml', 'res_config_view.xml', ], 'test': [ ], 'installable': True, 'auto_install': True, }
agpl-3.0
grade-it/grader
redkyn-grader/grader/commands/list.py
2
3714
'''TODO: List command docs ''' import itertools import logging from collections import OrderedDict from functools import reduce from prettytable import PrettyTable from grader.models import Grader from grader.utils.config import require_grader_config logger = logging.getLogger(__name__) help = "List student submission(s)" def setup_parser(parser): parser.add_argument('--submissions', action='store_true', help="Show submissions for each assignment") parser.add_argument('--full', action='store_true', help="Show full length of values") parser.add_argument('--sortby', choices=["time", "user"], default="user", help="Show full length of values") parser.add_argument('assignment', nargs='?', help='Name of the assignment to list submissions for.') parser.set_defaults(run=run) def shorten(value, length=8, full=False): if full: return value return "{}...".format(value[0:length]) def get_sort_key(short_name): funcs = { 'time': "Import Time", 'user': "User ID", } return lambda x: x[funcs[short_name]] def sort_by_assignment(rows, sortby): grouped = itertools.groupby(rows, key=lambda x: x['Assignment']) grouped = [(k, sorted(list(g), key=get_sort_key(sortby))) for k, g in grouped] grouped = sorted(grouped, key=lambda x: x[0]) return reduce(lambda x, y: x + y[1], grouped, []) def build_assignment_info(assignments, full=False): info = [] for aname, assignment in assignments.items(): count, graded, failed = 0, 0, 0 for submission in assignment.submissions: count += 1 # graded += ? # failed += ? info.append(OrderedDict([ ("Assignment", aname), ("Total", count), ("Graded", graded), ("Failed", failed), ])) return info def build_submission_info(assignments, full=False): info = [] for aname, assignment in assignments.items(): for userid, submissions in assignment.submissions_by_user.items(): for submission in submissions: info.append(OrderedDict([ ("Assignment", aname), ("User ID", userid), ("Submission UUID", shorten(submission.uuid, full=full)), ("Import Time", str(submission.import_time)), ("Last File MTime", str(submission.latest_mtime)), ("Last Commit", str(submission.latest_commit)), ("SHA1", shorten(submission.sha1sum, full=full)), ("Re-Grades", len(submission.results_files)), ("Failed", "--"), ])) return info @require_grader_config def run(args): g = Grader(args.path) assignments = g.assignments a_info = build_assignment_info(assignments, full=args.full) s_info = build_submission_info(assignments, full=args.full) columns = [ "Assignment", "Total", "Graded", "Failed" ] rows = a_info if args.submissions: columns = [ "Assignment", "User ID", "Submission UUID", "Import Time", "Last File MTime", "Last Commit", "SHA1", "Re-Grades", "Failed" ] rows = s_info rows = sort_by_assignment(rows, args.sortby) if args.assignment: try: a = assignments[args.assignment] rows = [r for r in rows if r['Assignment'] == a.name] except KeyError: rows = [] t = PrettyTable(columns) for row in rows: t.add_row([row[c] for c in columns]) print(t)
mit
SeanCameronConklin/aima-python
tests/test_mdp.py
25
1392
import pytest from mdp import * # noqa def test_value_iteration(): assert value_iteration(sequential_decision_environment, .01) == {(3, 2): 1.0, (3, 1): -1.0, (3, 0): 0.12958868267972745, (0, 1): 0.39810203830605462, (0, 2): 0.50928545646220924, (1, 0): 0.25348746162470537, (0, 0): 0.29543540628363629, (1, 2): 0.64958064617168676, (2, 0): 0.34461306281476806, (2, 1): 0.48643676237737926, (2, 2): 0.79536093684710951} def test_policy_iteration(): assert policy_iteration(sequential_decision_environment) == {(0, 0): (0, 1), (0, 1): (0, 1), (0, 2): (1, 0), (1, 0): (1, 0), (1, 2): (1, 0), (2, 0): (0, 1), (2, 1): (0, 1), (2, 2): (1, 0), (3, 0): (-1, 0), (3, 1): None, (3, 2): None} def test_best_policy(): pi = best_policy(sequential_decision_environment, value_iteration(sequential_decision_environment, .01)) assert sequential_decision_environment.to_arrows(pi) == [['>', '>', '>', '.'], ['^', None, '^', '.'], ['^', '>', '^', '<']]
mit
albertomurillo/ansible
lib/ansible/module_utils/common/parameters.py
12
5167
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible.module_utils._text import to_native from ansible.module_utils.common._collections_compat import Mapping from ansible.module_utils.common.collections import is_iterable from ansible.module_utils.six import ( binary_type, integer_types, text_type, ) # Python2 & 3 way to get NoneType NoneType = type(None) # if adding boolean attribute, also add to PASS_BOOL # some of this dupes defaults from controller config PASS_VARS = { 'check_mode': ('check_mode', False), 'debug': ('_debug', False), 'diff': ('_diff', False), 'keep_remote_files': ('_keep_remote_files', False), 'module_name': ('_name', None), 'no_log': ('no_log', False), 'remote_tmp': ('_remote_tmp', None), 'selinux_special_fs': ('_selinux_special_fs', ['fuse', 'nfs', 'vboxsf', 'ramfs', '9p']), 'shell_executable': ('_shell', '/bin/sh'), 'socket': ('_socket_path', None), 'string_conversion_action': ('_string_conversion_action', 'warn'), 'syslog_facility': ('_syslog_facility', 'INFO'), 'tmpdir': ('_tmpdir', None), 'verbosity': ('_verbosity', 0), 'version': ('ansible_version', '0.0'), } PASS_BOOLS = ('check_mode', 'debug', 'diff', 'keep_remote_files', 'no_log') def _return_datastructure_name(obj): """ Return native stringified values from datastructures. For use with removing sensitive values pre-jsonification.""" if isinstance(obj, (text_type, binary_type)): if obj: yield to_native(obj, errors='surrogate_or_strict') return elif isinstance(obj, Mapping): for element in obj.items(): for subelement in _return_datastructure_name(element[1]): yield subelement elif is_iterable(obj): for element in obj: for subelement in _return_datastructure_name(element): yield subelement elif isinstance(obj, (bool, NoneType)): # This must come before int because bools are also ints return elif isinstance(obj, tuple(list(integer_types) + [float])): yield to_native(obj, nonstring='simplerepr') else: raise TypeError('Unknown parameter type: %s, %s' % (type(obj), obj)) def list_no_log_values(argument_spec, params): """Return set of no log values :arg argument_spec: An argument spec dictionary from a module :arg params: Dictionary of all module parameters :returns: Set of strings that should be hidden from output:: {'secret_dict_value', 'secret_list_item_one', 'secret_list_item_two', 'secret_string'} """ no_log_values = set() for arg_name, arg_opts in argument_spec.items(): if arg_opts.get('no_log', False): # Find the value for the no_log'd param no_log_object = params.get(arg_name, None) if no_log_object: no_log_values.update(_return_datastructure_name(no_log_object)) return no_log_values def list_deprecations(argument_spec, params): """Return a list of deprecations :arg argument_spec: An argument spec dictionary from a module :arg params: Dictionary of all module parameters :returns: List of dictionaries containing a message and version in which the deprecated parameter will be removed, or an empty list:: [{'msg': "Param 'deptest' is deprecated. See the module docs for more information", 'version': '2.9'}] """ deprecations = [] for arg_name, arg_opts in argument_spec.items(): if arg_opts.get('removed_in_version') is not None and arg_name in params: deprecations.append({ 'msg': "Param '%s' is deprecated. See the module docs for more information" % arg_name, 'version': arg_opts.get('removed_in_version') }) return deprecations def handle_aliases(argument_spec, params): """Return a two item tuple. The first is a dictionary of aliases, the second is a list of legal inputs.""" legal_inputs = ['_ansible_%s' % k for k in PASS_VARS] aliases_results = {} # alias:canon for (k, v) in argument_spec.items(): legal_inputs.append(k) aliases = v.get('aliases', None) default = v.get('default', None) required = v.get('required', False) if default is not None and required: # not alias specific but this is a good place to check this raise ValueError("internal error: required and default are mutually exclusive for %s" % k) if aliases is None: continue if not is_iterable(aliases) or isinstance(aliases, (binary_type, text_type)): raise TypeError('internal error: aliases must be a list or tuple') for alias in aliases: legal_inputs.append(alias) aliases_results[alias] = k if alias in params: params[k] = params[alias] return aliases_results, legal_inputs
gpl-3.0
farodin91/servo
tests/wpt/web-platform-tests/tools/pywebsocket/src/example/echo_noext_wsh.py
465
2404
# Copyright 2013, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. _GOODBYE_MESSAGE = u'Goodbye' def web_socket_do_extra_handshake(request): """Received Sec-WebSocket-Extensions header value is parsed into request.ws_requested_extensions. pywebsocket creates extension processors using it before do_extra_handshake call and never looks at it after the call. To reject requested extensions, clear the processor list. """ request.ws_extension_processors = [] def web_socket_transfer_data(request): """Echo. Same as echo_wsh.py.""" while True: line = request.ws_stream.receive_message() if line is None: return if isinstance(line, unicode): request.ws_stream.send_message(line, binary=False) if line == _GOODBYE_MESSAGE: return else: request.ws_stream.send_message(line, binary=True) # vi:sts=4 sw=4 et
mpl-2.0
Radium-Devices/android_kernel_motorola_msm8916
tools/perf/scripts/python/sctop.py
11180
1924
# system call top # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Periodically displays system-wide system call totals, broken down by # syscall. If a [comm] arg is specified, only syscalls called by # [comm] are displayed. If an [interval] arg is specified, the display # will be refreshed every [interval] seconds. The default interval is # 3 seconds. import os, sys, thread, time sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf script -s sctop.py [comm] [interval]\n"; for_comm = None default_interval = 3 interval = default_interval if len(sys.argv) > 3: sys.exit(usage) if len(sys.argv) > 2: for_comm = sys.argv[1] interval = int(sys.argv[2]) elif len(sys.argv) > 1: try: interval = int(sys.argv[1]) except ValueError: for_comm = sys.argv[1] interval = default_interval syscalls = autodict() def trace_begin(): thread.start_new_thread(print_syscall_totals, (interval,)) pass def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): if for_comm is not None: if common_comm != for_comm: return try: syscalls[id] += 1 except TypeError: syscalls[id] = 1 def print_syscall_totals(interval): while 1: clear_term() if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "----------"), for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \ reverse = True): try: print "%-40s %10d\n" % (syscall_name(id), val), except TypeError: pass syscalls.clear() time.sleep(interval)
gpl-2.0
vorwerkc/pymatgen
pymatgen/core/tests/test_xcfunc.py
5
2615
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from pymatgen.core.xcfunc import XcFunc from pymatgen.util.testing import PymatgenTest class LibxcFuncTest(PymatgenTest): def test_xcfunc_api(self): """Testing XcFunc API.""" # Aliases should be unique assert len(XcFunc.aliases()) == len(set(XcFunc.aliases())) # LDA-Teter ixc_1 = XcFunc.from_abinit_ixc(1) print(ixc_1) assert ixc_1.type == "LDA" assert ixc_1.name == "LDA_XC_TETER93" assert ixc_1 == ixc_1 assert ixc_1 == "LDA_XC_TETER93" assert ixc_1 != "PBE" assert ixc_1.name not in XcFunc.aliases() assert ixc_1 == XcFunc.from_name(ixc_1.name) # LDA-PW (in aliases) ixc_7 = XcFunc.from_abinit_ixc(7) assert ixc_7.type == "LDA" assert ixc_7.name == "PW" assert ixc_7.name in XcFunc.aliases() assert ixc_7.name == XcFunc.from_name(ixc_7.name) assert ixc_7 != ixc_1 # GGA-PBE from ixc == 11 (in aliases) ixc_11 = XcFunc.from_abinit_ixc(11) assert ixc_11.type == "GGA" and ixc_11.name == "PBE" assert ixc_11.name in XcFunc.aliases() assert ixc_1 != ixc_11 # Test asxc assert XcFunc.asxc(ixc_11) is ixc_11 assert XcFunc.asxc("PBE") == ixc_11 d = {ixc_11: ixc_11.name} print(d) assert "PBE" in d assert ixc_11 in d # Test if object can be serialized with Pickle. self.serialize_with_pickle(ixc_11, test_eq=True) # Test if object supports MSONable # TODO # print("in test", type(ixc_11.x), type(ixc_11.c), type(ixc_11.xc)) # ixc_11.x.as_dict() # self.assertMSONable(ixc_11) # GGA-PBE from ixc given in abinit-libxc mode ixc_101130 = XcFunc.from_abinit_ixc(-101130) assert ixc_101130.type == "GGA" and ixc_101130.name == "PBE" assert ixc_101130 == ixc_11 # GGA-PBE built from name gga_pbe = XcFunc.from_name("PBE") assert gga_pbe.type == "GGA" and gga_pbe.name == "PBE" assert ixc_11 == gga_pbe # Use X from GGA and C from LDA! unknown_xc = XcFunc.from_name("GGA_X_PBE+ LDA_C_PW") assert unknown_xc not in XcFunc.aliases() assert unknown_xc.type == "GGA+LDA" assert unknown_xc.name == "GGA_X_PBE+LDA_C_PW" gga_pbe = XcFunc.from_type_name("GGA", "GGA_X_PBE+GGA_C_PBE") assert gga_pbe.type == "GGA" and gga_pbe.name == "PBE" assert str(gga_pbe) == "PBE"
mit
credativUK/connector-magento
__unported__/magentoerpconnect/partner.py
1
25089
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2013 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import logging import xmlrpclib from collections import namedtuple from openerp.osv import fields, orm from openerp.addons.connector.queue.job import job from openerp.addons.connector.connector import ConnectorUnit from openerp.addons.connector.exception import MappingError from openerp.addons.connector.unit.backend_adapter import BackendAdapter from openerp.addons.connector.unit.mapper import (mapping, only_create, ImportMapper ) from openerp.addons.connector.exception import IDMissingInBackend from .unit.backend_adapter import GenericAdapter from .unit.import_synchronizer import (DelayedBatchImport, MagentoImportSynchronizer ) from .backend import magento from .connector import get_environment _logger = logging.getLogger(__name__) class res_partner(orm.Model): _inherit = 'res.partner' _columns = { 'magento_bind_ids': fields.one2many( 'magento.res.partner', 'openerp_id', string="Magento Bindings"), 'magento_address_bind_ids': fields.one2many( 'magento.address', 'openerp_id', string="Magento Address Bindings"), 'birthday': fields.date('Birthday'), 'company': fields.char('Company'), } def copy_data(self, cr, uid, id, default=None, context=None): if default is None: default = {} default['magento_bind_ids'] = False return super(res_partner, self).copy_data(cr, uid, id, default=default, context=context) def _address_fields(self, cr, uid, context=None): """ Returns the list of address fields that are synced from the parent when the `use_parent_address` flag is set. """ fields = super(res_partner, self)._address_fields(cr, uid, context=context) fields.append('company') return fields class magento_res_partner(orm.Model): _name = 'magento.res.partner' _inherit = 'magento.binding' _inherits = {'res.partner': 'openerp_id'} _description = 'Magento Partner' _rec_name = 'website_id' def _get_mag_partner_from_website(self, cr, uid, ids, context=None): mag_partner_obj = self.pool['magento.res.partner'] return mag_partner_obj.search( cr, uid, [('website_id', 'in', ids)], context=context) _columns = { 'openerp_id': fields.many2one('res.partner', string='Partner', required=True, ondelete='cascade'), 'backend_id': fields.related( 'website_id', 'backend_id', type='many2one', relation='magento.backend', string='Magento Backend', store={ 'magento.res.partner': (lambda self, cr, uid, ids, c=None: ids, ['website_id'], 10), 'magento.website': (_get_mag_partner_from_website, ['backend_id'], 20), }, readonly=True), 'website_id': fields.many2one('magento.website', string='Magento Website', required=True, ondelete='restrict'), 'group_id': fields.many2one('magento.res.partner.category', string='Magento Group (Category)'), 'created_at': fields.datetime('Created At (on Magento)', readonly=True), 'updated_at': fields.datetime('Updated At (on Magento)', readonly=True), 'emailid': fields.char('E-mail address'), 'taxvat': fields.char('Magento VAT'), 'newsletter': fields.boolean('Newsletter'), 'guest_customer': fields.boolean('Guest Customer'), 'consider_as_company': fields.boolean( 'Considered as company', help="An account imported with a 'company' in " "the billing address is considered as a company.\n " "The partner takes the name of the company and " "is not merged with the billing address."), } _sql_constraints = [ ('magento_uniq', 'unique(website_id, magento_id)', 'A partner with same ID on Magento already exists for this website.'), ] class magento_address(orm.Model): _name = 'magento.address' _inherit = 'magento.binding' _inherits = {'res.partner': 'openerp_id'} _description = 'Magento Address' _rec_name = 'backend_id' def _get_mag_address_from_partner(self, cr, uid, ids, context=None): mag_address_obj = self.pool['magento.address'] return mag_address_obj.search( cr, uid, [('magento_partner_id', 'in', ids)], context=context) _columns = { 'openerp_id': fields.many2one('res.partner', string='Partner', required=True, ondelete='cascade'), 'created_at': fields.datetime('Created At (on Magento)', readonly=True), 'updated_at': fields.datetime('Updated At (on Magento)', readonly=True), 'is_default_billing': fields.boolean('Default Invoice'), 'is_default_shipping': fields.boolean('Default Shipping'), 'magento_partner_id': fields.many2one('magento.res.partner', string='Magento Partner', required=True, ondelete='cascade'), 'backend_id': fields.related( 'magento_partner_id', 'backend_id', type='many2one', relation='magento.backend', string='Magento Backend', store={ 'magento.address': (lambda self, cr, uid, ids, c=None: ids, ['magento_partner_id'], 10), 'magento.res.partner': (_get_mag_address_from_partner, ['backend_id', 'website_id'], 20), }, readonly=True), 'website_id': fields.related( 'magento_partner_id', 'website_id', type='many2one', relation='magento.website', string='Magento Website', store={ 'magento.address': (lambda self, cr, uid, ids, c=None: ids, ['magento_partner_id'], 10), 'magento.res.partner': (_get_mag_address_from_partner, ['website_id'], 20), }, readonly=True), 'is_magento_order_address': fields.boolean( 'Address from a Magento Order'), } _sql_constraints = [ ('magento_uniq', 'unique(backend_id, magento_id)', 'A partner address with same ID on Magento already exists.'), ] @magento class PartnerAdapter(GenericAdapter): _model_name = 'magento.res.partner' _magento_model = 'customer' _admin_path = '/{model}/edit/id/{id}' def _call(self, method, arguments): try: return super(PartnerAdapter, self)._call(method, arguments) except xmlrpclib.Fault as err: # this is the error in the Magento API # when the customer does not exist if err.faultCode == 102: raise IDMissingInBackend else: raise def search(self, filters=None, from_date=None, magento_website_ids=None): """ Search records according to some criterias and returns a list of ids :rtype: list """ if filters is None: filters = {} if from_date is not None: # updated_at include the created records str_from_date = from_date.strftime('%Y/%m/%d %H:%M:%S') filters['updated_at'] = {'from': str_from_date} if magento_website_ids is not None: filters['website_id'] = {'in': magento_website_ids} # the search method is on ol_customer instead of customer return self._call('ol_customer.search', [filters] if filters else [{}]) @magento class PartnerBatchImport(DelayedBatchImport): """ Import the Magento Partners. For every partner in the list, a delayed job is created. """ _model_name = ['magento.res.partner'] def run(self, filters=None): """ Run the synchronization """ from_date = filters.pop('from_date', None) magento_website_ids = [filters.pop('magento_website_id')] record_ids = self.backend_adapter.search(filters, from_date, magento_website_ids) _logger.info('search for magento partners %s returned %s', filters, record_ids) for record_id in record_ids: self._import_record(record_id) @magento class PartnerImport(MagentoImportSynchronizer): _model_name = ['magento.res.partner'] def _import_dependencies(self): """ Import the dependencies for the record""" record = self.magento_record self._import_dependency(record['group_id'], 'magento.res.partner.category') @property def mapper(self): """ Return an instance of ``Mapper`` for the synchronization. The instanciation is delayed because some synchronisations do not need such an unit and the unit may not exist. For ``magento.res.partner``, we have a company mapper and a mapper, ensure we find the correct one here. :rtype: :py:class:`~.PartnerImportMapper` """ if self._mapper is None: get_unit = self.environment.get_connector_unit self._mapper = get_unit(PartnerImportMapper) return self._mapper def _after_import(self, partner_binding_id): """ Import the addresses """ get_unit = self.get_connector_unit_for_model book = get_unit(PartnerAddressBook, 'magento.address') book.import_addresses(self.magento_id, partner_binding_id) @magento class PartnerImportMapper(ImportMapper): _model_name = 'magento.res.partner' direct = [ ('email', 'email'), ('dob', 'birthday'), ('created_at', 'created_at'), ('updated_at', 'updated_at'), ('email', 'emailid'), ('taxvat', 'taxvat'), ('group_id', 'group_id'), ] @only_create @mapping def is_company(self, record): # partners are companies so we can bind # addresses on them return {'is_company': True} @mapping def names(self, record): # TODO create a glue module for base_surname parts = [part for part in (record['firstname'], record['middlename'], record['lastname']) if part] return {'name': ' '.join(parts)} @mapping def customer_group_id(self, record): # import customer groups binder = self.get_binder_for_model('magento.res.partner.category') category_id = binder.to_openerp(record['group_id'], unwrap=True) if category_id is None: raise MappingError("The partner category with " "magento id %s does not exist" % record['group_id']) # FIXME: should remove the previous tag (all the other tags from # the same backend) return {'category_id': [(4, category_id)]} @mapping def website_id(self, record): binder = self.get_binder_for_model('magento.website') website_id = binder.to_openerp(record['website_id']) return {'website_id': website_id} @mapping def lang(self, record): binder = self.get_binder_for_model('magento.storeview') binding_id = binder.to_openerp(record['store_id']) if binding_id: storeview = self.session.browse('magento.storeview', binding_id) if storeview.lang_id: return {'lang': storeview.lang_id.code} @only_create @mapping def customer(self, record): return {'customer': True} @mapping def type(self, record): return {'type': 'default'} @only_create @mapping def openerp_id(self, record): """ Will bind the customer on a existing partner with the same email """ sess = self.session partner_ids = sess.search('res.partner', [('email', '=', record['email']), ('customer', '=', True), # FIXME once it has been changed in openerp ('is_company', '=', True)]) if partner_ids: return {'openerp_id': partner_ids[0]} AddressInfos = namedtuple('AddressInfos', ['magento_record', 'partner_binding_id', 'merge']) @magento class PartnerAddressBook(ConnectorUnit): """ Import all addresses from the address book of a customer. This class is responsible to define which addresses should be imported and how (merge with the partner or not...). Then, it delegate the import to the appropriate importer. This is really intricate. The datamodel are different between Magento and OpenERP and we have many uses cases to cover. The first thing is that: - we do not import companies and individuals the same manner - we do not know if an account is a company -> we assume that if we found something in the company field of the billing address, the whole account is a company. Differences: - Individuals: we merge the billing address with the partner, so we'll end with 1 entity if the customer has 1 address - Companies: we never merge the addresses with the partner, but we use the company name of the billing address as name of the partner. We also copy the address informations from the billing address as default values. More information on: https://bugs.launchpad.net/openerp-connector/+bug/1193281 """ _model_name = 'magento.address' def import_addresses(self, magento_partner_id, partner_binding_id): get_unit = self.get_connector_unit_for_model addresses = self._get_address_infos(magento_partner_id, partner_binding_id) for address_id, infos in addresses: importer = get_unit(MagentoImportSynchronizer) importer.run(address_id, infos) def _get_address_infos(self, magento_partner_id, partner_binding_id): get_unit = self.get_connector_unit_for_model adapter = get_unit(BackendAdapter) mag_address_ids = adapter.search({'customer_id': {'eq': magento_partner_id}}) if not mag_address_ids: return for address_id in mag_address_ids: magento_record = adapter.read(address_id) # defines if the billing address is merged with the partner # or imported as a standalone contact merge = False if magento_record.get('is_default_billing'): if magento_record.get('company'): # when a company is there, we never merge the contact # with the partner. # Copy the billing address on the company # and use the name of the company for the name company_mapper = get_unit(CompanyImportMapper, 'magento.res.partner') map_record = company_mapper.map_record(magento_record) self.session.write('magento.res.partner', partner_binding_id, map_record.values()) else: # for B2C individual customers, merge with the main # partner merge = True # in the case if the billing address no longer # has a company, reset the flag self.session.write('magento.res.partner', partner_binding_id, {'consider_as_company': False}) address_infos = AddressInfos(magento_record=magento_record, partner_binding_id=partner_binding_id, merge=merge) yield address_id, address_infos class BaseAddressImportMapper(ImportMapper): """ Defines the base mappings for the imports in ``res.partner`` (state, country, ...) """ direct = [('postcode', 'zip'), ('city', 'city'), ('telephone', 'phone'), ('fax', 'fax'), ('company', 'company'), ] @mapping def state(self, record): if not record.get('region'): return state_ids = self.session.search('res.country.state', [('name', '=ilike', record['region'])]) if state_ids: return {'state_id': state_ids[0]} @mapping def country(self, record): if not record.get('country_id'): return country_ids = self.session.search( 'res.country', [('code', '=', record['country_id'])]) if country_ids: return {'country_id': country_ids[0]} @mapping def street(self, record): value = record['street'] lines = [line.strip() for line in value.split('\n') if line.strip()] if len(lines) == 1: result = {'street': lines[0], 'street2': False} elif len(lines) >= 2: result = {'street': lines[0], 'street2': u' - '.join(lines[1:])} else: result = {} return result @mapping def title(self, record): prefix = record['prefix'] title_id = False if prefix: title_ids = self.session.search('res.partner.title', [('domain', '=', 'contact'), ('shortcut', 'ilike', prefix)]) if title_ids: title_id = title_ids[0] else: title_id = self.session.create('res.partner.title', {'domain': 'contact', 'shortcut': prefix, 'name': prefix}) return {'title': title_id} @magento class CompanyImportMapper(BaseAddressImportMapper): """ Special mapping used when we import a company. A company is considered as such when the billing address of an account has something in the 'company' field. This is a very special mapping not used in the same way than the other. The billing address will exist as a contact, but we want to *copy* the data on the company. The input record is the billing address. The mapper returns data which will be written on the main partner, in other words, the company. The ``@only_create`` decorator would not have any effect here because the mapper is always called for updates. """ _model_name = 'magento.res.partner' direct = BaseAddressImportMapper.direct + [ ('company', 'name'), ] @mapping def consider_as_company(self, record): return {'consider_as_company': True} @magento class AddressAdapter(GenericAdapter): _model_name = 'magento.address' _magento_model = 'customer_address' def search(self, filters=None): """ Search records according to some criterias and returns a list of ids :rtype: list """ return [int(row['customer_address_id']) for row in self._call('%s.list' % self._magento_model, [filters] if filters else [{}])] @magento class AddressImport(MagentoImportSynchronizer): _model_name = ['magento.address'] def run(self, magento_id, address_infos): """ Run the synchronization """ self.address_infos = address_infos return super(AddressImport, self).run(magento_id) def _get_magento_data(self): """ Return the raw Magento data for ``self.magento_id`` """ # we already read the data from the Partner Importer if self.address_infos.magento_record: return self.address_infos.magento_record else: return super(AddressImport, self)._get_magento_data() def _define_partner_relationship(self, data): """ Link address with partner or parent company. """ partner_binding_id = self.address_infos.partner_binding_id partner_id = self.session.read('magento.res.partner', partner_binding_id, ['openerp_id'])['openerp_id'][0] if self.address_infos.merge: # it won't be imported as an independant address, # but will be linked with the main res.partner data['openerp_id'] = partner_id data['type'] = 'default' else: data['parent_id'] = partner_id partner = self.session.browse('res.partner', partner_id) data['lang'] = partner.lang data['magento_partner_id'] = self.address_infos.partner_binding_id return data def _create(self, data): data = self._define_partner_relationship(data) return super(AddressImport, self)._create(data) @magento class AddressImportMapper(BaseAddressImportMapper): _model_name = 'magento.address' # TODO fields not mapped: # "suffix"=>"a", # "vat_id"=>"12334", direct = BaseAddressImportMapper.direct + [ ('created_at', 'created_at'), ('updated_at', 'updated_at'), ('is_default_billing', 'is_default_billing'), ('is_default_shipping', 'is_default_shipping'), ('company', 'company'), ] @mapping def names(self, record): # TODO create a glue module for base_surname parts = [part for part in (record['firstname'], record.get('middlename'), record['lastname']) if part] return {'name': ' '.join(parts)} @mapping def use_parent_address(self, record): return {'use_parent_address': False} @mapping def type(self, record): if record.get('is_default_billing'): address_type = 'invoice' elif record.get('is_default_shipping'): address_type = 'delivery' else: address_type = 'contact' return {'type': address_type} @job def partner_import_batch(session, model_name, backend_id, filters=None): """ Prepare the import of partners modified on Magento """ if filters is None: filters = {} assert 'magento_website_id' in filters, ( 'Missing information about Magento Website') env = get_environment(session, model_name, backend_id) importer = env.get_connector_unit(PartnerBatchImport) importer.run(filters=filters)
agpl-3.0
GalaxyTab4/twrp_kernel_samsung_degaswifi
tools/perf/python/twatch.py
7370
1334
#! /usr/bin/python # -*- python -*- # -*- coding: utf-8 -*- # twatch - Experimental use of the perf python interface # Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com> # # This application is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; version 2. # # This application 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. import perf def main(): cpus = perf.cpu_map() threads = perf.thread_map() evsel = perf.evsel(task = 1, comm = 1, mmap = 0, wakeup_events = 1, watermark = 1, sample_id_all = 1, sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU | perf.SAMPLE_TID) evsel.open(cpus = cpus, threads = threads); evlist = perf.evlist(cpus, threads) evlist.add(evsel) evlist.mmap() while True: evlist.poll(timeout = -1) for cpu in cpus: event = evlist.read_on_cpu(cpu) if not event: continue print "cpu: %2d, pid: %4d, tid: %4d" % (event.sample_cpu, event.sample_pid, event.sample_tid), print event if __name__ == '__main__': main()
gpl-2.0
luotao1/Paddle
python/paddle/static/io.py
1
30947
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import errno import inspect import logging import os import warnings import six import numpy as np import paddle from paddle.fluid import ( core, Variable, CompiledProgram, default_main_program, Program, layers, unique_name, program_guard, ) from paddle.fluid.io import prepend_feed_ops, append_fetch_ops from paddle.fluid.framework import static_only, Parameter from paddle.fluid.executor import Executor, global_scope from paddle.fluid.log_helper import get_logger __all__ = [ 'save_inference_model', 'load_inference_model', 'serialize_program', 'serialize_persistables', 'save_to_file', 'deserialize_program', 'deserialize_persistables', 'load_from_file', 'normalize_program', ] _logger = get_logger( __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s') def _check_args(caller, args, supported_args=None, deprecated_args=None): supported_args = [] if supported_args is None else supported_args deprecated_args = [] if deprecated_args is None else deprecated_args for arg in args: if arg in deprecated_args: raise ValueError( "argument '{}' in function '{}' is deprecated, only {} are supported.". format(arg, caller, supported_args)) elif arg not in supported_args: raise ValueError( "function '{}' doesn't support argument '{}',\n only {} are supported.". format(caller, arg, supported_args)) def _check_vars(name, var_list): if not isinstance(var_list, list): var_list = [var_list] if not var_list or not all([isinstance(var, Variable) for var in var_list]): raise ValueError( "'{}' should be a Variable or a list of Variable.".format(name)) def _normalize_path_prefix(path_prefix): """ convert path_prefix to absolute path. """ if not isinstance(path_prefix, six.string_types): raise ValueError("'path_prefix' should be a string.") if path_prefix.endswith("/"): raise ValueError("'path_prefix' should not be a directory") path_prefix = os.path.normpath(path_prefix) path_prefix = os.path.abspath(path_prefix) return path_prefix def _get_valid_program(program=None): """ return default main program if program is None. """ if program is None: program = default_main_program() elif isinstance(program, CompiledProgram): program = program._program if program is None: raise TypeError( "The type of input program is invalid, expected tyep is Program, but received None" ) warnings.warn( "The input is a CompiledProgram, this is not recommended.") if not isinstance(program, Program): raise TypeError( "The type of input program is invalid, expected type is fluid.Program, but received %s" % type(program)) return program def _clone_var_in_block(block, var): assert isinstance(var, Variable) if var.desc.type() == core.VarDesc.VarType.LOD_TENSOR: return block.create_var( name=var.name, shape=var.shape, dtype=var.dtype, type=var.type, lod_level=var.lod_level, persistable=True) else: return block.create_var( name=var.name, shape=var.shape, dtype=var.dtype, type=var.type, persistable=True) def normalize_program(program, feed_vars, fetch_vars): """ :api_attr: Static Graph Normalize/Optimize a program according to feed_vars and fetch_vars. Args: program(Program): Specify a program you want to optimize. feed_vars(Variable | list[Variable]): Variables needed by inference. fetch_vars(Variable | list[Variable]): Variables returned by inference. Returns: Program: Normalized/Optimized program. Raises: TypeError: If `program` is not a Program, an exception is thrown. TypeError: If `feed_vars` is not a Variable or a list of Variable, an exception is thrown. TypeError: If `fetch_vars` is not a Variable or a list of Variable, an exception is thrown. Examples: .. code-block:: python import paddle paddle.enable_static() path_prefix = "./infer_model" # User defined network, here a softmax regession example image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') predict = paddle.static.nn.fc(image, 10, activation='softmax') loss = paddle.nn.functional.cross_entropy(predict, label) exe = paddle.static.Executor(paddle.CPUPlace()) exe.run(paddle.static.default_startup_program()) # normalize main program. program = default_main_program() normalized_program = paddle.static.normalize_program(program, [image], [predict]) """ if not isinstance(program, Program): raise TypeError( "program type must be `fluid.Program`, but received `%s`" % type(program)) if not isinstance(feed_vars, list): feed_vars = [feed_vars] if not all(isinstance(v, Variable) for v in feed_vars): raise TypeError( "feed_vars type must be a Variable or a list of Variable.") if not isinstance(fetch_vars, list): fetch_vars = [fetch_vars] if not all(isinstance(v, Variable) for v in fetch_vars): raise TypeError( "fetch_vars type must be a Variable or a list of Variable.") # remind users to set auc_states to 0 if auc op were found. for op in program.global_block().ops: # clear device of Op device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName() op._set_attr(device_attr_name, "") if op.type == 'auc': warnings.warn("Be sure that you have set auc states to 0 " "before saving inference model.") break # fix the bug that the activation op's output as target will be pruned. # will affect the inference performance. # TODO(Superjomn) add an IR pass to remove 1-scale op. with program_guard(program): uniq_fetch_vars = [] for i, var in enumerate(fetch_vars): var = layers.scale( var, 1., name="save_infer_model/scale_{}".format(i)) uniq_fetch_vars.append(var) fetch_vars = uniq_fetch_vars # serialize program copy_program = program.clone() global_block = copy_program.global_block() remove_op_idx = [] for i, op in enumerate(global_block.ops): op.desc.set_is_target(False) if op.type == "feed" or op.type == "fetch": remove_op_idx.append(i) for idx in remove_op_idx[::-1]: global_block._remove_op(idx) copy_program.desc.flush() feed_var_names = [var.name for var in feed_vars] copy_program = copy_program._prune_with_input( feeded_var_names=feed_var_names, targets=fetch_vars) copy_program = copy_program._inference_optimize(prune_read_op=True) fetch_var_names = [var.name for var in fetch_vars] prepend_feed_ops(copy_program, feed_var_names) append_fetch_ops(copy_program, fetch_var_names) copy_program.desc._set_version() return copy_program def is_persistable(var): """ Check whether the given variable is persistable. Args: var(Variable): The variable to be checked. Returns: bool: True if the given `var` is persistable False if not. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() param = fluid.default_main_program().global_block().var('fc.b') res = fluid.io.is_persistable(param) """ if var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH or \ var.desc.type() == core.VarDesc.VarType.FETCH_LIST or \ var.desc.type() == core.VarDesc.VarType.READER: return False return var.persistable @static_only def serialize_program(feed_vars, fetch_vars, **kwargs): """ :api_attr: Static Graph Serialize default main program according to feed_vars and fetch_vars. Args: feed_vars(Variable | list[Variable]): Variables needed by inference. fetch_vars(Variable | list[Variable]): Variables returned by inference. kwargs: Supported keys including 'program'.Attention please, kwargs is used for backward compatibility mainly. - program(Program): specify a program if you don't want to use default main program. Returns: bytes: serialized program. Raises: ValueError: If `feed_vars` is not a Variable or a list of Variable, an exception is thrown. ValueError: If `fetch_vars` is not a Variable or a list of Variable, an exception is thrown. Examples: .. code-block:: python import paddle paddle.enable_static() path_prefix = "./infer_model" # User defined network, here a softmax regession example image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') predict = paddle.static.nn.fc(image, 10, activation='softmax') loss = paddle.nn.functional.cross_entropy(predict, label) exe = paddle.static.Executor(paddle.CPUPlace()) exe.run(paddle.static.default_startup_program()) # serialize the default main program to bytes. serialized_program = paddle.static.serialize_program([image], [predict]) # deserialize bytes to program deserialized_program = paddle.static.deserialize_program(serialized_program) """ # verify feed_vars _check_vars('feed_vars', feed_vars) # verify fetch_vars _check_vars('fetch_vars', fetch_vars) program = _get_valid_program(kwargs.get('program', None)) program = normalize_program(program, feed_vars, fetch_vars) return _serialize_program(program) def _serialize_program(program): """ serialize given program to bytes. """ return program.desc.serialize_to_string() @static_only def serialize_persistables(feed_vars, fetch_vars, executor, **kwargs): """ :api_attr: Static Graph Serialize parameters using given executor and default main program according to feed_vars and fetch_vars. Args: feed_vars(Variable | list[Variable]): Variables needed by inference. fetch_vars(Variable | list[Variable]): Variables returned by inference. kwargs: Supported keys including 'program'.Attention please, kwargs is used for backward compatibility mainly. - program(Program): specify a program if you don't want to use default main program. Returns: bytes: serialized program. Raises: ValueError: If `feed_vars` is not a Variable or a list of Variable, an exception is thrown. ValueError: If `fetch_vars` is not a Variable or a list of Variable, an exception is thrown. Examples: .. code-block:: python import paddle paddle.enable_static() path_prefix = "./infer_model" # User defined network, here a softmax regession example image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') predict = paddle.static.nn.fc(image, 10, activation='softmax') loss = paddle.nn.functional.cross_entropy(predict, label) exe = paddle.static.Executor(paddle.CPUPlace()) exe.run(paddle.static.default_startup_program()) # serialize parameters to bytes. serialized_params = paddle.static.serialize_persistables([image], [predict], exe) # deserialize bytes to parameters. main_program = paddle.static.default_main_program() deserialized_params = paddle.static.deserialize_persistables(main_program, serialized_params, exe) """ # verify feed_vars _check_vars('feed_vars', feed_vars) # verify fetch_vars _check_vars('fetch_vars', fetch_vars) program = _get_valid_program(kwargs.get('program', None)) program = normalize_program(program, feed_vars, fetch_vars) return _serialize_persistables(program, executor) def _serialize_persistables(program, executor): """ Serialize parameters using given program and executor. """ vars_ = list(filter(is_persistable, program.list_vars())) # warn if no variable found in model if len(vars_) == 0: warnings.warn("no variable in your model, please ensure there are any " "variables in your model to save") return None # create a new program and clone persitable vars to it save_program = Program() save_block = save_program.global_block() save_var_map = {} for var in vars_: if var.type != core.VarDesc.VarType.RAW: var_copy = _clone_var_in_block(save_block, var) save_var_map[var_copy.name] = var # create in_vars and out_var, then append a save_combine op to save_program in_vars = [] for name in sorted(save_var_map.keys()): in_vars.append(save_var_map[name]) out_var_name = unique_name.generate("out_var") out_var = save_block.create_var( type=core.VarDesc.VarType.RAW, name=out_var_name) out_var.desc.set_persistable(True) save_block.append_op( type='save_combine', inputs={'X': in_vars}, outputs={'Y': out_var}, attrs={'file_path': '', 'save_to_memory': True}) # run save_program to save vars # NOTE(zhiqiu): save op will add variable kLookupTablePath to save_program.desc, # which leads to diff between save_program and its desc. Call _sync_with_cpp # to keep consistency. save_program._sync_with_cpp() executor.run(save_program) # return serialized bytes in out_var return global_scope().find_var(out_var_name).get_bytes() def save_to_file(path, content): """ Save content to given path. Args: path(str): Path to write content to. content(bytes): Content to write. Returns: None """ if not isinstance(content, bytes): raise ValueError("'content' type should be bytes.") with open(path, "wb") as f: f.write(content) @static_only def save_inference_model(path_prefix, feed_vars, fetch_vars, executor, **kwargs): """ :api_attr: Static Graph Save current model and its parameters to given path. i.e. Given path_prefix = "/path/to/modelname", after invoking save_inference_model(path_prefix, feed_vars, fetch_vars, executor), you will find two files named modelname.pdmodel and modelname.pdiparams under "/path/to", which represent your model and parameters respectively. Args: path_prefix(str): Directory path to save model + model name without suffix. feed_vars(Variable | list[Variable]): Variables needed by inference. fetch_vars(Variable | list[Variable]): Variables returned by inference. executor(Executor): The executor that saves the inference model. You can refer to :ref:`api_guide_executor_en` for more details. kwargs: Supported keys including 'program'.Attention please, kwargs is used for backward compatibility mainly. - program(Program): specify a program if you don't want to use default main program. Returns: None Raises: ValueError: If `feed_vars` is not a Variable or a list of Variable, an exception is thrown. ValueError: If `fetch_vars` is not a Variable or a list of Variable, an exception is thrown. Examples: .. code-block:: python import paddle paddle.enable_static() path_prefix = "./infer_model" # User defined network, here a softmax regession example image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') predict = paddle.static.nn.fc(image, 10, activation='softmax') loss = paddle.nn.functional.cross_entropy(predict, label) exe = paddle.static.Executor(paddle.CPUPlace()) exe.run(paddle.static.default_startup_program()) # Feed data and train process # Save inference model. Note we don't save label and loss in this example paddle.static.save_inference_model(path_prefix, [image], [predict], exe) # In this example, the save_inference_mode inference will prune the default # main program according to the network's input node (img) and output node(predict). # The pruned inference program is going to be saved in file "./infer_model.pdmodel" # and parameters are going to be saved in file "./infer_model.pdiparams". """ # check path_prefix, set model_path and params_path path_prefix = _normalize_path_prefix(path_prefix) try: # mkdir may conflict if pserver and trainer are running on the same machine dirname = os.path.dirname(path_prefix) os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise model_path = path_prefix + ".pdmodel" params_path = path_prefix + ".pdiparams" if os.path.isdir(model_path): raise ValueError("'{}' is an existing directory.".format(model_path)) if os.path.isdir(params_path): raise ValueError("'{}' is an existing directory.".format(params_path)) # verify feed_vars _check_vars('feed_vars', feed_vars) # verify fetch_vars _check_vars('fetch_vars', fetch_vars) program = _get_valid_program(kwargs.get('program', None)) program = normalize_program(program, feed_vars, fetch_vars) # serialize and save program program_bytes = _serialize_program(program) save_to_file(model_path, program_bytes) # serialize and save params params_bytes = _serialize_persistables(program, executor) save_to_file(params_path, params_bytes) @static_only def deserialize_program(data): """ :api_attr: Static Graph Deserialize given data to a program. Args: data(bytes): serialized program. Returns: Program: deserialized program. Examples: .. code-block:: python import paddle paddle.enable_static() path_prefix = "./infer_model" # User defined network, here a softmax regession example image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') predict = paddle.static.nn.fc(image, 10, activation='softmax') loss = paddle.nn.functional.cross_entropy(predict, label) exe = paddle.static.Executor(paddle.CPUPlace()) exe.run(paddle.static.default_startup_program()) # serialize the default main program to bytes. serialized_program = paddle.static.serialize_program([image], [predict]) # deserialize bytes to program deserialized_program = paddle.static.deserialize_program(serialized_program) """ program = Program.parse_from_string(data) if not core._is_program_version_supported(program._version()): raise ValueError("Unsupported program version: %d\n" % program._version()) return program @static_only def deserialize_persistables(program, data, executor): """ :api_attr: Static Graph Deserialize given data to parameters according to given program and executor. Args: program(Program): program that contains parameter names (to deserialize). data(bytes): serialized parameters. executor(Executor): executor used to run load op. Returns: Program: deserialized program. Examples: .. code-block:: python import paddle paddle.enable_static() path_prefix = "./infer_model" # User defined network, here a softmax regession example image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') predict = paddle.static.nn.fc(image, 10, activation='softmax') loss = paddle.nn.functional.cross_entropy(predict, label) exe = paddle.static.Executor(paddle.CPUPlace()) exe.run(paddle.static.default_startup_program()) # serialize parameters to bytes. serialized_params = paddle.static.serialize_persistables([image], [predict], exe) # deserialize bytes to parameters. main_program = paddle.static.default_main_program() deserialized_params = paddle.static.deserialize_persistables(main_program, serialized_params, exe) """ if not isinstance(program, Program): raise TypeError( "program type must be `fluid.Program`, but received `%s`" % type(program)) # load params to a tmp program load_program = Program() load_block = load_program.global_block() vars_ = list(filter(is_persistable, program.list_vars())) origin_shape_map = {} load_var_map = {} check_vars = [] sparse_vars = [] for var in vars_: assert isinstance(var, Variable) if var.type == core.VarDesc.VarType.RAW: continue if isinstance(var, Parameter): origin_shape_map[var.name] = tuple(var.desc.get_shape()) if var.type == core.VarDesc.VarType.SELECTED_ROWS: sparse_vars.append(var) continue var_copy = _clone_var_in_block(load_block, var) check_vars.append(var) load_var_map[var_copy.name] = var_copy # append load_combine op to load parameters, load_var_list = [] for name in sorted(load_var_map.keys()): load_var_list.append(load_var_map[name]) load_block.append_op( type='load_combine', inputs={}, outputs={"Out": load_var_list}, # if load from memory, file_path is data attrs={'file_path': data, 'model_from_memory': True}) executor.run(load_program) # check var shape for var in check_vars: if not isinstance(var, Parameter): continue var_tmp = paddle.fluid.global_scope().find_var(var.name) assert var_tmp != None, "can't not find var: " + var.name new_shape = (np.array(var_tmp.get_tensor())).shape assert var.name in origin_shape_map, var.name + " MUST in var list." origin_shape = origin_shape_map.get(var.name) if new_shape != origin_shape: raise RuntimeError( "Shape mismatch, program needs a parameter with shape ({}), " "but the loaded parameter ('{}') has a shape of ({}).".format( origin_shape, var.name, new_shape)) def load_from_file(path): """ Load file in binary mode. Args: path(str): Path of an existed file. Returns: bytes: Content of file. """ with open(path, 'rb') as f: data = f.read() return data @static_only def load_inference_model(path_prefix, executor, **kwargs): """ :api_attr: Static Graph Load inference model from a given path. By this API, you can get the model structure(Inference Program) and model parameters. Args: path_prefix(str | None): One of the following: - Directory path to save model + model name without suffix. - Set to None when reading the model from memory. executor(Executor): The executor to run for loading inference model. See :ref:`api_guide_executor_en` for more details about it. kwargs: Supported keys including 'model_filename', 'params_filename'.Attention please, kwargs is used for backward compatibility mainly. - model_filename(str): specify model_filename if you don't want to use default name. - params_filename(str): specify params_filename if you don't want to use default name. Returns: list: The return of this API is a list with three elements: (program, feed_target_names, fetch_targets). The `program` is a ``Program`` (refer to :ref:`api_guide_Program_en`), which is used for inference. The `feed_target_names` is a list of ``str``, which contains names of variables that need to feed data in the inference program. The `fetch_targets` is a list of ``Variable`` (refer to :ref:`api_guide_Program_en`). It contains variables from which we can get inference results. Raises: ValueError: If `path_prefix.pdmodel` or `path_prefix.pdiparams` doesn't exist. Examples: .. code-block:: python import paddle import numpy as np paddle.enable_static() # Build the model startup_prog = paddle.static.default_startup_program() main_prog = paddle.static.default_main_program() with paddle.static.program_guard(main_prog, startup_prog): image = paddle.static.data(name="img", shape=[64, 784]) w = paddle.create_parameter(shape=[784, 200], dtype='float32') b = paddle.create_parameter(shape=[200], dtype='float32') hidden_w = paddle.matmul(x=image, y=w) hidden_b = paddle.add(hidden_w, b) exe = paddle.static.Executor(paddle.CPUPlace()) exe.run(startup_prog) # Save the inference model path_prefix = "./infer_model" paddle.static.save_inference_model(path_prefix, [image], [hidden_b], exe) [inference_program, feed_target_names, fetch_targets] = ( paddle.static.load_inference_model(path_prefix, exe)) tensor_img = np.array(np.random.random((64, 784)), dtype=np.float32) results = exe.run(inference_program, feed={feed_target_names[0]: tensor_img}, fetch_list=fetch_targets) # In this example, the inference program was saved in file # "./infer_model.pdmodel" and parameters were saved in file # " ./infer_model.pdiparams". # By the inference program, feed_target_names and # fetch_targets, we can use an executor to run the inference # program to get the inference result. """ # check kwargs supported_args = ('model_filename', 'params_filename') deprecated_args = ('pserver_endpoints', ) caller = inspect.currentframe().f_code.co_name _check_args(caller, kwargs, supported_args, deprecated_args) # load from memory if path_prefix is None: _logger.warning("Load inference model from memory is deprecated.") model_filename = kwargs.get('model_filename', None) params_filename = kwargs.get('params_filename', None) if params_filename is None: raise ValueError( "params_filename cannot be None when path_prefix is None.") load_dirname = '' program_bytes = model_filename params_filename = params_filename # load from file else: # check and norm path_prefix path_prefix = _normalize_path_prefix(path_prefix) # set model_path and params_path in new way, # path_prefix represents a file path without suffix in this case. if not kwargs: model_path = path_prefix + ".pdmodel" params_path = path_prefix + ".pdiparams" # set model_path and params_path in old way for compatible, # path_prefix represents a directory path. else: model_filename = kwargs.get('model_filename', None) params_filename = kwargs.get('params_filename', None) # set model_path if model_filename is None: model_path = os.path.join(path_prefix, "__model__") else: model_path = os.path.join(path_prefix, model_filename + ".pdmodel") if not os.path.exists(model_path): model_path = os.path.join(path_prefix, model_filename) # set params_path if params_filename is None: params_path = os.path.join(path_prefix, "") else: params_path = os.path.join(path_prefix, params_filename + ".pdiparams") if not os.path.exists(params_path): params_path = os.path.join(path_prefix, params_filename) _logger.warning("The old way to load inference model is deprecated." " model path: {}, params path: {}".format( model_path, params_path)) program_bytes = load_from_file(model_path) load_dirname = os.path.dirname(params_path) params_filename = os.path.basename(params_path) # deserialize bytes to program program = deserialize_program(program_bytes) # load params data params_path = os.path.join(load_dirname, params_filename) params_bytes = load_from_file(params_path) # deserialize bytes to params deserialize_persistables(program, params_bytes, executor) feed_target_names = program.desc.get_feed_target_names() fetch_target_names = program.desc.get_fetch_target_names() fetch_targets = [ program.global_block().var(name) for name in fetch_target_names ] return [program, feed_target_names, fetch_targets]
apache-2.0
mwarkentin/ansible
lib/ansible/runner/lookup_plugins/env.py
22
1201
# (c) 2012, Jan-Piet Mens <jpmens(at)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/>. from ansible import utils, errors import os class LookupModule(object): def __init__(self, basedir=None, **kwargs): self.basedir = basedir def run(self, terms, inject=None, **kwargs): terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject) if isinstance(terms, basestring): terms = [ terms ] ret = [] for term in terms: var = term.split()[0] ret.append(os.getenv(var, '')) return ret
gpl-3.0
kirbyfan64/pygments-unofficial
pygments/styles/manni.py
135
2374
# -*- coding: utf-8 -*- """ pygments.styles.manni ~~~~~~~~~~~~~~~~~~~~~ A colorful style, inspired by the terminal highlighting style. This is a port of the style used in the `php port`_ of pygments by Manni. The style is called 'default' there. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class ManniStyle(Style): """ A colorful style, inspired by the terminal highlighting style. """ background_color = '#f0f3f3' styles = { Whitespace: '#bbbbbb', Comment: 'italic #0099FF', Comment.Preproc: 'noitalic #009999', Comment.Special: 'bold', Keyword: 'bold #006699', Keyword.Pseudo: 'nobold', Keyword.Type: '#007788', Operator: '#555555', Operator.Word: 'bold #000000', Name.Builtin: '#336666', Name.Function: '#CC00FF', Name.Class: 'bold #00AA88', Name.Namespace: 'bold #00CCFF', Name.Exception: 'bold #CC0000', Name.Variable: '#003333', Name.Constant: '#336600', Name.Label: '#9999FF', Name.Entity: 'bold #999999', Name.Attribute: '#330099', Name.Tag: 'bold #330099', Name.Decorator: '#9999FF', String: '#CC3300', String.Doc: 'italic', String.Interpol: '#AA0000', String.Escape: 'bold #CC3300', String.Regex: '#33AAAA', String.Symbol: '#FFCC33', String.Other: '#CC3300', Number: '#FF6600', Generic.Heading: 'bold #003300', Generic.Subheading: 'bold #003300', Generic.Deleted: 'border:#CC0000 bg:#FFCCCC', Generic.Inserted: 'border:#00CC00 bg:#CCFFCC', Generic.Error: '#FF0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: 'bold #000099', Generic.Output: '#AAAAAA', Generic.Traceback: '#99CC66', Error: 'bg:#FFAAAA #AA0000' }
bsd-2-clause
kemalakyol48/python-for-android
python3-alpha/python3-src/Lib/test/test_cgi.py
46
13764
from test.support import run_unittest, check_warnings import cgi import os import sys import tempfile import unittest from io import StringIO, BytesIO class HackedSysModule: # The regression test will have real values in sys.argv, which # will completely confuse the test of the cgi module argv = [] stdin = sys.stdin cgi.sys = HackedSysModule() class ComparableException: def __init__(self, err): self.err = err def __str__(self): return str(self.err) def __eq__(self, anExc): if not isinstance(anExc, Exception): return NotImplemented return (self.err.__class__ == anExc.__class__ and self.err.args == anExc.args) def __getattr__(self, attr): return getattr(self.err, attr) def do_test(buf, method): env = {} if method == "GET": fp = None env['REQUEST_METHOD'] = 'GET' env['QUERY_STRING'] = buf elif method == "POST": fp = BytesIO(buf.encode('latin-1')) # FieldStorage expects bytes env['REQUEST_METHOD'] = 'POST' env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' env['CONTENT_LENGTH'] = str(len(buf)) else: raise ValueError("unknown method: %s" % method) try: return cgi.parse(fp, env, strict_parsing=1) except Exception as err: return ComparableException(err) parse_strict_test_cases = [ ("", ValueError("bad query field: ''")), ("&", ValueError("bad query field: ''")), ("&&", ValueError("bad query field: ''")), (";", ValueError("bad query field: ''")), (";&;", ValueError("bad query field: ''")), # Should the next few really be valid? ("=", {}), ("=&=", {}), ("=;=", {}), # This rest seem to make sense ("=a", {'': ['a']}), ("&=a", ValueError("bad query field: ''")), ("=a&", ValueError("bad query field: ''")), ("=&a", ValueError("bad query field: 'a'")), ("b=a", {'b': ['a']}), ("b+=a", {'b ': ['a']}), ("a=b=a", {'a': ['b=a']}), ("a=+b=a", {'a': [' b=a']}), ("&b=a", ValueError("bad query field: ''")), ("b&=a", ValueError("bad query field: 'b'")), ("a=a+b&b=b+c", {'a': ['a b'], 'b': ['b c']}), ("a=a+b&a=b+a", {'a': ['a b', 'b a']}), ("x=1&y=2.0&z=2-3.%2b0", {'x': ['1'], 'y': ['2.0'], 'z': ['2-3.+0']}), ("x=1;y=2.0&z=2-3.%2b0", {'x': ['1'], 'y': ['2.0'], 'z': ['2-3.+0']}), ("x=1;y=2.0;z=2-3.%2b0", {'x': ['1'], 'y': ['2.0'], 'z': ['2-3.+0']}), ("Hbc5161168c542333633315dee1182227:key_store_seqid=400006&cuyer=r&view=bustomer&order_id=0bb2e248638833d48cb7fed300000f1b&expire=964546263&lobale=en-US&kid=130003.300038&ss=env", {'Hbc5161168c542333633315dee1182227:key_store_seqid': ['400006'], 'cuyer': ['r'], 'expire': ['964546263'], 'kid': ['130003.300038'], 'lobale': ['en-US'], 'order_id': ['0bb2e248638833d48cb7fed300000f1b'], 'ss': ['env'], 'view': ['bustomer'], }), ("group_id=5470&set=custom&_assigned_to=31392&_status=1&_category=100&SUBMIT=Browse", {'SUBMIT': ['Browse'], '_assigned_to': ['31392'], '_category': ['100'], '_status': ['1'], 'group_id': ['5470'], 'set': ['custom'], }) ] def norm(seq): return sorted(seq, key=repr) def first_elts(list): return [p[0] for p in list] def first_second_elts(list): return [(p[0], p[1][0]) for p in list] def gen_result(data, environ): encoding = 'latin-1' fake_stdin = BytesIO(data.encode(encoding)) fake_stdin.seek(0) form = cgi.FieldStorage(fp=fake_stdin, environ=environ, encoding=encoding) result = {} for k, v in dict(form).items(): result[k] = isinstance(v, list) and form.getlist(k) or v.value return result class CgiTests(unittest.TestCase): def test_strict(self): for orig, expect in parse_strict_test_cases: # Test basic parsing d = do_test(orig, "GET") self.assertEqual(d, expect, "Error parsing %s method GET" % repr(orig)) d = do_test(orig, "POST") self.assertEqual(d, expect, "Error parsing %s method POST" % repr(orig)) env = {'QUERY_STRING': orig} fs = cgi.FieldStorage(environ=env) if isinstance(expect, dict): # test dict interface self.assertEqual(len(expect), len(fs)) self.assertCountEqual(expect.keys(), fs.keys()) ##self.assertEqual(norm(expect.values()), norm(fs.values())) ##self.assertEqual(norm(expect.items()), norm(fs.items())) self.assertEqual(fs.getvalue("nonexistent field", "default"), "default") # test individual fields for key in expect.keys(): expect_val = expect[key] self.assertIn(key, fs) if len(expect_val) > 1: self.assertEqual(fs.getvalue(key), expect_val) else: self.assertEqual(fs.getvalue(key), expect_val[0]) def test_log(self): cgi.log("Testing") cgi.logfp = StringIO() cgi.initlog("%s", "Testing initlog 1") cgi.log("%s", "Testing log 2") self.assertEqual(cgi.logfp.getvalue(), "Testing initlog 1\nTesting log 2\n") if os.path.exists("/dev/null"): cgi.logfp = None cgi.logfile = "/dev/null" cgi.initlog("%s", "Testing log 3") def log_cleanup(): """Restore the global state of the log vars.""" cgi.logfile = '' cgi.logfp.close() cgi.logfp = None cgi.log = cgi.initlog self.addCleanup(log_cleanup) cgi.log("Testing log 4") def test_fieldstorage_readline(self): # FieldStorage uses readline, which has the capacity to read all # contents of the input file into memory; we use readline's size argument # to prevent that for files that do not contain any newlines in # non-GET/HEAD requests class TestReadlineFile: def __init__(self, file): self.file = file self.numcalls = 0 def readline(self, size=None): self.numcalls += 1 if size: return self.file.readline(size) else: return self.file.readline() def __getattr__(self, name): file = self.__dict__['file'] a = getattr(file, name) if not isinstance(a, int): setattr(self, name, a) return a f = TestReadlineFile(tempfile.TemporaryFile("wb+")) self.addCleanup(f.close) f.write(b'x' * 256 * 1024) f.seek(0) env = {'REQUEST_METHOD':'PUT'} fs = cgi.FieldStorage(fp=f, environ=env) self.addCleanup(fs.file.close) # if we're not chunking properly, readline is only called twice # (by read_binary); if we are chunking properly, it will be called 5 times # as long as the chunksize is 1 << 16. self.assertTrue(f.numcalls > 2) f.close() def test_fieldstorage_multipart(self): #Test basic FieldStorage multipart parsing env = { 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY), 'CONTENT_LENGTH': '558'} fp = BytesIO(POSTDATA.encode('latin-1')) fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1") self.assertEqual(len(fs.list), 4) expect = [{'name':'id', 'filename':None, 'value':'1234'}, {'name':'title', 'filename':None, 'value':''}, {'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'}, {'name':'submit', 'filename':None, 'value':' Add '}] for x in range(len(fs.list)): for k, exp in expect[x].items(): got = getattr(fs.list[x], k) self.assertEqual(got, exp) def test_fieldstorage_multipart_non_ascii(self): #Test basic FieldStorage multipart parsing env = {'REQUEST_METHOD':'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY), 'CONTENT_LENGTH':'558'} for encoding in ['iso-8859-1','utf-8']: fp = BytesIO(POSTDATA_NON_ASCII.encode(encoding)) fs = cgi.FieldStorage(fp, environ=env,encoding=encoding) self.assertEqual(len(fs.list), 1) expect = [{'name':'id', 'filename':None, 'value':'\xe7\xf1\x80'}] for x in range(len(fs.list)): for k, exp in expect[x].items(): got = getattr(fs.list[x], k) self.assertEqual(got, exp) _qs_result = { 'key1': 'value1', 'key2': ['value2x', 'value2y'], 'key3': 'value3', 'key4': 'value4' } def testQSAndUrlEncode(self): data = "key2=value2x&key3=value3&key4=value4" environ = { 'CONTENT_LENGTH': str(len(data)), 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'QUERY_STRING': 'key1=value1&key2=value2y', 'REQUEST_METHOD': 'POST', } v = gen_result(data, environ) self.assertEqual(self._qs_result, v) def testQSAndFormData(self): data = """---123 Content-Disposition: form-data; name="key2" value2y ---123 Content-Disposition: form-data; name="key3" value3 ---123 Content-Disposition: form-data; name="key4" value4 ---123-- """ environ = { 'CONTENT_LENGTH': str(len(data)), 'CONTENT_TYPE': 'multipart/form-data; boundary=-123', 'QUERY_STRING': 'key1=value1&key2=value2x', 'REQUEST_METHOD': 'POST', } v = gen_result(data, environ) self.assertEqual(self._qs_result, v) def testQSAndFormDataFile(self): data = """---123 Content-Disposition: form-data; name="key2" value2y ---123 Content-Disposition: form-data; name="key3" value3 ---123 Content-Disposition: form-data; name="key4" value4 ---123 Content-Disposition: form-data; name="upload"; filename="fake.txt" Content-Type: text/plain this is the content of the fake file ---123-- """ environ = { 'CONTENT_LENGTH': str(len(data)), 'CONTENT_TYPE': 'multipart/form-data; boundary=-123', 'QUERY_STRING': 'key1=value1&key2=value2x', 'REQUEST_METHOD': 'POST', } result = self._qs_result.copy() result.update({ 'upload': b'this is the content of the fake file\n' }) v = gen_result(data, environ) self.assertEqual(result, v) def test_deprecated_parse_qs(self): # this func is moved to urllib.parse, this is just a sanity check with check_warnings(('cgi.parse_qs is deprecated, use urllib.parse.' 'parse_qs instead', DeprecationWarning)): self.assertEqual({'a': ['A1'], 'B': ['B3'], 'b': ['B2']}, cgi.parse_qs('a=A1&b=B2&B=B3')) def test_deprecated_parse_qsl(self): # this func is moved to urllib.parse, this is just a sanity check with check_warnings(('cgi.parse_qsl is deprecated, use urllib.parse.' 'parse_qsl instead', DeprecationWarning)): self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')], cgi.parse_qsl('a=A1&b=B2&B=B3')) def test_parse_header(self): self.assertEqual( cgi.parse_header("text/plain"), ("text/plain", {})) self.assertEqual( cgi.parse_header("text/vnd.just.made.this.up ; "), ("text/vnd.just.made.this.up", {})) self.assertEqual( cgi.parse_header("text/plain;charset=us-ascii"), ("text/plain", {"charset": "us-ascii"})) self.assertEqual( cgi.parse_header('text/plain ; charset="us-ascii"'), ("text/plain", {"charset": "us-ascii"})) self.assertEqual( cgi.parse_header('text/plain ; charset="us-ascii"; another=opt'), ("text/plain", {"charset": "us-ascii", "another": "opt"})) self.assertEqual( cgi.parse_header('attachment; filename="silly.txt"'), ("attachment", {"filename": "silly.txt"})) self.assertEqual( cgi.parse_header('attachment; filename="strange;name"'), ("attachment", {"filename": "strange;name"})) self.assertEqual( cgi.parse_header('attachment; filename="strange;name";size=123;'), ("attachment", {"filename": "strange;name", "size": "123"})) BOUNDARY = "---------------------------721837373350705526688164684" POSTDATA = """-----------------------------721837373350705526688164684 Content-Disposition: form-data; name="id" 1234 -----------------------------721837373350705526688164684 Content-Disposition: form-data; name="title" -----------------------------721837373350705526688164684 Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain Testing 123. -----------------------------721837373350705526688164684 Content-Disposition: form-data; name="submit" Add\x20 -----------------------------721837373350705526688164684-- """ POSTDATA_NON_ASCII = """-----------------------------721837373350705526688164684 Content-Disposition: form-data; name="id" \xe7\xf1\x80 -----------------------------721837373350705526688164684 """ def test_main(): run_unittest(CgiTests) if __name__ == '__main__': test_main()
apache-2.0
tropp/acq4
acq4/modules/Patch/PatchTemplate.py
3
19449
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'PatchTemplate.ui' # # Created: Sat Feb 21 11:45:16 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(315, 464) self.verticalLayout_2 = QtGui.QVBoxLayout(Form) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setMargin(0) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.splitter_3 = QtGui.QSplitter(Form) self.splitter_3.setOrientation(QtCore.Qt.Vertical) self.splitter_3.setObjectName(_fromUtf8("splitter_3")) self.splitter_2 = QtGui.QSplitter(self.splitter_3) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(_fromUtf8("splitter_2")) self.layoutWidget = QtGui.QWidget(self.splitter_2) self.layoutWidget.setObjectName(_fromUtf8("layoutWidget")) self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget) self.verticalLayout.setSpacing(0) self.verticalLayout.setMargin(0) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.groupBox_2 = QtGui.QGroupBox(self.layoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().hasHeightForWidth()) self.groupBox_2.setSizePolicy(sizePolicy) self.groupBox_2.setTitle(_fromUtf8("")) self.groupBox_2.setObjectName(_fromUtf8("groupBox_2")) self.gridLayout_2 = QtGui.QGridLayout(self.groupBox_2) self.gridLayout_2.setMargin(0) self.gridLayout_2.setSpacing(0) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.vcPulseCheck = QtGui.QCheckBox(self.groupBox_2) self.vcPulseCheck.setChecked(True) self.vcPulseCheck.setObjectName(_fromUtf8("vcPulseCheck")) self.gridLayout_2.addWidget(self.vcPulseCheck, 2, 1, 1, 1) self.vcHoldCheck = QtGui.QCheckBox(self.groupBox_2) self.vcHoldCheck.setObjectName(_fromUtf8("vcHoldCheck")) self.gridLayout_2.addWidget(self.vcHoldCheck, 3, 1, 1, 1) self.icPulseCheck = QtGui.QCheckBox(self.groupBox_2) self.icPulseCheck.setChecked(True) self.icPulseCheck.setObjectName(_fromUtf8("icPulseCheck")) self.gridLayout_2.addWidget(self.icPulseCheck, 4, 1, 1, 1) self.icHoldCheck = QtGui.QCheckBox(self.groupBox_2) self.icHoldCheck.setObjectName(_fromUtf8("icHoldCheck")) self.gridLayout_2.addWidget(self.icHoldCheck, 6, 1, 1, 1) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_2.addItem(spacerItem, 7, 1, 1, 1) self.label = QtGui.QLabel(self.groupBox_2) self.label.setObjectName(_fromUtf8("label")) self.gridLayout_2.addWidget(self.label, 10, 0, 1, 2) self.label_3 = QtGui.QLabel(self.groupBox_2) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout_2.addWidget(self.label_3, 9, 0, 1, 2) self.label_4 = QtGui.QLabel(self.groupBox_2) self.label_4.setObjectName(_fromUtf8("label_4")) self.gridLayout_2.addWidget(self.label_4, 8, 0, 1, 2) self.icModeRadio = QtGui.QRadioButton(self.groupBox_2) self.icModeRadio.setObjectName(_fromUtf8("icModeRadio")) self.gridLayout_2.addWidget(self.icModeRadio, 4, 0, 1, 1) self.vcModeRadio = QtGui.QRadioButton(self.groupBox_2) self.vcModeRadio.setChecked(True) self.vcModeRadio.setObjectName(_fromUtf8("vcModeRadio")) self.gridLayout_2.addWidget(self.vcModeRadio, 2, 0, 1, 1) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.startBtn = QtGui.QPushButton(self.groupBox_2) self.startBtn.setCheckable(True) self.startBtn.setObjectName(_fromUtf8("startBtn")) self.horizontalLayout.addWidget(self.startBtn) self.recordBtn = QtGui.QPushButton(self.groupBox_2) self.recordBtn.setCheckable(True) self.recordBtn.setObjectName(_fromUtf8("recordBtn")) self.horizontalLayout.addWidget(self.recordBtn) self.gridLayout_2.addLayout(self.horizontalLayout, 0, 0, 1, 3) self.icPulseSpin = SpinBox(self.groupBox_2) self.icPulseSpin.setObjectName(_fromUtf8("icPulseSpin")) self.gridLayout_2.addWidget(self.icPulseSpin, 4, 2, 1, 1) self.pulseTimeSpin = SpinBox(self.groupBox_2) self.pulseTimeSpin.setSingleStep(1.0) self.pulseTimeSpin.setObjectName(_fromUtf8("pulseTimeSpin")) self.gridLayout_2.addWidget(self.pulseTimeSpin, 9, 2, 1, 1) self.delayTimeSpin = SpinBox(self.groupBox_2) self.delayTimeSpin.setMinimum(1.0) self.delayTimeSpin.setMaximum(10000.0) self.delayTimeSpin.setSingleStep(1.0) self.delayTimeSpin.setObjectName(_fromUtf8("delayTimeSpin")) self.gridLayout_2.addWidget(self.delayTimeSpin, 8, 2, 1, 1) self.vcPulseSpin = SpinBox(self.groupBox_2) self.vcPulseSpin.setObjectName(_fromUtf8("vcPulseSpin")) self.gridLayout_2.addWidget(self.vcPulseSpin, 2, 2, 1, 1) self.icHoldSpin = SpinBox(self.groupBox_2) self.icHoldSpin.setObjectName(_fromUtf8("icHoldSpin")) self.gridLayout_2.addWidget(self.icHoldSpin, 5, 2, 2, 1) self.cycleTimeSpin = SpinBox(self.groupBox_2) self.cycleTimeSpin.setSingleStep(1.0) self.cycleTimeSpin.setProperty("value", 0.2) self.cycleTimeSpin.setObjectName(_fromUtf8("cycleTimeSpin")) self.gridLayout_2.addWidget(self.cycleTimeSpin, 10, 2, 1, 1) self.vcHoldSpin = SpinBox(self.groupBox_2) self.vcHoldSpin.setObjectName(_fromUtf8("vcHoldSpin")) self.gridLayout_2.addWidget(self.vcHoldSpin, 3, 2, 1, 1) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setSpacing(0) self.horizontalLayout_2.setContentsMargins(0, -1, -1, -1) self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.bathModeBtn = QtGui.QToolButton(self.groupBox_2) self.bathModeBtn.setObjectName(_fromUtf8("bathModeBtn")) self.horizontalLayout_2.addWidget(self.bathModeBtn) self.patchModeBtn = QtGui.QToolButton(self.groupBox_2) self.patchModeBtn.setObjectName(_fromUtf8("patchModeBtn")) self.horizontalLayout_2.addWidget(self.patchModeBtn) self.cellModeBtn = QtGui.QToolButton(self.groupBox_2) self.cellModeBtn.setObjectName(_fromUtf8("cellModeBtn")) self.horizontalLayout_2.addWidget(self.cellModeBtn) self.monitorModeBtn = QtGui.QToolButton(self.groupBox_2) self.monitorModeBtn.setObjectName(_fromUtf8("monitorModeBtn")) self.horizontalLayout_2.addWidget(self.monitorModeBtn) spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem1) self.gridLayout_2.addLayout(self.horizontalLayout_2, 1, 0, 1, 3) self.label_2 = QtGui.QLabel(self.groupBox_2) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout_2.addWidget(self.label_2, 11, 0, 1, 1) self.averageSpin = QtGui.QSpinBox(self.groupBox_2) self.averageSpin.setMinimum(1) self.averageSpin.setMaximum(100) self.averageSpin.setProperty("value", 1) self.averageSpin.setObjectName(_fromUtf8("averageSpin")) self.gridLayout_2.addWidget(self.averageSpin, 11, 2, 1, 1) self.verticalLayout.addWidget(self.groupBox_2) self.groupBox = QtGui.QGroupBox(self.layoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth()) self.groupBox.setSizePolicy(sizePolicy) self.groupBox.setTitle(_fromUtf8("")) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.gridLayout = QtGui.QGridLayout(self.groupBox) self.gridLayout.setMargin(0) self.gridLayout.setHorizontalSpacing(5) self.gridLayout.setVerticalSpacing(0) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.restingPotentialCheck = QtGui.QCheckBox(self.groupBox) self.restingPotentialCheck.setText(_fromUtf8("")) self.restingPotentialCheck.setObjectName(_fromUtf8("restingPotentialCheck")) self.gridLayout.addWidget(self.restingPotentialCheck, 3, 0, 1, 1) self.restingPotentialLabel = QtGui.QLabel(self.groupBox) self.restingPotentialLabel.setMinimumSize(QtCore.QSize(140, 0)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.restingPotentialLabel.setFont(font) self.restingPotentialLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.restingPotentialLabel.setObjectName(_fromUtf8("restingPotentialLabel")) self.gridLayout.addWidget(self.restingPotentialLabel, 3, 2, 1, 1) self.restingCurrentCheck = QtGui.QCheckBox(self.groupBox) self.restingCurrentCheck.setText(_fromUtf8("")) self.restingCurrentCheck.setObjectName(_fromUtf8("restingCurrentCheck")) self.gridLayout.addWidget(self.restingCurrentCheck, 4, 0, 1, 1) self.fitErrorCheck = QtGui.QCheckBox(self.groupBox) self.fitErrorCheck.setText(_fromUtf8("")) self.fitErrorCheck.setObjectName(_fromUtf8("fitErrorCheck")) self.gridLayout.addWidget(self.fitErrorCheck, 6, 0, 1, 1) self.fitErrorLabel = QtGui.QLabel(self.groupBox) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.fitErrorLabel.setFont(font) self.fitErrorLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.fitErrorLabel.setObjectName(_fromUtf8("fitErrorLabel")) self.gridLayout.addWidget(self.fitErrorLabel, 6, 2, 1, 1) self.drawFitCheck = QtGui.QCheckBox(self.groupBox) self.drawFitCheck.setChecked(True) self.drawFitCheck.setObjectName(_fromUtf8("drawFitCheck")) self.gridLayout.addWidget(self.drawFitCheck, 0, 2, 1, 1) self.accessResistanceLabel = QtGui.QLabel(self.groupBox) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.accessResistanceLabel.setFont(font) self.accessResistanceLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.accessResistanceLabel.setObjectName(_fromUtf8("accessResistanceLabel")) self.gridLayout.addWidget(self.accessResistanceLabel, 2, 2, 1, 1) self.inputResistanceLabel = QtGui.QLabel(self.groupBox) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.inputResistanceLabel.setFont(font) self.inputResistanceLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.inputResistanceLabel.setObjectName(_fromUtf8("inputResistanceLabel")) self.gridLayout.addWidget(self.inputResistanceLabel, 1, 2, 1, 1) self.accessResistanceCheck = QtGui.QCheckBox(self.groupBox) self.accessResistanceCheck.setText(_fromUtf8("")) self.accessResistanceCheck.setObjectName(_fromUtf8("accessResistanceCheck")) self.gridLayout.addWidget(self.accessResistanceCheck, 2, 0, 1, 1) self.restingCurrentLabel = QtGui.QLabel(self.groupBox) self.restingCurrentLabel.setMinimumSize(QtCore.QSize(120, 0)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.restingCurrentLabel.setFont(font) self.restingCurrentLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.restingCurrentLabel.setObjectName(_fromUtf8("restingCurrentLabel")) self.gridLayout.addWidget(self.restingCurrentLabel, 4, 2, 1, 1) self.inputResistanceCheck = QtGui.QCheckBox(self.groupBox) self.inputResistanceCheck.setMaximumSize(QtCore.QSize(20, 16777215)) self.inputResistanceCheck.setText(_fromUtf8("")) self.inputResistanceCheck.setChecked(True) self.inputResistanceCheck.setObjectName(_fromUtf8("inputResistanceCheck")) self.gridLayout.addWidget(self.inputResistanceCheck, 1, 0, 1, 1) self.capacitanceCheck = QtGui.QCheckBox(self.groupBox) self.capacitanceCheck.setText(_fromUtf8("")) self.capacitanceCheck.setObjectName(_fromUtf8("capacitanceCheck")) self.gridLayout.addWidget(self.capacitanceCheck, 5, 0, 1, 1) self.capacitanceLabel = QtGui.QLabel(self.groupBox) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.capacitanceLabel.setFont(font) self.capacitanceLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.capacitanceLabel.setObjectName(_fromUtf8("capacitanceLabel")) self.gridLayout.addWidget(self.capacitanceLabel, 5, 2, 1, 1) self.label_5 = QtGui.QLabel(self.groupBox) self.label_5.setObjectName(_fromUtf8("label_5")) self.gridLayout.addWidget(self.label_5, 1, 1, 1, 1) self.resetBtn = QtGui.QToolButton(self.groupBox) self.resetBtn.setObjectName(_fromUtf8("resetBtn")) self.gridLayout.addWidget(self.resetBtn, 0, 0, 1, 2) self.label_6 = QtGui.QLabel(self.groupBox) self.label_6.setObjectName(_fromUtf8("label_6")) self.gridLayout.addWidget(self.label_6, 2, 1, 1, 1) self.label_7 = QtGui.QLabel(self.groupBox) self.label_7.setObjectName(_fromUtf8("label_7")) self.gridLayout.addWidget(self.label_7, 3, 1, 1, 1) self.label_8 = QtGui.QLabel(self.groupBox) self.label_8.setObjectName(_fromUtf8("label_8")) self.gridLayout.addWidget(self.label_8, 4, 1, 1, 1) self.label_9 = QtGui.QLabel(self.groupBox) self.label_9.setObjectName(_fromUtf8("label_9")) self.gridLayout.addWidget(self.label_9, 5, 1, 1, 1) self.label_10 = QtGui.QLabel(self.groupBox) self.label_10.setObjectName(_fromUtf8("label_10")) self.gridLayout.addWidget(self.label_10, 6, 1, 1, 1) self.verticalLayout.addWidget(self.groupBox) self.splitter = QtGui.QSplitter(self.splitter_2) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(_fromUtf8("splitter")) self.patchPlot = PlotWidget(self.splitter) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.patchPlot.sizePolicy().hasHeightForWidth()) self.patchPlot.setSizePolicy(sizePolicy) self.patchPlot.setObjectName(_fromUtf8("patchPlot")) self.commandPlot = PlotWidget(self.splitter) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.commandPlot.sizePolicy().hasHeightForWidth()) self.commandPlot.setSizePolicy(sizePolicy) self.commandPlot.setObjectName(_fromUtf8("commandPlot")) self.layoutWidget1 = QtGui.QWidget(self.splitter_3) self.layoutWidget1.setObjectName(_fromUtf8("layoutWidget1")) self.plotLayout = QtGui.QVBoxLayout(self.layoutWidget1) self.plotLayout.setSpacing(0) self.plotLayout.setMargin(0) self.plotLayout.setObjectName(_fromUtf8("plotLayout")) self.verticalLayout_2.addWidget(self.splitter_3) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Patch", None)) self.vcPulseCheck.setText(_translate("Form", "Pulse", None)) self.vcHoldCheck.setText(_translate("Form", "Hold", None)) self.icPulseCheck.setText(_translate("Form", "Pulse", None)) self.icHoldCheck.setText(_translate("Form", "Hold", None)) self.label.setText(_translate("Form", "Cycle Time", None)) self.label_3.setText(_translate("Form", "Pulse Length", None)) self.label_4.setText(_translate("Form", "Delay Length", None)) self.icModeRadio.setText(_translate("Form", "IC", None)) self.vcModeRadio.setText(_translate("Form", "VC", None)) self.startBtn.setText(_translate("Form", "Start", None)) self.recordBtn.setText(_translate("Form", "Record", None)) self.icPulseSpin.setSuffix(_translate("Form", "A", None)) self.pulseTimeSpin.setSuffix(_translate("Form", "s", None)) self.delayTimeSpin.setSuffix(_translate("Form", "s", None)) self.vcPulseSpin.setSuffix(_translate("Form", "V", None)) self.icHoldSpin.setSuffix(_translate("Form", "A", None)) self.cycleTimeSpin.setSuffix(_translate("Form", "s", None)) self.vcHoldSpin.setSuffix(_translate("Form", "V", None)) self.bathModeBtn.setText(_translate("Form", "Bath", None)) self.patchModeBtn.setText(_translate("Form", "Patch", None)) self.cellModeBtn.setText(_translate("Form", "Cell", None)) self.monitorModeBtn.setText(_translate("Form", "Monitor", None)) self.label_2.setText(_translate("Form", "Average", None)) self.restingPotentialLabel.setText(_translate("Form", "0", None)) self.fitErrorLabel.setText(_translate("Form", "0", None)) self.drawFitCheck.setText(_translate("Form", "Draw Fit", None)) self.accessResistanceLabel.setText(_translate("Form", "0", None)) self.inputResistanceLabel.setText(_translate("Form", "0", None)) self.restingCurrentLabel.setText(_translate("Form", "0", None)) self.capacitanceLabel.setText(_translate("Form", "0", None)) self.label_5.setText(_translate("Form", "Input Res.", None)) self.resetBtn.setText(_translate("Form", "Reset History", None)) self.label_6.setText(_translate("Form", "Access Res.", None)) self.label_7.setText(_translate("Form", "Rest Potential", None)) self.label_8.setText(_translate("Form", "Rest Current", None)) self.label_9.setText(_translate("Form", "Capacitance", None)) self.label_10.setText(_translate("Form", "Fit Error", None)) from acq4.pyqtgraph import SpinBox, PlotWidget
mit
Erotemic/hotspotter
hsgui/_frontend/EditPrefSkel.py
1
2626
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/joncrall/code/hotspotter/hsgui/_frontend/EditPrefSkel.ui' # # Created: Mon Feb 10 13:40:41 2014 # by: PyQt4 UI code generator 4.9.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_editPrefSkel(object): def setupUi(self, editPrefSkel): editPrefSkel.setObjectName(_fromUtf8("editPrefSkel")) editPrefSkel.resize(668, 530) self.verticalLayout = QtGui.QVBoxLayout(editPrefSkel) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.prefTreeView = QtGui.QTreeView(editPrefSkel) self.prefTreeView.setObjectName(_fromUtf8("prefTreeView")) self.verticalLayout.addWidget(self.prefTreeView) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.redrawBUT = QtGui.QPushButton(editPrefSkel) self.redrawBUT.setObjectName(_fromUtf8("redrawBUT")) self.horizontalLayout.addWidget(self.redrawBUT) self.unloadFeaturesAndModelsBUT = QtGui.QPushButton(editPrefSkel) self.unloadFeaturesAndModelsBUT.setObjectName(_fromUtf8("unloadFeaturesAndModelsBUT")) self.horizontalLayout.addWidget(self.unloadFeaturesAndModelsBUT) self.defaultPrefsBUT = QtGui.QPushButton(editPrefSkel) self.defaultPrefsBUT.setObjectName(_fromUtf8("defaultPrefsBUT")) self.horizontalLayout.addWidget(self.defaultPrefsBUT) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(editPrefSkel) QtCore.QMetaObject.connectSlotsByName(editPrefSkel) def retranslateUi(self, editPrefSkel): editPrefSkel.setWindowTitle(QtGui.QApplication.translate("editPrefSkel", "Edit Preferences", None, QtGui.QApplication.UnicodeUTF8)) self.redrawBUT.setText(QtGui.QApplication.translate("editPrefSkel", "Redraw", None, QtGui.QApplication.UnicodeUTF8)) self.unloadFeaturesAndModelsBUT.setText(QtGui.QApplication.translate("editPrefSkel", "Unload Features and Models", None, QtGui.QApplication.UnicodeUTF8)) self.defaultPrefsBUT.setText(QtGui.QApplication.translate("editPrefSkel", "Defaults", None, QtGui.QApplication.UnicodeUTF8)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) editPrefSkel = QtGui.QWidget() ui = Ui_editPrefSkel() ui.setupUi(editPrefSkel) editPrefSkel.show() sys.exit(app.exec_())
apache-2.0
canaltinova/servo
tests/wpt/web-platform-tests/tools/third_party/funcsigs/tests/test_inspect.py
40
37844
# Copyright 2001-2013 Python Software Foundation; All Rights Reserved from __future__ import absolute_import, division, print_function import collections import sys try: import unittest2 as unittest except ImportError: import unittest import funcsigs as inspect class TestSignatureObject(unittest.TestCase): @staticmethod def signature(func): sig = inspect.signature(func) return (tuple((param.name, (Ellipsis if param.default is param.empty else param.default), (Ellipsis if param.annotation is param.empty else param.annotation), str(param.kind).lower()) for param in sig.parameters.values()), (Ellipsis if sig.return_annotation is sig.empty else sig.return_annotation)) def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) if not hasattr(self, 'assertRaisesRegex'): self.assertRaisesRegex = self.assertRaisesRegexp if sys.version_info[0] > 2: exec(""" def test_signature_object(self): S = inspect.Signature P = inspect.Parameter self.assertEqual(str(S()), '()') def test(po, pk, *args, ko, **kwargs): pass sig = inspect.signature(test) po = sig.parameters['po'].replace(kind=P.POSITIONAL_ONLY) pk = sig.parameters['pk'] args = sig.parameters['args'] ko = sig.parameters['ko'] kwargs = sig.parameters['kwargs'] S((po, pk, args, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((pk, po, args, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((po, args, pk, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((args, po, pk, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((po, pk, args, kwargs, ko)) kwargs2 = kwargs.replace(name='args') with self.assertRaisesRegex(ValueError, 'duplicate parameter name'): S((po, pk, args, kwargs2, ko)) """) def test_signature_immutability(self): def test(a): pass sig = inspect.signature(test) with self.assertRaises(AttributeError): sig.foo = 'bar' # Python2 does not have MappingProxyType class if sys.version_info[:2] < (3, 3): return with self.assertRaises(TypeError): sig.parameters['a'] = None def test_signature_on_noarg(self): def test(): pass self.assertEqual(self.signature(test), ((), Ellipsis)) if sys.version_info[0] > 2: exec(""" def test_signature_on_wargs(self): def test(a, b:'foo') -> 123: pass self.assertEqual(self.signature(test), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('b', Ellipsis, 'foo', "positional_or_keyword")), 123)) """) if sys.version_info[0] > 2: exec(""" def test_signature_on_wkwonly(self): def test(*, a:float, b:str) -> int: pass self.assertEqual(self.signature(test), ((('a', Ellipsis, float, "keyword_only"), ('b', Ellipsis, str, "keyword_only")), int)) """) if sys.version_info[0] > 2: exec(""" def test_signature_on_complex_args(self): def test(a, b:'foo'=10, *args:'bar', spam:'baz', ham=123, **kwargs:int): pass self.assertEqual(self.signature(test), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('b', 10, 'foo', "positional_or_keyword"), ('args', Ellipsis, 'bar', "var_positional"), ('spam', Ellipsis, 'baz', "keyword_only"), ('ham', 123, Ellipsis, "keyword_only"), ('kwargs', Ellipsis, int, "var_keyword")), Ellipsis)) """) def test_signature_on_builtin_function(self): with self.assertRaisesRegex(ValueError, 'not supported by signature'): inspect.signature(type) with self.assertRaisesRegex(ValueError, 'not supported by signature'): # support for 'wrapper_descriptor' inspect.signature(type.__call__) if hasattr(sys, 'pypy_version_info'): raise ValueError('not supported by signature') with self.assertRaisesRegex(ValueError, 'not supported by signature'): # support for 'method-wrapper' inspect.signature(min.__call__) if hasattr(sys, 'pypy_version_info'): raise ValueError('not supported by signature') with self.assertRaisesRegex(ValueError, 'no signature found for builtin function'): # support for 'method-wrapper' inspect.signature(min) def test_signature_on_non_function(self): with self.assertRaisesRegex(TypeError, 'is not a callable object'): inspect.signature(42) with self.assertRaisesRegex(TypeError, 'is not a Python function'): inspect.Signature.from_function(42) if sys.version_info[0] > 2: exec(""" def test_signature_on_method(self): class Test: def foo(self, arg1, arg2=1) -> int: pass meth = Test().foo self.assertEqual(self.signature(meth), ((('arg1', Ellipsis, Ellipsis, "positional_or_keyword"), ('arg2', 1, Ellipsis, "positional_or_keyword")), int)) """) if sys.version_info[0] > 2: exec(""" def test_signature_on_classmethod(self): class Test: @classmethod def foo(cls, arg1, *, arg2=1): pass meth = Test().foo self.assertEqual(self.signature(meth), ((('arg1', Ellipsis, Ellipsis, "positional_or_keyword"), ('arg2', 1, Ellipsis, "keyword_only")), Ellipsis)) meth = Test.foo self.assertEqual(self.signature(meth), ((('arg1', Ellipsis, Ellipsis, "positional_or_keyword"), ('arg2', 1, Ellipsis, "keyword_only")), Ellipsis)) """) if sys.version_info[0] > 2: exec(""" def test_signature_on_staticmethod(self): class Test: @staticmethod def foo(cls, *, arg): pass meth = Test().foo self.assertEqual(self.signature(meth), ((('cls', Ellipsis, Ellipsis, "positional_or_keyword"), ('arg', Ellipsis, Ellipsis, "keyword_only")), Ellipsis)) meth = Test.foo self.assertEqual(self.signature(meth), ((('cls', Ellipsis, Ellipsis, "positional_or_keyword"), ('arg', Ellipsis, Ellipsis, "keyword_only")), Ellipsis)) """) if sys.version_info[0] > 2: exec(""" def test_signature_on_partial(self): from functools import partial def test(): pass self.assertEqual(self.signature(partial(test)), ((), Ellipsis)) with self.assertRaisesRegex(ValueError, "has incorrect arguments"): inspect.signature(partial(test, 1)) with self.assertRaisesRegex(ValueError, "has incorrect arguments"): inspect.signature(partial(test, a=1)) def test(a, b, *, c, d): pass self.assertEqual(self.signature(partial(test)), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('b', Ellipsis, Ellipsis, "positional_or_keyword"), ('c', Ellipsis, Ellipsis, "keyword_only"), ('d', Ellipsis, Ellipsis, "keyword_only")), Ellipsis)) self.assertEqual(self.signature(partial(test, 1)), ((('b', Ellipsis, Ellipsis, "positional_or_keyword"), ('c', Ellipsis, Ellipsis, "keyword_only"), ('d', Ellipsis, Ellipsis, "keyword_only")), Ellipsis)) self.assertEqual(self.signature(partial(test, 1, c=2)), ((('b', Ellipsis, Ellipsis, "positional_or_keyword"), ('c', 2, Ellipsis, "keyword_only"), ('d', Ellipsis, Ellipsis, "keyword_only")), Ellipsis)) self.assertEqual(self.signature(partial(test, b=1, c=2)), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('b', 1, Ellipsis, "positional_or_keyword"), ('c', 2, Ellipsis, "keyword_only"), ('d', Ellipsis, Ellipsis, "keyword_only")), Ellipsis)) self.assertEqual(self.signature(partial(test, 0, b=1, c=2)), ((('b', 1, Ellipsis, "positional_or_keyword"), ('c', 2, Ellipsis, "keyword_only"), ('d', Ellipsis, Ellipsis, "keyword_only"),), Ellipsis)) def test(a, *args, b, **kwargs): pass self.assertEqual(self.signature(partial(test, 1)), ((('args', Ellipsis, Ellipsis, "var_positional"), ('b', Ellipsis, Ellipsis, "keyword_only"), ('kwargs', Ellipsis, Ellipsis, "var_keyword")), Ellipsis)) self.assertEqual(self.signature(partial(test, 1, 2, 3)), ((('args', Ellipsis, Ellipsis, "var_positional"), ('b', Ellipsis, Ellipsis, "keyword_only"), ('kwargs', Ellipsis, Ellipsis, "var_keyword")), Ellipsis)) self.assertEqual(self.signature(partial(test, 1, 2, 3, test=True)), ((('args', Ellipsis, Ellipsis, "var_positional"), ('b', Ellipsis, Ellipsis, "keyword_only"), ('kwargs', Ellipsis, Ellipsis, "var_keyword")), Ellipsis)) self.assertEqual(self.signature(partial(test, 1, 2, 3, test=1, b=0)), ((('args', Ellipsis, Ellipsis, "var_positional"), ('b', 0, Ellipsis, "keyword_only"), ('kwargs', Ellipsis, Ellipsis, "var_keyword")), Ellipsis)) self.assertEqual(self.signature(partial(test, b=0)), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('args', Ellipsis, Ellipsis, "var_positional"), ('b', 0, Ellipsis, "keyword_only"), ('kwargs', Ellipsis, Ellipsis, "var_keyword")), Ellipsis)) self.assertEqual(self.signature(partial(test, b=0, test=1)), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('args', Ellipsis, Ellipsis, "var_positional"), ('b', 0, Ellipsis, "keyword_only"), ('kwargs', Ellipsis, Ellipsis, "var_keyword")), Ellipsis)) def test(a, b, c:int) -> 42: pass sig = test.__signature__ = inspect.signature(test) self.assertEqual(self.signature(partial(partial(test, 1))), ((('b', Ellipsis, Ellipsis, "positional_or_keyword"), ('c', Ellipsis, int, "positional_or_keyword")), 42)) self.assertEqual(self.signature(partial(partial(test, 1), 2)), ((('c', Ellipsis, int, "positional_or_keyword"),), 42)) psig = inspect.signature(partial(partial(test, 1), 2)) def foo(a): return a _foo = partial(partial(foo, a=10), a=20) self.assertEqual(self.signature(_foo), ((('a', 20, Ellipsis, "positional_or_keyword"),), Ellipsis)) # check that we don't have any side-effects in signature(), # and the partial object is still functioning self.assertEqual(_foo(), 20) def foo(a, b, c): return a, b, c _foo = partial(partial(foo, 1, b=20), b=30) self.assertEqual(self.signature(_foo), ((('b', 30, Ellipsis, "positional_or_keyword"), ('c', Ellipsis, Ellipsis, "positional_or_keyword")), Ellipsis)) self.assertEqual(_foo(c=10), (1, 30, 10)) _foo = partial(_foo, 2) # now 'b' has two values - # positional and keyword with self.assertRaisesRegex(ValueError, "has incorrect arguments"): inspect.signature(_foo) def foo(a, b, c, *, d): return a, b, c, d _foo = partial(partial(foo, d=20, c=20), b=10, d=30) self.assertEqual(self.signature(_foo), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('b', 10, Ellipsis, "positional_or_keyword"), ('c', 20, Ellipsis, "positional_or_keyword"), ('d', 30, Ellipsis, "keyword_only")), Ellipsis)) ba = inspect.signature(_foo).bind(a=200, b=11) self.assertEqual(_foo(*ba.args, **ba.kwargs), (200, 11, 20, 30)) def foo(a=1, b=2, c=3): return a, b, c _foo = partial(foo, a=10, c=13) ba = inspect.signature(_foo).bind(11) self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 2, 13)) ba = inspect.signature(_foo).bind(11, 12) self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13)) ba = inspect.signature(_foo).bind(11, b=12) self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13)) ba = inspect.signature(_foo).bind(b=12) self.assertEqual(_foo(*ba.args, **ba.kwargs), (10, 12, 13)) _foo = partial(_foo, b=10) ba = inspect.signature(_foo).bind(12, 14) self.assertEqual(_foo(*ba.args, **ba.kwargs), (12, 14, 13)) """) if sys.version_info[0] > 2: exec(""" def test_signature_on_decorated(self): import functools def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs) -> int: return func(*args, **kwargs) return wrapper class Foo: @decorator def bar(self, a, b): pass self.assertEqual(self.signature(Foo.bar), ((('self', Ellipsis, Ellipsis, "positional_or_keyword"), ('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('b', Ellipsis, Ellipsis, "positional_or_keyword")), Ellipsis)) self.assertEqual(self.signature(Foo().bar), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('b', Ellipsis, Ellipsis, "positional_or_keyword")), Ellipsis)) # Test that we handle method wrappers correctly def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs) -> int: return func(42, *args, **kwargs) sig = inspect.signature(func) new_params = tuple(sig.parameters.values())[1:] wrapper.__signature__ = sig.replace(parameters=new_params) return wrapper class Foo: @decorator def __call__(self, a, b): pass self.assertEqual(self.signature(Foo.__call__), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"), ('b', Ellipsis, Ellipsis, "positional_or_keyword")), Ellipsis)) self.assertEqual(self.signature(Foo().__call__), ((('b', Ellipsis, Ellipsis, "positional_or_keyword"),), Ellipsis)) """) if sys.version_info[0] > 2: exec(""" def test_signature_on_class(self): class C: def __init__(self, a): pass self.assertEqual(self.signature(C), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"),), Ellipsis)) class CM(type): def __call__(cls, a): pass class C(metaclass=CM): def __init__(self, b): pass self.assertEqual(self.signature(C), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"),), Ellipsis)) class CM(type): def __new__(mcls, name, bases, dct, *, foo=1): return super().__new__(mcls, name, bases, dct) class C(metaclass=CM): def __init__(self, b): pass self.assertEqual(self.signature(C), ((('b', Ellipsis, Ellipsis, "positional_or_keyword"),), Ellipsis)) self.assertEqual(self.signature(CM), ((('name', Ellipsis, Ellipsis, "positional_or_keyword"), ('bases', Ellipsis, Ellipsis, "positional_or_keyword"), ('dct', Ellipsis, Ellipsis, "positional_or_keyword"), ('foo', 1, Ellipsis, "keyword_only")), Ellipsis)) class CMM(type): def __new__(mcls, name, bases, dct, *, foo=1): return super().__new__(mcls, name, bases, dct) def __call__(cls, nm, bs, dt): return type(nm, bs, dt) class CM(type, metaclass=CMM): def __new__(mcls, name, bases, dct, *, bar=2): return super().__new__(mcls, name, bases, dct) class C(metaclass=CM): def __init__(self, b): pass self.assertEqual(self.signature(CMM), ((('name', Ellipsis, Ellipsis, "positional_or_keyword"), ('bases', Ellipsis, Ellipsis, "positional_or_keyword"), ('dct', Ellipsis, Ellipsis, "positional_or_keyword"), ('foo', 1, Ellipsis, "keyword_only")), Ellipsis)) self.assertEqual(self.signature(CM), ((('nm', Ellipsis, Ellipsis, "positional_or_keyword"), ('bs', Ellipsis, Ellipsis, "positional_or_keyword"), ('dt', Ellipsis, Ellipsis, "positional_or_keyword")), Ellipsis)) self.assertEqual(self.signature(C), ((('b', Ellipsis, Ellipsis, "positional_or_keyword"),), Ellipsis)) class CM(type): def __init__(cls, name, bases, dct, *, bar=2): return super().__init__(name, bases, dct) class C(metaclass=CM): def __init__(self, b): pass self.assertEqual(self.signature(CM), ((('name', Ellipsis, Ellipsis, "positional_or_keyword"), ('bases', Ellipsis, Ellipsis, "positional_or_keyword"), ('dct', Ellipsis, Ellipsis, "positional_or_keyword"), ('bar', 2, Ellipsis, "keyword_only")), Ellipsis)) """) def test_signature_on_callable_objects(self): class Foo(object): def __call__(self, a): pass self.assertEqual(self.signature(Foo()), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"),), Ellipsis)) class Spam(object): pass with self.assertRaisesRegex(TypeError, "is not a callable object"): inspect.signature(Spam()) class Bar(Spam, Foo): pass self.assertEqual(self.signature(Bar()), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"),), Ellipsis)) class ToFail(object): __call__ = type with self.assertRaisesRegex(ValueError, "not supported by signature"): inspect.signature(ToFail()) if sys.version_info[0] < 3: return class Wrapped(object): pass Wrapped.__wrapped__ = lambda a: None self.assertEqual(self.signature(Wrapped), ((('a', Ellipsis, Ellipsis, "positional_or_keyword"),), Ellipsis)) def test_signature_on_lambdas(self): self.assertEqual(self.signature((lambda a=10: a)), ((('a', 10, Ellipsis, "positional_or_keyword"),), Ellipsis)) if sys.version_info[0] > 2: exec(""" def test_signature_equality(self): def foo(a, *, b:int) -> float: pass self.assertNotEqual(inspect.signature(foo), 42) def bar(a, *, b:int) -> float: pass self.assertEqual(inspect.signature(foo), inspect.signature(bar)) def bar(a, *, b:int) -> int: pass self.assertNotEqual(inspect.signature(foo), inspect.signature(bar)) def bar(a, *, b:int): pass self.assertNotEqual(inspect.signature(foo), inspect.signature(bar)) def bar(a, *, b:int=42) -> float: pass self.assertNotEqual(inspect.signature(foo), inspect.signature(bar)) def bar(a, *, c) -> float: pass self.assertNotEqual(inspect.signature(foo), inspect.signature(bar)) def bar(a, b:int) -> float: pass self.assertNotEqual(inspect.signature(foo), inspect.signature(bar)) def spam(b:int, a) -> float: pass self.assertNotEqual(inspect.signature(spam), inspect.signature(bar)) def foo(*, a, b, c): pass def bar(*, c, b, a): pass self.assertEqual(inspect.signature(foo), inspect.signature(bar)) def foo(*, a=1, b, c): pass def bar(*, c, b, a=1): pass self.assertEqual(inspect.signature(foo), inspect.signature(bar)) def foo(pos, *, a=1, b, c): pass def bar(pos, *, c, b, a=1): pass self.assertEqual(inspect.signature(foo), inspect.signature(bar)) def foo(pos, *, a, b, c): pass def bar(pos, *, c, b, a=1): pass self.assertNotEqual(inspect.signature(foo), inspect.signature(bar)) def foo(pos, *args, a=42, b, c, **kwargs:int): pass def bar(pos, *args, c, b, a=42, **kwargs:int): pass self.assertEqual(inspect.signature(foo), inspect.signature(bar)) """) def test_signature_unhashable(self): def foo(a): pass sig = inspect.signature(foo) with self.assertRaisesRegex(TypeError, 'unhashable type'): hash(sig) if sys.version_info[0] > 2: exec(""" def test_signature_str(self): def foo(a:int=1, *, b, c=None, **kwargs) -> 42: pass self.assertEqual(str(inspect.signature(foo)), '(a:int=1, *, b, c=None, **kwargs) -> 42') def foo(a:int=1, *args, b, c=None, **kwargs) -> 42: pass self.assertEqual(str(inspect.signature(foo)), '(a:int=1, *args, b, c=None, **kwargs) -> 42') def foo(): pass self.assertEqual(str(inspect.signature(foo)), '()') """) if sys.version_info[0] > 2: exec(""" def test_signature_str_positional_only(self): P = inspect.Parameter def test(a_po, *, b, **kwargs): return a_po, kwargs sig = inspect.signature(test) new_params = list(sig.parameters.values()) new_params[0] = new_params[0].replace(kind=P.POSITIONAL_ONLY) test.__signature__ = sig.replace(parameters=new_params) self.assertEqual(str(inspect.signature(test)), '(<a_po>, *, b, **kwargs)') sig = inspect.signature(test) new_params = list(sig.parameters.values()) new_params[0] = new_params[0].replace(name=None) test.__signature__ = sig.replace(parameters=new_params) self.assertEqual(str(inspect.signature(test)), '(<0>, *, b, **kwargs)') """) if sys.version_info[0] > 2: exec(""" def test_signature_replace_anno(self): def test() -> 42: pass sig = inspect.signature(test) sig = sig.replace(return_annotation=None) self.assertIs(sig.return_annotation, None) sig = sig.replace(return_annotation=sig.empty) self.assertIs(sig.return_annotation, sig.empty) sig = sig.replace(return_annotation=42) self.assertEqual(sig.return_annotation, 42) self.assertEqual(sig, inspect.signature(test)) """) class TestParameterObject(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) if not hasattr(self, 'assertRaisesRegex'): self.assertRaisesRegex = self.assertRaisesRegexp def test_signature_parameter_kinds(self): P = inspect.Parameter self.assertTrue(P.POSITIONAL_ONLY < P.POSITIONAL_OR_KEYWORD < \ P.VAR_POSITIONAL < P.KEYWORD_ONLY < P.VAR_KEYWORD) self.assertEqual(str(P.POSITIONAL_ONLY), 'POSITIONAL_ONLY') self.assertTrue('POSITIONAL_ONLY' in repr(P.POSITIONAL_ONLY)) def test_signature_parameter_object(self): p = inspect.Parameter('foo', default=10, kind=inspect.Parameter.POSITIONAL_ONLY) self.assertEqual(p.name, 'foo') self.assertEqual(p.default, 10) self.assertIs(p.annotation, p.empty) self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY) with self.assertRaisesRegex(ValueError, 'invalid value'): inspect.Parameter('foo', default=10, kind='123') with self.assertRaisesRegex(ValueError, 'not a valid parameter name'): inspect.Parameter('1', kind=inspect.Parameter.VAR_KEYWORD) with self.assertRaisesRegex(ValueError, 'non-positional-only parameter'): inspect.Parameter(None, kind=inspect.Parameter.VAR_KEYWORD) with self.assertRaisesRegex(ValueError, 'cannot have default values'): inspect.Parameter('a', default=42, kind=inspect.Parameter.VAR_KEYWORD) with self.assertRaisesRegex(ValueError, 'cannot have default values'): inspect.Parameter('a', default=42, kind=inspect.Parameter.VAR_POSITIONAL) p = inspect.Parameter('a', default=42, kind=inspect.Parameter.POSITIONAL_OR_KEYWORD) with self.assertRaisesRegex(ValueError, 'cannot have default values'): p.replace(kind=inspect.Parameter.VAR_POSITIONAL) self.assertTrue(repr(p).startswith('<Parameter')) def test_signature_parameter_equality(self): P = inspect.Parameter p = P('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY) self.assertEqual(p, p) self.assertNotEqual(p, 42) self.assertEqual(p, P('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY)) def test_signature_parameter_unhashable(self): p = inspect.Parameter('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY) with self.assertRaisesRegex(TypeError, 'unhashable type'): hash(p) def test_signature_parameter_replace(self): p = inspect.Parameter('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY) self.assertIsNot(p, p.replace()) self.assertEqual(p, p.replace()) p2 = p.replace(annotation=1) self.assertEqual(p2.annotation, 1) p2 = p2.replace(annotation=p2.empty) self.assertEqual(p, p2) p2 = p2.replace(name='bar') self.assertEqual(p2.name, 'bar') self.assertNotEqual(p2, p) with self.assertRaisesRegex(ValueError, 'not a valid parameter name'): p2 = p2.replace(name=p2.empty) p2 = p2.replace(name='foo', default=None) self.assertIs(p2.default, None) self.assertNotEqual(p2, p) p2 = p2.replace(name='foo', default=p2.empty) self.assertIs(p2.default, p2.empty) p2 = p2.replace(default=42, kind=p2.POSITIONAL_OR_KEYWORD) self.assertEqual(p2.kind, p2.POSITIONAL_OR_KEYWORD) self.assertNotEqual(p2, p) with self.assertRaisesRegex(ValueError, 'invalid value for'): p2 = p2.replace(kind=p2.empty) p2 = p2.replace(kind=p2.KEYWORD_ONLY) self.assertEqual(p2, p) def test_signature_parameter_positional_only(self): p = inspect.Parameter(None, kind=inspect.Parameter.POSITIONAL_ONLY) self.assertEqual(str(p), '<>') p = p.replace(name='1') self.assertEqual(str(p), '<1>') def test_signature_parameter_immutability(self): p = inspect.Parameter(None, kind=inspect.Parameter.POSITIONAL_ONLY) with self.assertRaises(AttributeError): p.foo = 'bar' with self.assertRaises(AttributeError): p.kind = 123 class TestSignatureBind(unittest.TestCase): @staticmethod def call(func, *args, **kwargs): sig = inspect.signature(func) ba = sig.bind(*args, **kwargs) return func(*ba.args, **ba.kwargs) def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) if not hasattr(self, 'assertRaisesRegex'): self.assertRaisesRegex = self.assertRaisesRegexp def test_signature_bind_empty(self): def test(): return 42 self.assertEqual(self.call(test), 42) with self.assertRaisesRegex(TypeError, 'too many positional arguments'): self.call(test, 1) with self.assertRaisesRegex(TypeError, 'too many positional arguments'): self.call(test, 1, spam=10) with self.assertRaisesRegex(TypeError, 'too many keyword arguments'): self.call(test, spam=1) def test_signature_bind_var(self): def test(*args, **kwargs): return args, kwargs self.assertEqual(self.call(test), ((), {})) self.assertEqual(self.call(test, 1), ((1,), {})) self.assertEqual(self.call(test, 1, 2), ((1, 2), {})) self.assertEqual(self.call(test, foo='bar'), ((), {'foo': 'bar'})) self.assertEqual(self.call(test, 1, foo='bar'), ((1,), {'foo': 'bar'})) self.assertEqual(self.call(test, args=10), ((), {'args': 10})) self.assertEqual(self.call(test, 1, 2, foo='bar'), ((1, 2), {'foo': 'bar'})) def test_signature_bind_just_args(self): def test(a, b, c): return a, b, c self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) with self.assertRaisesRegex(TypeError, 'too many positional arguments'): self.call(test, 1, 2, 3, 4) with self.assertRaisesRegex(TypeError, "'b' parameter lacking default"): self.call(test, 1) with self.assertRaisesRegex(TypeError, "'a' parameter lacking default"): self.call(test) def test(a, b, c=10): return a, b, c self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) self.assertEqual(self.call(test, 1, 2), (1, 2, 10)) def test(a=1, b=2, c=3): return a, b, c self.assertEqual(self.call(test, a=10, c=13), (10, 2, 13)) self.assertEqual(self.call(test, a=10), (10, 2, 3)) self.assertEqual(self.call(test, b=10), (1, 10, 3)) def test_signature_bind_varargs_order(self): def test(*args): return args self.assertEqual(self.call(test), ()) self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3)) def test_signature_bind_args_and_varargs(self): def test(a, b, c=3, *args): return a, b, c, args self.assertEqual(self.call(test, 1, 2, 3, 4, 5), (1, 2, 3, (4, 5))) self.assertEqual(self.call(test, 1, 2), (1, 2, 3, ())) self.assertEqual(self.call(test, b=1, a=2), (2, 1, 3, ())) self.assertEqual(self.call(test, 1, b=2), (1, 2, 3, ())) with self.assertRaisesRegex(TypeError, "multiple values for argument 'c'"): self.call(test, 1, 2, 3, c=4) def test_signature_bind_just_kwargs(self): def test(**kwargs): return kwargs self.assertEqual(self.call(test), {}) self.assertEqual(self.call(test, foo='bar', spam='ham'), {'foo': 'bar', 'spam': 'ham'}) def test_signature_bind_args_and_kwargs(self): def test(a, b, c=3, **kwargs): return a, b, c, kwargs self.assertEqual(self.call(test, 1, 2), (1, 2, 3, {})) self.assertEqual(self.call(test, 1, 2, foo='bar', spam='ham'), (1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) self.assertEqual(self.call(test, b=2, a=1, foo='bar', spam='ham'), (1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) self.assertEqual(self.call(test, a=1, b=2, foo='bar', spam='ham'), (1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) self.assertEqual(self.call(test, 1, b=2, foo='bar', spam='ham'), (1, 2, 3, {'foo': 'bar', 'spam': 'ham'})) self.assertEqual(self.call(test, 1, b=2, c=4, foo='bar', spam='ham'), (1, 2, 4, {'foo': 'bar', 'spam': 'ham'})) self.assertEqual(self.call(test, 1, 2, 4, foo='bar'), (1, 2, 4, {'foo': 'bar'})) self.assertEqual(self.call(test, c=5, a=4, b=3), (4, 3, 5, {})) if sys.version_info[0] > 2: exec(""" def test_signature_bind_kwonly(self): def test(*, foo): return foo with self.assertRaisesRegex(TypeError, 'too many positional arguments'): self.call(test, 1) self.assertEqual(self.call(test, foo=1), 1) def test(a, *, foo=1, bar): return foo with self.assertRaisesRegex(TypeError, "'bar' parameter lacking default value"): self.call(test, 1) def test(foo, *, bar): return foo, bar self.assertEqual(self.call(test, 1, bar=2), (1, 2)) self.assertEqual(self.call(test, bar=2, foo=1), (1, 2)) with self.assertRaisesRegex(TypeError, 'too many keyword arguments'): self.call(test, bar=2, foo=1, spam=10) with self.assertRaisesRegex(TypeError, 'too many positional arguments'): self.call(test, 1, 2) with self.assertRaisesRegex(TypeError, 'too many positional arguments'): self.call(test, 1, 2, bar=2) with self.assertRaisesRegex(TypeError, 'too many keyword arguments'): self.call(test, 1, bar=2, spam='ham') with self.assertRaisesRegex(TypeError, "'bar' parameter lacking default value"): self.call(test, 1) def test(foo, *, bar, **bin): return foo, bar, bin self.assertEqual(self.call(test, 1, bar=2), (1, 2, {})) self.assertEqual(self.call(test, foo=1, bar=2), (1, 2, {})) self.assertEqual(self.call(test, 1, bar=2, spam='ham'), (1, 2, {'spam': 'ham'})) self.assertEqual(self.call(test, spam='ham', foo=1, bar=2), (1, 2, {'spam': 'ham'})) with self.assertRaisesRegex(TypeError, "'foo' parameter lacking default value"): self.call(test, spam='ham', bar=2) self.assertEqual(self.call(test, 1, bar=2, bin=1, spam=10), (1, 2, {'bin': 1, 'spam': 10})) """) # if sys.version_info[0] > 2: exec(""" def test_signature_bind_arguments(self): def test(a, *args, b, z=100, **kwargs): pass sig = inspect.signature(test) ba = sig.bind(10, 20, b=30, c=40, args=50, kwargs=60) # we won't have 'z' argument in the bound arguments object, as we didn't # pass it to the 'bind' self.assertEqual(tuple(ba.arguments.items()), (('a', 10), ('args', (20,)), ('b', 30), ('kwargs', {'c': 40, 'args': 50, 'kwargs': 60}))) self.assertEqual(ba.kwargs, {'b': 30, 'c': 40, 'args': 50, 'kwargs': 60}) self.assertEqual(ba.args, (10, 20)) """) # if sys.version_info[0] > 2: exec(""" def test_signature_bind_positional_only(self): P = inspect.Parameter def test(a_po, b_po, c_po=3, foo=42, *, bar=50, **kwargs): return a_po, b_po, c_po, foo, bar, kwargs sig = inspect.signature(test) new_params = collections.OrderedDict(tuple(sig.parameters.items())) for name in ('a_po', 'b_po', 'c_po'): new_params[name] = new_params[name].replace(kind=P.POSITIONAL_ONLY) new_sig = sig.replace(parameters=new_params.values()) test.__signature__ = new_sig self.assertEqual(self.call(test, 1, 2, 4, 5, bar=6), (1, 2, 4, 5, 6, {})) with self.assertRaisesRegex(TypeError, "parameter is positional only"): self.call(test, 1, 2, c_po=4) with self.assertRaisesRegex(TypeError, "parameter is positional only"): self.call(test, a_po=1, b_po=2) """) class TestBoundArguments(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) if not hasattr(self, 'assertRaisesRegex'): self.assertRaisesRegex = self.assertRaisesRegexp def test_signature_bound_arguments_unhashable(self): def foo(a): pass ba = inspect.signature(foo).bind(1) with self.assertRaisesRegex(TypeError, 'unhashable type'): hash(ba) def test_signature_bound_arguments_equality(self): def foo(a): pass ba = inspect.signature(foo).bind(1) self.assertEqual(ba, ba) ba2 = inspect.signature(foo).bind(1) self.assertEqual(ba, ba2) ba3 = inspect.signature(foo).bind(2) self.assertNotEqual(ba, ba3) ba3.arguments['a'] = 1 self.assertEqual(ba, ba3) def bar(b): pass ba4 = inspect.signature(bar).bind(1) self.assertNotEqual(ba, ba4) if __name__ == "__main__": unittest.begin()
mpl-2.0
KaranToor/MA450
google-cloud-sdk/.install/.backup/lib/googlecloudsdk/third_party/apis/cloudbilling/v1/cloudbilling_v1_messages.py
6
9240
"""Generated message classes for cloudbilling version v1. Allows developers to manage billing for their Google Cloud Platform projects programmatically. """ # NOTE: This file is autogenerated and should not be edited by hand. from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding package = 'cloudbilling' class BillingAccount(_messages.Message): """A billing account in [Google Cloud Console](https://console.cloud.google.com/). You can assign a billing account to one or more projects. Fields: displayName: The display name given to the billing account, such as `My Billing Account`. This name is displayed in the Google Cloud Console. name: The resource name of the billing account. The resource name has the form `billingAccounts/{billing_account_id}`. For example, `billingAccounts/012345-567890-ABCDEF` would be the resource name for billing account `012345-567890-ABCDEF`. open: True if the billing account is open, and will therefore be charged for any usage on associated projects. False if the billing account is closed, and therefore projects associated with it will be unable to use paid services. """ displayName = _messages.StringField(1) name = _messages.StringField(2) open = _messages.BooleanField(3) class CloudbillingBillingAccountsGetRequest(_messages.Message): """A CloudbillingBillingAccountsGetRequest object. Fields: name: The resource name of the billing account to retrieve. For example, `billingAccounts/012345-567890-ABCDEF`. """ name = _messages.StringField(1, required=True) class CloudbillingBillingAccountsListRequest(_messages.Message): """A CloudbillingBillingAccountsListRequest object. Fields: pageSize: Requested page size. The maximum page size is 100; this is also the default. pageToken: A token identifying a page of results to return. This should be a `next_page_token` value returned from a previous `ListBillingAccounts` call. If unspecified, the first page of results is returned. """ pageSize = _messages.IntegerField(1, variant=_messages.Variant.INT32) pageToken = _messages.StringField(2) class CloudbillingBillingAccountsProjectsListRequest(_messages.Message): """A CloudbillingBillingAccountsProjectsListRequest object. Fields: name: The resource name of the billing account associated with the projects that you want to list. For example, `billingAccounts/012345-567890-ABCDEF`. pageSize: Requested page size. The maximum page size is 100; this is also the default. pageToken: A token identifying a page of results to be returned. This should be a `next_page_token` value returned from a previous `ListProjectBillingInfo` call. If unspecified, the first page of results is returned. """ name = _messages.StringField(1, required=True) pageSize = _messages.IntegerField(2, variant=_messages.Variant.INT32) pageToken = _messages.StringField(3) class CloudbillingProjectsGetBillingInfoRequest(_messages.Message): """A CloudbillingProjectsGetBillingInfoRequest object. Fields: name: The resource name of the project for which billing information is retrieved. For example, `projects/tokyo-rain-123`. """ name = _messages.StringField(1, required=True) class CloudbillingProjectsUpdateBillingInfoRequest(_messages.Message): """A CloudbillingProjectsUpdateBillingInfoRequest object. Fields: name: The resource name of the project associated with the billing information that you want to update. For example, `projects/tokyo- rain-123`. projectBillingInfo: A ProjectBillingInfo resource to be passed as the request body. """ name = _messages.StringField(1, required=True) projectBillingInfo = _messages.MessageField('ProjectBillingInfo', 2) class ListBillingAccountsResponse(_messages.Message): """Response message for `ListBillingAccounts`. Fields: billingAccounts: A list of billing accounts. nextPageToken: A token to retrieve the next page of results. To retrieve the next page, call `ListBillingAccounts` again with the `page_token` field set to this value. This field is empty if there are no more results to retrieve. """ billingAccounts = _messages.MessageField('BillingAccount', 1, repeated=True) nextPageToken = _messages.StringField(2) class ListProjectBillingInfoResponse(_messages.Message): """Request message for `ListProjectBillingInfoResponse`. Fields: nextPageToken: A token to retrieve the next page of results. To retrieve the next page, call `ListProjectBillingInfo` again with the `page_token` field set to this value. This field is empty if there are no more results to retrieve. projectBillingInfo: A list of `ProjectBillingInfo` resources representing the projects associated with the billing account. """ nextPageToken = _messages.StringField(1) projectBillingInfo = _messages.MessageField('ProjectBillingInfo', 2, repeated=True) class ProjectBillingInfo(_messages.Message): """Encapsulation of billing information for a Cloud Console project. A project has at most one associated billing account at a time (but a billing account can be assigned to multiple projects). Fields: billingAccountName: The resource name of the billing account associated with the project, if any. For example, `billingAccounts/012345-567890-ABCDEF`. billingEnabled: True if the project is associated with an open billing account, to which usage on the project is charged. False if the project is associated with a closed billing account, or no billing account at all, and therefore cannot use paid services. This field is read-only. name: The resource name for the `ProjectBillingInfo`; has the form `projects/{project_id}/billingInfo`. For example, the resource name for the billing information for project `tokyo-rain-123` would be `projects /tokyo-rain-123/billingInfo`. This field is read-only. projectId: The ID of the project that this `ProjectBillingInfo` represents, such as `tokyo-rain-123`. This is a convenience field so that you don't need to parse the `name` field to obtain a project ID. This field is read-only. """ billingAccountName = _messages.StringField(1) billingEnabled = _messages.BooleanField(2) name = _messages.StringField(3) projectId = _messages.StringField(4) class StandardQueryParameters(_messages.Message): """Query parameters accepted by all methods. Enums: FXgafvValueValuesEnum: V1 error format. AltValueValuesEnum: Data format for response. Fields: f__xgafv: V1 error format. access_token: OAuth access token. alt: Data format for response. bearer_token: OAuth bearer token. callback: JSONP fields: Selector specifying which fields to include in a partial response. key: API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. oauth_token: OAuth 2.0 token for the current user. pp: Pretty-print response. prettyPrint: Returns response with indentations and line breaks. quotaUser: Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. trace: A tracing token of the form "token:<tokenid>" to include in api requests. uploadType: Legacy upload protocol for media (e.g. "media", "multipart"). upload_protocol: Upload protocol for media (e.g. "raw", "multipart"). """ class AltValueValuesEnum(_messages.Enum): """Data format for response. Values: json: Responses with Content-Type of application/json media: Media download with context-dependent Content-Type proto: Responses with Content-Type of application/x-protobuf """ json = 0 media = 1 proto = 2 class FXgafvValueValuesEnum(_messages.Enum): """V1 error format. Values: _1: v1 error format _2: v2 error format """ _1 = 0 _2 = 1 f__xgafv = _messages.EnumField('FXgafvValueValuesEnum', 1) access_token = _messages.StringField(2) alt = _messages.EnumField('AltValueValuesEnum', 3, default=u'json') bearer_token = _messages.StringField(4) callback = _messages.StringField(5) fields = _messages.StringField(6) key = _messages.StringField(7) oauth_token = _messages.StringField(8) pp = _messages.BooleanField(9, default=True) prettyPrint = _messages.BooleanField(10, default=True) quotaUser = _messages.StringField(11) trace = _messages.StringField(12) uploadType = _messages.StringField(13) upload_protocol = _messages.StringField(14) encoding.AddCustomJsonFieldMapping( StandardQueryParameters, 'f__xgafv', '$.xgafv', package=u'cloudbilling') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_1', '1', package=u'cloudbilling') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_2', '2', package=u'cloudbilling')
apache-2.0
thomas-maurice/docker-minecraft-webapp
webapp/lib/mcrcon.py
1
1703
import socket import select import struct class MCRconException(Exception): pass class MCRcon: socket = None def connect(self, host, port): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((host, port)) def disconnect(self): self.socket.close() self.socket = None def send(self, out_type, out_data): if self.socket is None: raise MCRconException("Must connect before sending data") # Send a request packet out_payload = struct.pack('<ii', 0, out_type) + out_data.encode('utf8') + b'\x00\x00' out_length = struct.pack('<i', len(out_payload)) self.socket.send(out_length + out_payload) # Read response packets in_data = "" while True: # Read a packet in_length, = struct.unpack('<i', self.socket.recv(4)) in_payload = self.socket.recv(in_length) in_id, in_type = struct.unpack('<ii', in_payload[:8]) in_data_partial, in_padding = in_payload[8:-2], in_payload[-2:] # Sanity checks if in_padding != b'\x00\x00': raise MCRconException("Incorrect padding") if in_id == -1: raise MCRconException("Login failed") # Record the response in_data += in_data_partial.decode('utf8') # If there's nothing more to receive, return the response if len(select.select([self.socket], [], [], 0)[0]) == 0: return in_data def command(self, command): return self.send(2, command) def login(self, password): return self.send(3, password)
gpl-3.0
neuropycon/ephypype
ephypype/externals/click/core.py
20
75305
import errno import inspect import os import sys from contextlib import contextmanager from itertools import repeat from functools import update_wrapper from .types import convert_type, IntRange, BOOL from .utils import PacifyFlushWrapper, make_str, make_default_short_help, \ echo, get_os_args from .exceptions import ClickException, UsageError, BadParameter, Abort, \ MissingParameter, Exit from .termui import prompt, confirm, style from .formatting import HelpFormatter, join_options from .parser import OptionParser, split_opt from .globals import push_context, pop_context from ._compat import PY2, isidentifier, iteritems, string_types from ._unicodefun import _check_for_unicode_literals, _verify_python3_env _missing = object() SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...' SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...' DEPRECATED_HELP_NOTICE = ' (DEPRECATED)' DEPRECATED_INVOKE_NOTICE = 'DeprecationWarning: ' + \ 'The command %(name)s is deprecated.' def _maybe_show_deprecated_notice(cmd): if cmd.deprecated: echo(style(DEPRECATED_INVOKE_NOTICE % {'name': cmd.name}, fg='red'), err=True) def fast_exit(code): """Exit without garbage collection, this speeds up exit by about 10ms for things like bash completion. """ sys.stdout.flush() sys.stderr.flush() os._exit(code) def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var) if not complete_instr: return from ._bashcomplete import bashcomplete if bashcomplete(cmd, prog_name, complete_var, complete_instr): fast_exit(1) def _check_multicommand(base_command, cmd_name, cmd, register=False): if not base_command.chain or not isinstance(cmd, MultiCommand): return if register: hint = 'It is not possible to add multi commands as children to ' \ 'another multi command that is in chain mode' else: hint = 'Found a multi command as subcommand to a multi command ' \ 'that is in chain mode. This is not supported' raise RuntimeError('%s. Command "%s" is set to chain and "%s" was ' 'added as subcommand but it in itself is a ' 'multi command. ("%s" is a %s within a chained ' '%s named "%s").' % ( hint, base_command.name, cmd_name, cmd_name, cmd.__class__.__name__, base_command.__class__.__name__, base_command.name)) def batch(iterable, batch_size): return list(zip(*repeat(iter(iterable), batch_size))) def invoke_param_callback(callback, ctx, param, value): code = getattr(callback, '__code__', None) args = getattr(code, 'co_argcount', 3) if args < 3: # This will become a warning in Click 3.0: from warnings import warn warn(Warning('Invoked legacy parameter callback "%s". The new ' 'signature for such callbacks starting with ' 'click 2.0 is (ctx, param, value).' % callback), stacklevel=3) return callback(ctx, value) return callback(ctx, param, value) @contextmanager def augment_usage_errors(ctx, param=None): """Context manager that attaches extra information to exceptions that fly. """ try: yield except BadParameter as e: if e.ctx is None: e.ctx = ctx if param is not None and e.param is None: e.param = param raise except UsageError as e: if e.ctx is None: e.ctx = ctx raise def iter_params_for_processing(invocation_order, declaration_order): """Given a sequence of parameters in the order as should be considered for processing and an iterable of parameters that exist, this returns a list in the correct order as they should be processed. """ def sort_key(item): try: idx = invocation_order.index(item) except ValueError: idx = float('inf') return (not item.is_eager, idx) return sorted(declaration_order, key=sort_key) class Context(object): """The context is a special internal object that holds state relevant for the script execution at every single level. It's normally invisible to commands unless they opt-in to getting access to it. The context is useful as it can pass internal objects around and can control special execution features such as reading data from environment variables. A context can be used as context manager in which case it will call :meth:`close` on teardown. .. versionadded:: 2.0 Added the `resilient_parsing`, `help_option_names`, `token_normalize_func` parameters. .. versionadded:: 3.0 Added the `allow_extra_args` and `allow_interspersed_args` parameters. .. versionadded:: 4.0 Added the `color`, `ignore_unknown_options`, and `max_content_width` parameters. :param command: the command class for this context. :param parent: the parent context. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it is usually the name of the script, for commands below it it's the name of the script. :param obj: an arbitrary object of user data. :param auto_envvar_prefix: the prefix to use for automatic environment variables. If this is `None` then reading from environment variables is disabled. This does not affect manually set environment variables which are always read. :param default_map: a dictionary (like object) with default values for parameters. :param terminal_width: the width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied. :param max_content_width: the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right. :param resilient_parsing: if this flag is enabled then Click will parse without any interactivity or callback invocation. Default values will also be ignored. This is useful for implementing things such as completion support. :param allow_extra_args: if this is set to `True` then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command. :param allow_interspersed_args: if this is set to `False` then options and arguments cannot be mixed. The default is to inherit from the command. :param ignore_unknown_options: instructs click to ignore options it does not know and keeps them for later processing. :param help_option_names: optionally a list of strings that define how the default help parameter is named. The default is ``['--help']``. :param token_normalize_func: an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output. """ def __init__(self, command, parent=None, info_name=None, obj=None, auto_envvar_prefix=None, default_map=None, terminal_width=None, max_content_width=None, resilient_parsing=False, allow_extra_args=None, allow_interspersed_args=None, ignore_unknown_options=None, help_option_names=None, token_normalize_func=None, color=None): #: the parent context or `None` if none exists. self.parent = parent #: the :class:`Command` for this context. self.command = command #: the descriptive information name self.info_name = info_name #: the parsed parameters except if the value is hidden in which #: case it's not remembered. self.params = {} #: the leftover arguments. self.args = [] #: protected arguments. These are arguments that are prepended #: to `args` when certain parsing scenarios are encountered but #: must be never propagated to another arguments. This is used #: to implement nested parsing. self.protected_args = [] if obj is None and parent is not None: obj = parent.obj #: the user object stored. self.obj = obj self._meta = getattr(parent, 'meta', {}) #: A dictionary (-like object) with defaults for parameters. if default_map is None \ and parent is not None \ and parent.default_map is not None: default_map = parent.default_map.get(info_name) self.default_map = default_map #: This flag indicates if a subcommand is going to be executed. A #: group callback can use this information to figure out if it's #: being executed directly or because the execution flow passes #: onwards to a subcommand. By default it's None, but it can be #: the name of the subcommand to execute. #: #: If chaining is enabled this will be set to ``'*'`` in case #: any commands are executed. It is however not possible to #: figure out which ones. If you require this knowledge you #: should use a :func:`resultcallback`. self.invoked_subcommand = None if terminal_width is None and parent is not None: terminal_width = parent.terminal_width #: The width of the terminal (None is autodetection). self.terminal_width = terminal_width if max_content_width is None and parent is not None: max_content_width = parent.max_content_width #: The maximum width of formatted content (None implies a sensible #: default which is 80 for most things). self.max_content_width = max_content_width if allow_extra_args is None: allow_extra_args = command.allow_extra_args #: Indicates if the context allows extra args or if it should #: fail on parsing. #: #: .. versionadded:: 3.0 self.allow_extra_args = allow_extra_args if allow_interspersed_args is None: allow_interspersed_args = command.allow_interspersed_args #: Indicates if the context allows mixing of arguments and #: options or not. #: #: .. versionadded:: 3.0 self.allow_interspersed_args = allow_interspersed_args if ignore_unknown_options is None: ignore_unknown_options = command.ignore_unknown_options #: Instructs click to ignore options that a command does not #: understand and will store it on the context for later #: processing. This is primarily useful for situations where you #: want to call into external programs. Generally this pattern is #: strongly discouraged because it's not possibly to losslessly #: forward all arguments. #: #: .. versionadded:: 4.0 self.ignore_unknown_options = ignore_unknown_options if help_option_names is None: if parent is not None: help_option_names = parent.help_option_names else: help_option_names = ['--help'] #: The names for the help options. self.help_option_names = help_option_names if token_normalize_func is None and parent is not None: token_normalize_func = parent.token_normalize_func #: An optional normalization function for tokens. This is #: options, choices, commands etc. self.token_normalize_func = token_normalize_func #: Indicates if resilient parsing is enabled. In that case Click #: will do its best to not cause any failures and default values #: will be ignored. Useful for completion. self.resilient_parsing = resilient_parsing # If there is no envvar prefix yet, but the parent has one and # the command on this level has a name, we can expand the envvar # prefix automatically. if auto_envvar_prefix is None: if parent is not None \ and parent.auto_envvar_prefix is not None and \ self.info_name is not None: auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix, self.info_name.upper()) else: auto_envvar_prefix = auto_envvar_prefix.upper() self.auto_envvar_prefix = auto_envvar_prefix if color is None and parent is not None: color = parent.color #: Controls if styling output is wanted or not. self.color = color self._close_callbacks = [] self._depth = 0 def __enter__(self): self._depth += 1 push_context(self) return self def __exit__(self, exc_type, exc_value, tb): self._depth -= 1 if self._depth == 0: self.close() pop_context() @contextmanager def scope(self, cleanup=True): """This helper method can be used with the context object to promote it to the current thread local (see :func:`get_current_context`). The default behavior of this is to invoke the cleanup functions which can be disabled by setting `cleanup` to `False`. The cleanup functions are typically used for things such as closing file handles. If the cleanup is intended the context object can also be directly used as a context manager. Example usage:: with ctx.scope(): assert get_current_context() is ctx This is equivalent:: with ctx: assert get_current_context() is ctx .. versionadded:: 5.0 :param cleanup: controls if the cleanup functions should be run or not. The default is to run these functions. In some situations the context only wants to be temporarily pushed in which case this can be disabled. Nested pushes automatically defer the cleanup. """ if not cleanup: self._depth += 1 try: with self as rv: yield rv finally: if not cleanup: self._depth -= 1 @property def meta(self): """This is a dictionary which is shared with all the contexts that are nested. It exists so that click utilities can store some state here if they need to. It is however the responsibility of that code to manage this dictionary well. The keys are supposed to be unique dotted strings. For instance module paths are a good choice for it. What is stored in there is irrelevant for the operation of click. However what is important is that code that places data here adheres to the general semantics of the system. Example usage:: LANG_KEY = __name__ + '.lang' def set_language(value): ctx = get_current_context() ctx.meta[LANG_KEY] = value def get_language(): return get_current_context().meta.get(LANG_KEY, 'en_US') .. versionadded:: 5.0 """ return self._meta def make_formatter(self): """Creates the formatter for the help and usage output.""" return HelpFormatter(width=self.terminal_width, max_width=self.max_content_width) def call_on_close(self, f): """This decorator remembers a function as callback that should be executed when the context tears down. This is most useful to bind resource handling to the script execution. For instance, file objects opened by the :class:`File` type will register their close callbacks here. :param f: the function to execute on teardown. """ self._close_callbacks.append(f) return f def close(self): """Invokes all close callbacks.""" for cb in self._close_callbacks: cb() self._close_callbacks = [] @property def command_path(self): """The computed command path. This is used for the ``usage`` information on the help page. It's automatically created by combining the info names of the chain of contexts to the root. """ rv = '' if self.info_name is not None: rv = self.info_name if self.parent is not None: rv = self.parent.command_path + ' ' + rv return rv.lstrip() def find_root(self): """Finds the outermost context.""" node = self while node.parent is not None: node = node.parent return node def find_object(self, object_type): """Finds the closest object of a given type.""" node = self while node is not None: if isinstance(node.obj, object_type): return node.obj node = node.parent def ensure_object(self, object_type): """Like :meth:`find_object` but sets the innermost object to a new instance of `object_type` if it does not exist. """ rv = self.find_object(object_type) if rv is None: self.obj = rv = object_type() return rv def lookup_default(self, name): """Looks up the default for a parameter name. This by default looks into the :attr:`default_map` if available. """ if self.default_map is not None: rv = self.default_map.get(name) if callable(rv): rv = rv() return rv def fail(self, message): """Aborts the execution of the program with a specific error message. :param message: the error message to fail with. """ raise UsageError(message, self) def abort(self): """Aborts the script.""" raise Abort() def exit(self, code=0): """Exits the application with a given exit code.""" raise Exit(code) def get_usage(self): """Helper method to get formatted usage string for the current context and command. """ return self.command.get_usage(self) def get_help(self): """Helper method to get formatted help page for the current context and command. """ return self.command.get_help(self) def invoke(*args, **kwargs): """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. """ self, callback = args[:2] ctx = self # It's also possible to invoke another command which might or # might not have a callback. In that case we also fill # in defaults and make a new context for this command. if isinstance(callback, Command): other_cmd = callback callback = other_cmd.callback ctx = Context(other_cmd, info_name=other_cmd.name, parent=self) if callback is None: raise TypeError('The given command does not have a ' 'callback that can be invoked.') for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.get_default(ctx) args = args[2:] with augment_usage_errors(self): with ctx: return callback(*args, **kwargs) def forward(*args, **kwargs): """Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. """ self, cmd = args[:2] # It's also possible to invoke another command which might or # might not have a callback. if not isinstance(cmd, Command): raise TypeError('Callback is not a command.') for param in self.params: if param not in kwargs: kwargs[param] = self.params[param] return self.invoke(cmd, **kwargs) class BaseCommand(object): """The base command implements the minimal API contract of commands. Most code will never use this as it does not implement a lot of useful functionality but it can act as the direct subclass of alternative parsing methods that do not depend on the Click parser. For instance, this can be used to bridge Click and other systems like argparse or docopt. Because base commands do not implement a lot of the API that other parts of Click take for granted, they are not supported for all operations. For instance, they cannot be used with the decorators usually and they have no built-in callback system. .. versionchanged:: 2.0 Added the `context_settings` parameter. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. """ #: the default for the :attr:`Context.allow_extra_args` flag. allow_extra_args = False #: the default for the :attr:`Context.allow_interspersed_args` flag. allow_interspersed_args = True #: the default for the :attr:`Context.ignore_unknown_options` flag. ignore_unknown_options = False def __init__(self, name, context_settings=None): #: the name the command thinks it has. Upon registering a command #: on a :class:`Group` the group will default the command name #: with this information. You should instead use the #: :class:`Context`\'s :attr:`~Context.info_name` attribute. self.name = name if context_settings is None: context_settings = {} #: an optional dictionary with defaults passed to the context. self.context_settings = context_settings def get_usage(self, ctx): raise NotImplementedError('Base commands cannot get usage') def get_help(self, ctx): raise NotImplementedError('Base commands cannot get help') def make_context(self, info_name, args, parent=None, **extra): """This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the script. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. """ for key, value in iteritems(self.context_settings): if key not in extra: extra[key] = value ctx = Context(self, info_name=info_name, parent=parent, **extra) with ctx.scope(cleanup=False): self.parse_args(ctx, args) return ctx def parse_args(self, ctx, args): """Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by :meth:`make_context`. """ raise NotImplementedError('Base commands do not know how to parse ' 'arguments.') def invoke(self, ctx): """Given a context, this invokes the command. The default implementation is raising a not implemented error. """ raise NotImplementedError('Base commands are not invokable by default') def main(self, args=None, prog_name=None, complete_var=None, standalone_mode=True, **extra): """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog_name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. """ # If we are in Python 3, we will verify that the environment is # sane at this point or reject further execution to avoid a # broken script. if not PY2: _verify_python3_env() else: _check_for_unicode_literals() if args is None: args = get_os_args() else: args = list(args) if prog_name is None: prog_name = make_str(os.path.basename( sys.argv and sys.argv[0] or __file__)) # Hook for the Bash completion. This only activates if the Bash # completion is actually enabled, otherwise this is quite a fast # noop. _bashcomplete(self, prog_name, complete_var) try: try: with self.make_context(prog_name, args, **extra) as ctx: rv = self.invoke(ctx) if not standalone_mode: return rv # it's not safe to `ctx.exit(rv)` here! # note that `rv` may actually contain data like "1" which # has obvious effects # more subtle case: `rv=[None, None]` can come out of # chained commands which all returned `None` -- so it's not # even always obvious that `rv` indicates success/failure # by its truthiness/falsiness ctx.exit() except (EOFError, KeyboardInterrupt): echo(file=sys.stderr) raise Abort() except ClickException as e: if not standalone_mode: raise e.show() sys.exit(e.exit_code) except IOError as e: if e.errno == errno.EPIPE: sys.stdout = PacifyFlushWrapper(sys.stdout) sys.stderr = PacifyFlushWrapper(sys.stderr) sys.exit(1) else: raise except Exit as e: if standalone_mode: sys.exit(e.exit_code) else: # in non-standalone mode, return the exit code # note that this is only reached if `self.invoke` above raises # an Exit explicitly -- thus bypassing the check there which # would return its result # the results of non-standalone execution may therefore be # somewhat ambiguous: if there are codepaths which lead to # `ctx.exit(1)` and to `return 1`, the caller won't be able to # tell the difference between the two return e.exit_code except Abort: if not standalone_mode: raise echo('Aborted!', file=sys.stderr) sys.exit(1) def __call__(self, *args, **kwargs): """Alias for :meth:`main`.""" return self.main(*args, **kwargs) class Command(BaseCommand): """Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it. .. versionchanged:: 2.0 Added the `context_settings` parameter. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. :param callback: the callback to invoke. This is optional. :param params: the parameters to register with this command. This can be either :class:`Option` or :class:`Argument` objects. :param help: the help string to use for this command. :param epilog: like the help string but it's printed at the end of the help page after everything else. :param short_help: the short help to use for this command. This is shown on the command listing of the parent command. :param add_help_option: by default each command registers a ``--help`` option. This can be disabled by this parameter. :param hidden: hide this command from help outputs. :param deprecated: issues a message indicating that the command is deprecated. """ def __init__(self, name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, hidden=False, deprecated=False): BaseCommand.__init__(self, name, context_settings) #: the callback to execute when the command fires. This might be #: `None` in which case nothing happens. self.callback = callback #: the list of parameters for this command in the order they #: should show up in the help page and execute. Eager parameters #: will automatically be handled before non eager ones. self.params = params or [] # if a form feed (page break) is found in the help text, truncate help # text to the content preceding the first form feed if help and '\f' in help: help = help.split('\f', 1)[0] self.help = help self.epilog = epilog self.options_metavar = options_metavar self.short_help = short_help self.add_help_option = add_help_option self.hidden = hidden self.deprecated = deprecated def get_usage(self, ctx): formatter = ctx.make_formatter() self.format_usage(ctx, formatter) return formatter.getvalue().rstrip('\n') def get_params(self, ctx): rv = self.params help_option = self.get_help_option(ctx) if help_option is not None: rv = rv + [help_option] return rv def format_usage(self, ctx, formatter): """Writes the usage line into the formatter.""" pieces = self.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, ' '.join(pieces)) def collect_usage_pieces(self, ctx): """Returns all the pieces that go into the usage line and returns it as a list of strings. """ rv = [self.options_metavar] for param in self.get_params(ctx): rv.extend(param.get_usage_pieces(ctx)) return rv def get_help_option_names(self, ctx): """Returns the names for the help option.""" all_names = set(ctx.help_option_names) for param in self.params: all_names.difference_update(param.opts) all_names.difference_update(param.secondary_opts) return all_names def get_help_option(self, ctx): """Returns the help option object.""" help_options = self.get_help_option_names(ctx) if not help_options or not self.add_help_option: return def show_help(ctx, param, value): if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() return Option(help_options, is_flag=True, is_eager=True, expose_value=False, callback=show_help, help='Show this message and exit.') def make_parser(self, ctx): """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser def get_help(self, ctx): """Formats the help into a string and returns it. This creates a formatter and will call into the following formatting methods: """ formatter = ctx.make_formatter() self.format_help(ctx, formatter) return formatter.getvalue().rstrip('\n') def get_short_help_str(self, limit=45): """Gets short help for the command or makes it by shortening the long help string.""" return self.short_help or self.help and make_default_short_help(self.help, limit) or '' def format_help(self, ctx, formatter): """Writes the help into the formatter if it exists. This calls into the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` """ self.format_usage(ctx, formatter) self.format_help_text(ctx, formatter) self.format_options(ctx, formatter) self.format_epilog(ctx, formatter) def format_help_text(self, ctx, formatter): """Writes the help text to the formatter if it exists.""" if self.help: formatter.write_paragraph() with formatter.indentation(): help_text = self.help if self.deprecated: help_text += DEPRECATED_HELP_NOTICE formatter.write_text(help_text) elif self.deprecated: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(DEPRECATED_HELP_NOTICE) def format_options(self, ctx, formatter): """Writes all the options into the formatter if they exist.""" opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: opts.append(rv) if opts: with formatter.section('Options'): formatter.write_dl(opts) def format_epilog(self, ctx, formatter): """Writes the epilog into the formatter if it exists.""" if self.epilog: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.epilog) def parse_args(self, ctx, args): parser = self.make_parser(ctx) opts, args, param_order = parser.parse_args(args=args) for param in iter_params_for_processing( param_order, self.get_params(ctx)): value, args = param.handle_parse_result(ctx, opts, args) if args and not ctx.allow_extra_args and not ctx.resilient_parsing: ctx.fail('Got unexpected extra argument%s (%s)' % (len(args) != 1 and 's' or '', ' '.join(map(make_str, args)))) ctx.args = args return args def invoke(self, ctx): """Given a context, this invokes the attached callback (if it exists) in the right way. """ _maybe_show_deprecated_notice(self) if self.callback is not None: return ctx.invoke(self.callback, **ctx.params) class MultiCommand(Command): """A multi command is the basic implementation of a command that dispatches to subcommands. The most common version is the :class:`Group`. :param invoke_without_command: this controls how the multi command itself is invoked. By default it's only invoked if a subcommand is provided. :param no_args_is_help: this controls what happens if no arguments are provided. This option is enabled by default if `invoke_without_command` is disabled or disabled if it's enabled. If enabled this will add ``--help`` as argument if no arguments are passed. :param subcommand_metavar: the string that is used in the documentation to indicate the subcommand place. :param chain: if this is set to `True` chaining of multiple subcommands is enabled. This restricts the form of commands in that they cannot have optional arguments but it allows multiple commands to be chained together. :param result_callback: the result callback to attach to this multi command. """ allow_extra_args = True allow_interspersed_args = False def __init__(self, name=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, **attrs): Command.__init__(self, name, **attrs) if no_args_is_help is None: no_args_is_help = not invoke_without_command self.no_args_is_help = no_args_is_help self.invoke_without_command = invoke_without_command if subcommand_metavar is None: if chain: subcommand_metavar = SUBCOMMANDS_METAVAR else: subcommand_metavar = SUBCOMMAND_METAVAR self.subcommand_metavar = subcommand_metavar self.chain = chain #: The result callback that is stored. This can be set or #: overridden with the :func:`resultcallback` decorator. self.result_callback = result_callback if self.chain: for param in self.params: if isinstance(param, Argument) and not param.required: raise RuntimeError('Multi commands in chain mode cannot ' 'have optional arguments.') def collect_usage_pieces(self, ctx): rv = Command.collect_usage_pieces(self, ctx) rv.append(self.subcommand_metavar) return rv def format_options(self, ctx, formatter): Command.format_options(self, ctx, formatter) self.format_commands(ctx, formatter) def resultcallback(self, replace=False): """Adds a result callback to the chain command. By default if a result callback is already registered this will chain them but this can be disabled with the `replace` parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback. Example:: @click.group() @click.option('-i', '--input', default=23) def cli(input): return 42 @cli.resultcallback() def process_result(result, input): return result + input .. versionadded:: 3.0 :param replace: if set to `True` an already existing result callback will be removed. """ def decorator(f): old_callback = self.result_callback if old_callback is None or replace: self.result_callback = f return f def function(__value, *args, **kwargs): return f(old_callback(__value, *args, **kwargs), *args, **kwargs) self.result_callback = rv = update_wrapper(function, f) return rv return decorator def format_commands(self, ctx, formatter): """Extra format methods for multi methods that adds all the commands after the options. """ commands = [] for subcommand in self.list_commands(ctx): cmd = self.get_command(ctx, subcommand) # What is this, the tool lied about a command. Ignore it if cmd is None: continue if cmd.hidden: continue commands.append((subcommand, cmd)) # allow for 3 times the default spacing if len(commands): limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) rows = [] for subcommand, cmd in commands: help = cmd.get_short_help_str(limit) rows.append((subcommand, help)) if rows: with formatter.section('Commands'): formatter.write_dl(rows) def parse_args(self, ctx, args): if not args and self.no_args_is_help and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() rest = Command.parse_args(self, ctx, args) if self.chain: ctx.protected_args = rest ctx.args = [] elif rest: ctx.protected_args, ctx.args = rest[:1], rest[1:] return ctx.args def invoke(self, ctx): def _process_result(value): if self.result_callback is not None: value = ctx.invoke(self.result_callback, value, **ctx.params) return value if not ctx.protected_args: # If we are invoked without command the chain flag controls # how this happens. If we are not in chain mode, the return # value here is the return value of the command. # If however we are in chain mode, the return value is the # return value of the result processor invoked with an empty # list (which means that no subcommand actually was executed). if self.invoke_without_command: if not self.chain: return Command.invoke(self, ctx) with ctx: Command.invoke(self, ctx) return _process_result([]) ctx.fail('Missing command.') # Fetch args back out args = ctx.protected_args + ctx.args ctx.args = [] ctx.protected_args = [] # If we're not in chain mode, we only allow the invocation of a # single command but we also inform the current context about the # name of the command to invoke. if not self.chain: # Make sure the context is entered so we do not clean up # resources until the result processor has worked. with ctx: cmd_name, cmd, args = self.resolve_command(ctx, args) ctx.invoked_subcommand = cmd_name Command.invoke(self, ctx) sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) with sub_ctx: return _process_result(sub_ctx.command.invoke(sub_ctx)) # In chain mode we create the contexts step by step, but after the # base command has been invoked. Because at that point we do not # know the subcommands yet, the invoked subcommand attribute is # set to ``*`` to inform the command that subcommands are executed # but nothing else. with ctx: ctx.invoked_subcommand = args and '*' or None Command.invoke(self, ctx) # Otherwise we make every single context and invoke them in a # chain. In that case the return value to the result processor # is the list of all invoked subcommand's results. contexts = [] while args: cmd_name, cmd, args = self.resolve_command(ctx, args) sub_ctx = cmd.make_context(cmd_name, args, parent=ctx, allow_extra_args=True, allow_interspersed_args=False) contexts.append(sub_ctx) args, sub_ctx.args = sub_ctx.args, [] rv = [] for sub_ctx in contexts: with sub_ctx: rv.append(sub_ctx.command.invoke(sub_ctx)) return _process_result(rv) def resolve_command(self, ctx, args): cmd_name = make_str(args[0]) original_cmd_name = cmd_name # Get the command cmd = self.get_command(ctx, cmd_name) # If we can't find the command but there is a normalization # function available, we try with that one. if cmd is None and ctx.token_normalize_func is not None: cmd_name = ctx.token_normalize_func(cmd_name) cmd = self.get_command(ctx, cmd_name) # If we don't find the command we want to show an error message # to the user that it was not provided. However, there is # something else we should do: if the first argument looks like # an option we want to kick off parsing again for arguments to # resolve things like --help which now should go to the main # place. if cmd is None and not ctx.resilient_parsing: if split_opt(cmd_name)[0]: self.parse_args(ctx, ctx.args) ctx.fail('No such command "%s".' % original_cmd_name) return cmd_name, cmd, args[1:] def get_command(self, ctx, cmd_name): """Given a context and a command name, this returns a :class:`Command` object if it exists or returns `None`. """ raise NotImplementedError() def list_commands(self, ctx): """Returns a list of subcommand names in the order they should appear. """ return [] class Group(MultiCommand): """A group allows a command to have subcommands attached. This is the most common way to implement nesting in Click. :param commands: a dictionary of commands. """ def __init__(self, name=None, commands=None, **attrs): MultiCommand.__init__(self, name, **attrs) #: the registered subcommands by their exported names. self.commands = commands or {} def add_command(self, cmd, name=None): """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError('Command has no name.') _check_multicommand(self, name, cmd, register=True) self.commands[name] = cmd def command(self, *args, **kwargs): """A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` but immediately registers the created command with this instance by calling into :meth:`add_command`. """ def decorator(f): cmd = command(*args, **kwargs)(f) self.add_command(cmd) return cmd return decorator def group(self, *args, **kwargs): """A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` but immediately registers the created command with this instance by calling into :meth:`add_command`. """ def decorator(f): cmd = group(*args, **kwargs)(f) self.add_command(cmd) return cmd return decorator def get_command(self, ctx, cmd_name): return self.commands.get(cmd_name) def list_commands(self, ctx): return sorted(self.commands) class CommandCollection(MultiCommand): """A command collection is a multi command that merges multiple multi commands together into one. This is a straightforward implementation that accepts a list of different multi commands as sources and provides all the commands for each of them. """ def __init__(self, name=None, sources=None, **attrs): MultiCommand.__init__(self, name, **attrs) #: The list of registered multi commands. self.sources = sources or [] def add_source(self, multi_cmd): """Adds a new multi command to the chain dispatcher.""" self.sources.append(multi_cmd) def get_command(self, ctx, cmd_name): for source in self.sources: rv = source.get_command(ctx, cmd_name) if rv is not None: if self.chain: _check_multicommand(self, cmd_name, rv) return rv def list_commands(self, ctx): rv = set() for source in self.sources: rv.update(source.list_commands(ctx)) return sorted(rv) class Parameter(object): r"""A parameter to a command comes in two versions: they are either :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized. Some settings are supported by both options and arguments. .. versionchanged:: 2.0 Changed signature for parameter callback to also be passed the parameter. In Click 2.0, the old callback format will still work, but it will raise a warning to give you change to migrate the code easier. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param type: the type that should be used. Either a :class:`ParamType` or a Python type. The later is converted into the former automatically if supported. :param required: controls if this is optional or not. :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. :param callback: a callback that should be executed after the parameter was matched. This is called as ``fn(ctx, param, value)`` and needs to return the value. Before Click 2.0, the signature was ``(ctx, value)``. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's the arity of the tuple). :param metavar: how the value is represented in the help page. :param expose_value: if this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it's skipped. :param is_eager: eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing. :param envvar: a string or list of strings that are environment variables that should be checked. """ param_type_name = 'parameter' def __init__(self, param_decls=None, type=None, required=False, default=None, callback=None, nargs=None, metavar=None, expose_value=True, is_eager=False, envvar=None, autocompletion=None): self.name, self.opts, self.secondary_opts = \ self._parse_decls(param_decls or (), expose_value) self.type = convert_type(type, default) # Default nargs to what the type tells us if we have that # information available. if nargs is None: if self.type.is_composite: nargs = self.type.arity else: nargs = 1 self.required = required self.callback = callback self.nargs = nargs self.multiple = False self.expose_value = expose_value self.default = default self.is_eager = is_eager self.metavar = metavar self.envvar = envvar self.autocompletion = autocompletion @property def human_readable_name(self): """Returns the human readable name of this parameter. This is the same as the name for options, but the metavar for arguments. """ return self.name def make_metavar(self): if self.metavar is not None: return self.metavar metavar = self.type.get_metavar(self) if metavar is None: metavar = self.type.name.upper() if self.nargs != 1: metavar += '...' return metavar def get_default(self, ctx): """Given a context variable this calculates the default value.""" # Otherwise go with the regular default. if callable(self.default): rv = self.default() else: rv = self.default return self.type_cast_value(ctx, rv) def add_to_parser(self, parser, ctx): pass def consume_value(self, ctx, opts): value = opts.get(self.name) if value is None: value = self.value_from_envvar(ctx) if value is None: value = ctx.lookup_default(self.name) return value def type_cast_value(self, ctx, value): """Given a value this runs it properly through the type system. This automatically handles things like `nargs` and `multiple` as well as composite types. """ if self.type.is_composite: if self.nargs <= 1: raise TypeError('Attempted to invoke composite type ' 'but nargs has been set to %s. This is ' 'not supported; nargs needs to be set to ' 'a fixed value > 1.' % self.nargs) if self.multiple: return tuple(self.type(x or (), self, ctx) for x in value or ()) return self.type(value or (), self, ctx) def _convert(value, level): if level == 0: return self.type(value, self, ctx) return tuple(_convert(x, level - 1) for x in value or ()) return _convert(value, (self.nargs != 1) + bool(self.multiple)) def process_value(self, ctx, value): """Given a value and context this runs the logic to convert the value as necessary. """ # If the value we were given is None we do nothing. This way # code that calls this can easily figure out if something was # not provided. Otherwise it would be converted into an empty # tuple for multiple invocations which is inconvenient. if value is not None: return self.type_cast_value(ctx, value) def value_is_missing(self, value): if value is None: return True if (self.nargs != 1 or self.multiple) and value == (): return True return False def full_process_value(self, ctx, value): value = self.process_value(ctx, value) if value is None and not ctx.resilient_parsing: value = self.get_default(ctx) if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self) return value def resolve_envvar_value(self, ctx): if self.envvar is None: return if isinstance(self.envvar, (tuple, list)): for envvar in self.envvar: rv = os.environ.get(envvar) if rv is not None: return rv else: return os.environ.get(self.envvar) def value_from_envvar(self, ctx): rv = self.resolve_envvar_value(ctx) if rv is not None and self.nargs != 1: rv = self.type.split_envvar_value(rv) return rv def handle_parse_result(self, ctx, opts, args): with augment_usage_errors(ctx, param=self): value = self.consume_value(ctx, opts) try: value = self.full_process_value(ctx, value) except Exception: if not ctx.resilient_parsing: raise value = None if self.callback is not None: try: value = invoke_param_callback( self.callback, ctx, self, value) except Exception: if not ctx.resilient_parsing: raise if self.expose_value: ctx.params[self.name] = value return value, args def get_help_record(self, ctx): pass def get_usage_pieces(self, ctx): return [] def get_error_hint(self, ctx): """Get a stringified version of the param for use in error messages to indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] return ' / '.join('"%s"' % x for x in hint_list) class Option(Parameter): """Options are usually optional values on the command line and have some extra features that arguments don't have. All other parameters are passed onwards to the parameter constructor. :param show_default: controls if the default value should be shown on the help page. Normally, defaults are not shown. If this value is a string, it shows the string instead of the value. This is particularly useful for dynamic options. :param show_envvar: controls if an environment variable should be shown on the help page. Normally, environment variables are not shown. :param prompt: if set to `True` or a non empty string then the user will be prompted for input. If set to `True` the prompt will be the option name capitalized. :param confirmation_prompt: if set then the value will need to be confirmed if it was prompted for. :param hide_input: if this is `True` then the input on the prompt will be hidden from the user. This is useful for password input. :param is_flag: forces this option to act as a flag. The default is auto detection. :param flag_value: which value should be used for this flag if it's enabled. This is set to a boolean automatically if the option string contains a slash to mark two options. :param multiple: if this is set to `True` then the argument is accepted multiple times and recorded. This is similar to ``nargs`` in how it works but supports arbitrary number of arguments. :param count: this flag makes an option increment an integer. :param allow_from_autoenv: if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. :param help: the help string. :param hidden: hide this option from help outputs. """ param_type_name = 'option' def __init__(self, param_decls=None, show_default=False, prompt=False, confirmation_prompt=False, hide_input=False, is_flag=None, flag_value=None, multiple=False, count=False, allow_from_autoenv=True, type=None, help=None, hidden=False, show_choices=True, show_envvar=False, **attrs): default_is_missing = attrs.get('default', _missing) is _missing Parameter.__init__(self, param_decls, type=type, **attrs) if prompt is True: prompt_text = self.name.replace('_', ' ').capitalize() elif prompt is False: prompt_text = None else: prompt_text = prompt self.prompt = prompt_text self.confirmation_prompt = confirmation_prompt self.hide_input = hide_input self.hidden = hidden # Flags if is_flag is None: if flag_value is not None: is_flag = True else: is_flag = bool(self.secondary_opts) if is_flag and default_is_missing: self.default = False if flag_value is None: flag_value = not self.default self.is_flag = is_flag self.flag_value = flag_value if self.is_flag and isinstance(self.flag_value, bool) \ and type is None: self.type = BOOL self.is_bool_flag = True else: self.is_bool_flag = False # Counting self.count = count if count: if type is None: self.type = IntRange(min=0) if default_is_missing: self.default = 0 self.multiple = multiple self.allow_from_autoenv = allow_from_autoenv self.help = help self.show_default = show_default self.show_choices = show_choices self.show_envvar = show_envvar # Sanity check for stuff we don't support if __debug__: if self.nargs < 0: raise TypeError('Options cannot have nargs < 0') if self.prompt and self.is_flag and not self.is_bool_flag: raise TypeError('Cannot prompt for flags that are not bools.') if not self.is_bool_flag and self.secondary_opts: raise TypeError('Got secondary option for non boolean flag.') if self.is_bool_flag and self.hide_input \ and self.prompt is not None: raise TypeError('Hidden input does not work with boolean ' 'flag prompts.') if self.count: if self.multiple: raise TypeError('Options cannot be multiple and count ' 'at the same time.') elif self.is_flag: raise TypeError('Options cannot be count and flags at ' 'the same time.') def _parse_decls(self, decls, expose_value): opts = [] secondary_opts = [] name = None possible_names = [] for decl in decls: if isidentifier(decl): if name is not None: raise TypeError('Name defined twice') name = decl else: split_char = decl[:1] == '/' and ';' or '/' if split_char in decl: first, second = decl.split(split_char, 1) first = first.rstrip() if first: possible_names.append(split_opt(first)) opts.append(first) second = second.lstrip() if second: secondary_opts.append(second.lstrip()) else: possible_names.append(split_opt(decl)) opts.append(decl) if name is None and possible_names: possible_names.sort(key=lambda x: -len(x[0])) # group long options first name = possible_names[0][1].replace('-', '_').lower() if not isidentifier(name): name = None if name is None: if not expose_value: return None, opts, secondary_opts raise TypeError('Could not determine name for option') if not opts and not secondary_opts: raise TypeError('No options defined but a name was passed (%s). ' 'Did you mean to declare an argument instead ' 'of an option?' % name) return name, opts, secondary_opts def add_to_parser(self, parser, ctx): kwargs = { 'dest': self.name, 'nargs': self.nargs, 'obj': self, } if self.multiple: action = 'append' elif self.count: action = 'count' else: action = 'store' if self.is_flag: kwargs.pop('nargs', None) if self.is_bool_flag and self.secondary_opts: parser.add_option(self.opts, action=action + '_const', const=True, **kwargs) parser.add_option(self.secondary_opts, action=action + '_const', const=False, **kwargs) else: parser.add_option(self.opts, action=action + '_const', const=self.flag_value, **kwargs) else: kwargs['action'] = action parser.add_option(self.opts, **kwargs) def get_help_record(self, ctx): if self.hidden: return any_prefix_is_slash = [] def _write_opts(opts): rv, any_slashes = join_options(opts) if any_slashes: any_prefix_is_slash[:] = [True] if not self.is_flag and not self.count: rv += ' ' + self.make_metavar() return rv rv = [_write_opts(self.opts)] if self.secondary_opts: rv.append(_write_opts(self.secondary_opts)) help = self.help or '' extra = [] if self.show_envvar: envvar = self.envvar if envvar is None: if self.allow_from_autoenv and \ ctx.auto_envvar_prefix is not None: envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper()) if envvar is not None: extra.append('env var: %s' % ( ', '.join('%s' % d for d in envvar) if isinstance(envvar, (list, tuple)) else envvar, )) if self.default is not None and self.show_default: if isinstance(self.show_default, string_types): default_string = '({})'.format(self.show_default) elif isinstance(self.default, (list, tuple)): default_string = ', '.join('%s' % d for d in self.default) elif inspect.isfunction(self.default): default_string = "(dynamic)" else: default_string = self.default extra.append('default: {}'.format(default_string)) if self.required: extra.append('required') if extra: help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra)) return ((any_prefix_is_slash and '; ' or ' / ').join(rv), help) def get_default(self, ctx): # If we're a non boolean flag out default is more complex because # we need to look at all flags in the same group to figure out # if we're the the default one in which case we return the flag # value as default. if self.is_flag and not self.is_bool_flag: for param in ctx.command.params: if param.name == self.name and param.default: return param.flag_value return None return Parameter.get_default(self, ctx) def prompt_for_value(self, ctx): """This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result. """ # Calculate the default before prompting anything to be stable. default = self.get_default(ctx) # If this is a prompt for a flag we need to handle this # differently. if self.is_bool_flag: return confirm(self.prompt, default) return prompt(self.prompt, default=default, type=self.type, hide_input=self.hide_input, show_choices=self.show_choices, confirmation_prompt=self.confirmation_prompt, value_proc=lambda x: self.process_value(ctx, x)) def resolve_envvar_value(self, ctx): rv = Parameter.resolve_envvar_value(self, ctx) if rv is not None: return rv if self.allow_from_autoenv and \ ctx.auto_envvar_prefix is not None: envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper()) return os.environ.get(envvar) def value_from_envvar(self, ctx): rv = self.resolve_envvar_value(ctx) if rv is None: return None value_depth = (self.nargs != 1) + bool(self.multiple) if value_depth > 0 and rv is not None: rv = self.type.split_envvar_value(rv) if self.multiple and self.nargs != 1: rv = batch(rv, self.nargs) return rv def full_process_value(self, ctx, value): if value is None and self.prompt is not None \ and not ctx.resilient_parsing: return self.prompt_for_value(ctx) return Parameter.full_process_value(self, ctx, value) class Argument(Parameter): """Arguments are positional parameters to a command. They generally provide fewer features than options but can have infinite ``nargs`` and are required by default. All parameters are passed onwards to the parameter constructor. """ param_type_name = 'argument' def __init__(self, param_decls, required=None, **attrs): if required is None: if attrs.get('default') is not None: required = False else: required = attrs.get('nargs', 1) > 0 Parameter.__init__(self, param_decls, required=required, **attrs) if self.default is not None and self.nargs < 0: raise TypeError('nargs=-1 in combination with a default value ' 'is not supported.') @property def human_readable_name(self): if self.metavar is not None: return self.metavar return self.name.upper() def make_metavar(self): if self.metavar is not None: return self.metavar var = self.type.get_metavar(self) if not var: var = self.name.upper() if not self.required: var = '[%s]' % var if self.nargs != 1: var += '...' return var def _parse_decls(self, decls, expose_value): if not decls: if not expose_value: return None, [], [] raise TypeError('Could not determine name for argument') if len(decls) == 1: name = arg = decls[0] name = name.replace('-', '_').lower() else: raise TypeError('Arguments take exactly one ' 'parameter declaration, got %d' % len(decls)) return name, [arg], [] def get_usage_pieces(self, ctx): return [self.make_metavar()] def get_error_hint(self, ctx): return '"%s"' % self.make_metavar() def add_to_parser(self, parser, ctx): parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) # Circular dependency between decorators and core from .decorators import command, group
bsd-3-clause
epam-mooc/edx-platform
common/lib/xmodule/xmodule/tests/test_split_test_module.py
11
21753
""" Tests for the Split Testing Module """ import ddt import lxml from mock import Mock, patch from fs.memoryfs import MemoryFS from xmodule.tests.xml import factories as xml from xmodule.tests.xml import XModuleXmlImportTest from xmodule.tests import get_test_system from xmodule.x_module import AUTHOR_VIEW, STUDENT_VIEW from xmodule.split_test_module import SplitTestDescriptor, SplitTestFields, ValidationMessageType from xmodule.partitions.partitions import Group, UserPartition from xmodule.partitions.test_partitions import StaticPartitionService, MemoryUserTagsService class SplitTestModuleFactory(xml.XmlImportFactory): """ Factory for generating SplitTestModules for testing purposes """ tag = 'split_test' class SplitTestModuleTest(XModuleXmlImportTest): """ Base class for all split_module tests. """ def setUp(self): self.course_id = 'test_org/test_course_number/test_run' # construct module course = xml.CourseFactory.build() sequence = xml.SequenceFactory.build(parent=course) split_test = SplitTestModuleFactory( parent=sequence, attribs={ 'user_partition_id': '0', 'group_id_to_child': '{"0": "i4x://edX/xml_test_course/html/split_test_cond0", "1": "i4x://edX/xml_test_course/html/split_test_cond1"}' } ) xml.HtmlFactory(parent=split_test, url_name='split_test_cond0', text='HTML FOR GROUP 0') xml.HtmlFactory(parent=split_test, url_name='split_test_cond1', text='HTML FOR GROUP 1') self.course = self.process_xml(course) self.course_sequence = self.course.get_children()[0] self.module_system = get_test_system() def get_module(descriptor): """Mocks module_system get_module function""" module_system = get_test_system() module_system.get_module = get_module descriptor.bind_for_student(module_system, descriptor._field_data) # pylint: disable=protected-access return descriptor self.module_system.get_module = get_module self.module_system.descriptor_system = self.course.runtime self.course.runtime.export_fs = MemoryFS() self.tags_service = MemoryUserTagsService() self.module_system._services['user_tags'] = self.tags_service # pylint: disable=protected-access self.partitions_service = StaticPartitionService( [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("1", 'beta')]), UserPartition(1, 'second_partition', 'Second Partition', [Group("0", 'abel'), Group("1", 'baker'), Group("2", 'charlie')]) ], user_tags_service=self.tags_service, course_id=self.course.id, track_function=Mock(name='track_function'), ) self.module_system._services['partitions'] = self.partitions_service # pylint: disable=protected-access self.split_test_module = self.course_sequence.get_children()[0] self.split_test_module.bind_for_student(self.module_system, self.split_test_module._field_data) # pylint: disable=protected-access @ddt.ddt class SplitTestModuleLMSTest(SplitTestModuleTest): """ Test the split test module """ @ddt.data(('0', 'split_test_cond0'), ('1', 'split_test_cond1')) @ddt.unpack def test_child(self, user_tag, child_url_name): self.tags_service.set_tag( self.tags_service.COURSE_SCOPE, 'xblock.partition_service.partition_0', user_tag ) self.assertEquals(self.split_test_module.child_descriptor.url_name, child_url_name) @ddt.data(('0',), ('1',)) @ddt.unpack def test_child_old_tag_value(self, _user_tag): # If user_tag has a stale value, we should still get back a valid child url self.tags_service.set_tag( self.tags_service.COURSE_SCOPE, 'xblock.partition_service.partition_0', '2' ) self.assertIn(self.split_test_module.child_descriptor.url_name, ['split_test_cond0', 'split_test_cond1']) @ddt.data(('0', 'HTML FOR GROUP 0'), ('1', 'HTML FOR GROUP 1')) @ddt.unpack def test_get_html(self, user_tag, child_content): self.tags_service.set_tag( self.tags_service.COURSE_SCOPE, 'xblock.partition_service.partition_0', user_tag ) self.assertIn( child_content, self.module_system.render(self.split_test_module, STUDENT_VIEW).content ) @ddt.data(('0',), ('1',)) @ddt.unpack def test_child_missing_tag_value(self, _user_tag): # If user_tag has a missing value, we should still get back a valid child url self.assertIn(self.split_test_module.child_descriptor.url_name, ['split_test_cond0', 'split_test_cond1']) @ddt.data(('100',), ('200',), ('300',), ('400',), ('500',), ('600',), ('700',), ('800',), ('900',), ('1000',)) @ddt.unpack def test_child_persist_new_tag_value_when_tag_missing(self, _user_tag): # If a user_tag has a missing value, a group should be saved/persisted for that user. # So, we check that we get the same url_name when we call on the url_name twice. # We run the test ten times so that, if our storage is failing, we'll be most likely to notice it. self.assertEquals(self.split_test_module.child_descriptor.url_name, self.split_test_module.child_descriptor.url_name) # Patch the definition_to_xml for the html children. @patch('xmodule.html_module.HtmlDescriptor.definition_to_xml') def test_export_import_round_trip(self, def_to_xml): # The HtmlDescriptor definition_to_xml tries to write to the filesystem # before returning an xml object. Patch this to just return the xml. def_to_xml.return_value = lxml.etree.Element('html') # Mock out the process_xml # Expect it to return a child descriptor for the SplitTestDescriptor when called. self.module_system.process_xml = Mock() # Write out the xml. xml_obj = self.split_test_module.definition_to_xml(MemoryFS()) self.assertEquals(xml_obj.get('user_partition_id'), '0') self.assertIsNotNone(xml_obj.get('group_id_to_child')) # Read the xml back in. fields, children = SplitTestDescriptor.definition_from_xml(xml_obj, self.module_system) self.assertEquals(fields.get('user_partition_id'), '0') self.assertIsNotNone(fields.get('group_id_to_child')) self.assertEquals(len(children), 2) class SplitTestModuleStudioTest(SplitTestModuleTest): """ Unit tests for how split test interacts with Studio. """ @patch('xmodule.split_test_module.SplitTestDescriptor.group_configuration_url', return_value='http://example.com') def test_render_author_view(self, group_configuration_url): """ Test the rendering of the Studio author view. """ def create_studio_context(root_xblock): """ Context for rendering the studio "author_view". """ return { 'reorderable_items': set(), 'root_xblock': root_xblock, } # The split_test module should render both its groups when it is the root context = create_studio_context(self.split_test_module) html = self.module_system.render(self.split_test_module, AUTHOR_VIEW, context).content self.assertIn('HTML FOR GROUP 0', html) self.assertIn('HTML FOR GROUP 1', html) # When rendering as a child, it shouldn't render either of its groups context = create_studio_context(self.course_sequence) html = self.module_system.render(self.split_test_module, AUTHOR_VIEW, context).content self.assertNotIn('HTML FOR GROUP 0', html) self.assertNotIn('HTML FOR GROUP 1', html) # The "Create Missing Groups" button should be rendered when groups are missing context = create_studio_context(self.split_test_module) self.split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("1", 'beta'), Group("2", 'gamma')]) ] html = self.module_system.render(self.split_test_module, AUTHOR_VIEW, context).content self.assertIn('HTML FOR GROUP 0', html) self.assertIn('HTML FOR GROUP 1', html) def test_group_configuration_url(self): """ Test creation of correct Group Configuration URL. """ mocked_course = Mock(advanced_modules=['split_test']) mocked_modulestore = Mock() mocked_modulestore.get_course.return_value = mocked_course self.split_test_module.system.modulestore = mocked_modulestore self.split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("1", 'beta')]) ] expected_url = '/group_configurations/edX/xml_test_course/101#0' self.assertEqual(expected_url, self.split_test_module.group_configuration_url) def test_editable_settings(self): """ Test the setting information passed back from editable_metadata_fields. """ editable_metadata_fields = self.split_test_module.editable_metadata_fields self.assertIn(SplitTestDescriptor.display_name.name, editable_metadata_fields) self.assertNotIn(SplitTestDescriptor.due.name, editable_metadata_fields) self.assertNotIn(SplitTestDescriptor.user_partitions.name, editable_metadata_fields) # user_partition_id will always appear in editable_metadata_settings, regardless # of the selected value. self.assertIn(SplitTestDescriptor.user_partition_id.name, editable_metadata_fields) def test_non_editable_settings(self): """ Test the settings that are marked as "non-editable". """ non_editable_metadata_fields = self.split_test_module.non_editable_metadata_fields self.assertIn(SplitTestDescriptor.due, non_editable_metadata_fields) self.assertIn(SplitTestDescriptor.user_partitions, non_editable_metadata_fields) self.assertNotIn(SplitTestDescriptor.display_name, non_editable_metadata_fields) def test_available_partitions(self): """ Tests that the available partitions are populated correctly when editable_metadata_fields are called """ self.assertEqual([], SplitTestDescriptor.user_partition_id.values) # user_partitions is empty, only the "Not Selected" item will appear. self.split_test_module.user_partition_id = SplitTestFields.no_partition_selected['value'] self.split_test_module.editable_metadata_fields # pylint: disable=pointless-statement partitions = SplitTestDescriptor.user_partition_id.values self.assertEqual(1, len(partitions)) self.assertEqual(SplitTestFields.no_partition_selected['value'], partitions[0]['value']) # Populate user_partitions and call editable_metadata_fields again self.split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("1", 'beta')]) ] self.split_test_module.editable_metadata_fields # pylint: disable=pointless-statement partitions = SplitTestDescriptor.user_partition_id.values self.assertEqual(2, len(partitions)) self.assertEqual(SplitTestFields.no_partition_selected['value'], partitions[0]['value']) self.assertEqual(0, partitions[1]['value']) self.assertEqual("first_partition", partitions[1]['display_name']) # Try again with a selected partition and verify that there is no option for "No Selection" self.split_test_module.user_partition_id = 0 self.split_test_module.editable_metadata_fields # pylint: disable=pointless-statement partitions = SplitTestDescriptor.user_partition_id.values self.assertEqual(1, len(partitions)) self.assertEqual(0, partitions[0]['value']) self.assertEqual("first_partition", partitions[0]['display_name']) # Finally try again with an invalid selected partition and verify that "No Selection" is an option self.split_test_module.user_partition_id = 999 self.split_test_module.editable_metadata_fields # pylint: disable=pointless-statement partitions = SplitTestDescriptor.user_partition_id.values self.assertEqual(2, len(partitions)) self.assertEqual(SplitTestFields.no_partition_selected['value'], partitions[0]['value']) self.assertEqual(0, partitions[1]['value']) self.assertEqual("first_partition", partitions[1]['display_name']) def test_active_and_inactive_children(self): """ Tests the active and inactive children returned for different split test configurations. """ split_test_module = self.split_test_module children = split_test_module.get_children() # Verify that a split test has no active children if it has no specified user partition. split_test_module.user_partition_id = -1 [active_children, inactive_children] = split_test_module.active_and_inactive_children() self.assertEqual(active_children, []) self.assertEqual(inactive_children, children) # Verify that all the children are returned as active for a correctly configured split_test split_test_module.user_partition_id = 0 split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("1", 'beta')]) ] [active_children, inactive_children] = split_test_module.active_and_inactive_children() self.assertEqual(active_children, children) self.assertEqual(inactive_children, []) # Verify that a split_test does not return inactive children in the active children self.split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha')]) ] [active_children, inactive_children] = split_test_module.active_and_inactive_children() self.assertEqual(active_children, [children[0]]) self.assertEqual(inactive_children, [children[1]]) # Verify that a split_test ignores misconfigured children self.split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("2", 'gamma')]) ] [active_children, inactive_children] = split_test_module.active_and_inactive_children() self.assertEqual(active_children, [children[0]]) self.assertEqual(inactive_children, [children[1]]) # Verify that a split_test referring to a non-existent user partition has no active children self.split_test_module.user_partition_id = 2 [active_children, inactive_children] = split_test_module.active_and_inactive_children() self.assertEqual(active_children, []) self.assertEqual(inactive_children, children) def test_validation_message_types(self): """ Test the behavior of validation message types. """ self.assertEqual(ValidationMessageType.display_name(ValidationMessageType.error), u"Error") self.assertEqual(ValidationMessageType.display_name(ValidationMessageType.warning), u"Warning") self.assertIsNone(ValidationMessageType.display_name(ValidationMessageType.information)) def test_validation_messages(self): """ Test the validation messages produced for different split test configurations. """ split_test_module = self.split_test_module def verify_validation_message(message, expected_message, expected_message_type, expected_action_class=None, expected_action_label=None): """ Verify that the validation message has the expected validation message and type. """ self.assertEqual(unicode(message), expected_message) self.assertEqual(message.message_type, expected_message_type) self.assertEqual(message.action_class, expected_action_class) self.assertEqual(message.action_label, expected_action_label) def verify_general_validation_message(general_validation, expected_message, expected_message_type): """ Verify that the general validation message has the expected validation message and type. """ self.assertEqual(unicode(general_validation['message']), expected_message) self.assertEqual(general_validation['type'], expected_message_type) # Verify the messages for an unconfigured user partition split_test_module.user_partition_id = -1 messages = split_test_module.validation_messages() self.assertEqual(len(messages), 1) verify_validation_message( messages[0], u"The experiment is not associated with a group configuration.", ValidationMessageType.warning, 'edit-button', u"Select a Group Configuration", ) verify_general_validation_message( split_test_module.general_validation_message, u"This content experiment has issues that affect content visibility.", ValidationMessageType.warning ) # Verify the messages for a correctly configured split_test split_test_module.user_partition_id = 0 split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("1", 'beta')]) ] messages = split_test_module.validation_messages() self.assertEqual(len(messages), 0) self.assertIsNone(split_test_module.general_validation_message, None) # Verify the messages for a split test with too few groups split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("1", 'beta'), Group("2", 'gamma')]) ] messages = split_test_module.validation_messages() self.assertEqual(len(messages), 1) verify_validation_message( messages[0], u"The experiment does not contain all of the groups in the configuration.", ValidationMessageType.error, 'add-missing-groups-button', u"Add Missing Groups" ) verify_general_validation_message( split_test_module.general_validation_message, u"This content experiment has issues that affect content visibility.", ValidationMessageType.error ) # Verify the messages for a split test with children that are not associated with any group split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha')]) ] messages = split_test_module.validation_messages() self.assertEqual(len(messages), 1) verify_validation_message( messages[0], u"The experiment has an inactive group. Move content into active groups, then delete the inactive group.", ValidationMessageType.warning ) verify_general_validation_message( split_test_module.general_validation_message, u"This content experiment has issues that affect content visibility.", ValidationMessageType.warning ) # Verify the messages for a split test with both missing and inactive children split_test_module.user_partitions = [ UserPartition(0, 'first_partition', 'First Partition', [Group("0", 'alpha'), Group("2", 'gamma')]) ] messages = split_test_module.validation_messages() self.assertEqual(len(messages), 2) verify_validation_message( messages[0], u"The experiment does not contain all of the groups in the configuration.", ValidationMessageType.error, 'add-missing-groups-button', u"Add Missing Groups" ) verify_validation_message( messages[1], u"The experiment has an inactive group. Move content into active groups, then delete the inactive group.", ValidationMessageType.warning ) # With two messages of type error and warning priority given to error. verify_general_validation_message( split_test_module.general_validation_message, u"This content experiment has issues that affect content visibility.", ValidationMessageType.error ) # Verify the messages for a split test referring to a non-existent user partition split_test_module.user_partition_id = 2 messages = split_test_module.validation_messages() self.assertEqual(len(messages), 1) verify_validation_message( messages[0], u"The experiment uses a deleted group configuration. " u"Select a valid group configuration or delete this experiment.", ValidationMessageType.error ) verify_general_validation_message( split_test_module.general_validation_message, u"This content experiment has issues that affect content visibility.", ValidationMessageType.error )
agpl-3.0
mpurzynski/MozDef
mq/plugins/large_strings.py
2
1926
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. # Copyright (c) 2014 Mozilla Corporation class message(object): def __init__(self): self.registration = ['nubis_events_prod', 'githubeventsqs'] self.priority = 20 self.MAX_STRING_LENGTH = 3000 def onMessage(self, message, metadata): if 'details' in message: if 'message' in message['details']: if type(message['details']['message']) is str \ and len(message['details']['message']) > self.MAX_STRING_LENGTH: message['details']['message'] = message['details']['message'][:self.MAX_STRING_LENGTH] message['details']['message'] += ' ...' if 'cmdline' in message['details']: if type(message['details']['cmdline']) is str \ and len(message['details']['cmdline']) > self.MAX_STRING_LENGTH: message['details']['cmdline'] = message['details']['cmdline'][:self.MAX_STRING_LENGTH] message['details']['cmdline'] += ' ...' if 'pr_body' in message['details']: if type(message['details']['pr_body']) is str \ and len(message['details']['pr_body']) > self.MAX_STRING_LENGTH: message['details']['pr_body'] = message['details']['pr_body'][:self.MAX_STRING_LENGTH] message['details']['pr_body'] += ' ...' if 'summary' in message: if type(message['summary']) is str \ and len(message['summary']) > self.MAX_STRING_LENGTH: message['summary'] = message['summary'][:self.MAX_STRING_LENGTH] message['summary'] += ' ...' return (message, metadata)
mpl-2.0
formath/mxnet
example/rcnn/rcnn/core/metric.py
41
5952
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import mxnet as mx import numpy as np from rcnn.config import config def get_rpn_names(): pred = ['rpn_cls_prob', 'rpn_bbox_loss'] label = ['rpn_label', 'rpn_bbox_target', 'rpn_bbox_weight'] return pred, label def get_rcnn_names(): pred = ['rcnn_cls_prob', 'rcnn_bbox_loss'] label = ['rcnn_label', 'rcnn_bbox_target', 'rcnn_bbox_weight'] if config.TRAIN.END2END: pred.append('rcnn_label') rpn_pred, rpn_label = get_rpn_names() pred = rpn_pred + pred label = rpn_label return pred, label class RPNAccMetric(mx.metric.EvalMetric): def __init__(self): super(RPNAccMetric, self).__init__('RPNAcc') self.pred, self.label = get_rpn_names() def update(self, labels, preds): pred = preds[self.pred.index('rpn_cls_prob')] label = labels[self.label.index('rpn_label')] # pred (b, c, p) or (b, c, h, w) pred_label = mx.ndarray.argmax_channel(pred).asnumpy().astype('int32') pred_label = pred_label.reshape((pred_label.shape[0], -1)) # label (b, p) label = label.asnumpy().astype('int32') # filter with keep_inds keep_inds = np.where(label != -1) pred_label = pred_label[keep_inds] label = label[keep_inds] self.sum_metric += np.sum(pred_label.flat == label.flat) self.num_inst += len(pred_label.flat) class RCNNAccMetric(mx.metric.EvalMetric): def __init__(self): super(RCNNAccMetric, self).__init__('RCNNAcc') self.e2e = config.TRAIN.END2END self.pred, self.label = get_rcnn_names() def update(self, labels, preds): pred = preds[self.pred.index('rcnn_cls_prob')] if self.e2e: label = preds[self.pred.index('rcnn_label')] else: label = labels[self.label.index('rcnn_label')] last_dim = pred.shape[-1] pred_label = pred.asnumpy().reshape(-1, last_dim).argmax(axis=1).astype('int32') label = label.asnumpy().reshape(-1,).astype('int32') self.sum_metric += np.sum(pred_label.flat == label.flat) self.num_inst += len(pred_label.flat) class RPNLogLossMetric(mx.metric.EvalMetric): def __init__(self): super(RPNLogLossMetric, self).__init__('RPNLogLoss') self.pred, self.label = get_rpn_names() def update(self, labels, preds): pred = preds[self.pred.index('rpn_cls_prob')] label = labels[self.label.index('rpn_label')] # label (b, p) label = label.asnumpy().astype('int32').reshape((-1)) # pred (b, c, p) or (b, c, h, w) --> (b, p, c) --> (b*p, c) pred = pred.asnumpy().reshape((pred.shape[0], pred.shape[1], -1)).transpose((0, 2, 1)) pred = pred.reshape((label.shape[0], -1)) # filter with keep_inds keep_inds = np.where(label != -1)[0] label = label[keep_inds] cls = pred[keep_inds, label] cls += 1e-14 cls_loss = -1 * np.log(cls) cls_loss = np.sum(cls_loss) self.sum_metric += cls_loss self.num_inst += label.shape[0] class RCNNLogLossMetric(mx.metric.EvalMetric): def __init__(self): super(RCNNLogLossMetric, self).__init__('RCNNLogLoss') self.e2e = config.TRAIN.END2END self.pred, self.label = get_rcnn_names() def update(self, labels, preds): pred = preds[self.pred.index('rcnn_cls_prob')] if self.e2e: label = preds[self.pred.index('rcnn_label')] else: label = labels[self.label.index('rcnn_label')] last_dim = pred.shape[-1] pred = pred.asnumpy().reshape(-1, last_dim) label = label.asnumpy().reshape(-1,).astype('int32') cls = pred[np.arange(label.shape[0]), label] cls += 1e-14 cls_loss = -1 * np.log(cls) cls_loss = np.sum(cls_loss) self.sum_metric += cls_loss self.num_inst += label.shape[0] class RPNL1LossMetric(mx.metric.EvalMetric): def __init__(self): super(RPNL1LossMetric, self).__init__('RPNL1Loss') self.pred, self.label = get_rpn_names() def update(self, labels, preds): bbox_loss = preds[self.pred.index('rpn_bbox_loss')].asnumpy() bbox_weight = labels[self.label.index('rpn_bbox_weight')].asnumpy() # calculate num_inst (average on those fg anchors) num_inst = np.sum(bbox_weight > 0) / 4 self.sum_metric += np.sum(bbox_loss) self.num_inst += num_inst class RCNNL1LossMetric(mx.metric.EvalMetric): def __init__(self): super(RCNNL1LossMetric, self).__init__('RCNNL1Loss') self.e2e = config.TRAIN.END2END self.pred, self.label = get_rcnn_names() def update(self, labels, preds): bbox_loss = preds[self.pred.index('rcnn_bbox_loss')].asnumpy() if self.e2e: label = preds[self.pred.index('rcnn_label')].asnumpy() else: label = labels[self.label.index('rcnn_label')].asnumpy() # calculate num_inst keep_inds = np.where(label != 0)[0] num_inst = len(keep_inds) self.sum_metric += np.sum(bbox_loss) self.num_inst += num_inst
apache-2.0
elainenaomi/sciwonc-dataflow-examples
dissertation2017/Experiment 2/instances/10_0_wikiflow_1sh_1s_annot/computeusergroup_0/ComputeUserGroup_0.py
6
3237
#!/usr/bin/env python from sciwonc.dataflow.DataStoreClient import DataStoreClient import ConfigDB_UserGroup_0 import re import json # connector and config client = DataStoreClient("mongodb", ConfigDB_UserGroup_0) # according to config data = client.getData() # return an array of docs (like a csv reader) output = [] contributors = [] if(data): # processing while True: doc = data.next() if doc is None: break; print doc if doc["_id"]: contributor_username = doc["_id"] contributors.append(contributor_username) output.append({"contributor_username": contributor_username}) if output: clientOutput = DataStoreClient("mongodb", ConfigDB_UserGroup_0) clientOutput.saveData(output) MAX_GROUPS = 10000 total_groups = min(MAX_GROUPS,len(output)) total_nodes = ConfigDB_UserGroup_0.TOTAL_NODES template_filename = ConfigDB_UserGroup_0.TEMPLATE_NAME total_groups_per_node = total_groups // total_nodes remain_groups = total_groups % total_nodes print "\n" print "MAX : ", MAX_GROUPS print "output size: ", len(output) print "groups: ",total_groups print "nodes: ",total_nodes print "groups per node: ", total_groups_per_node print "remain groups: ",remain_groups print "\n" initial = 0 for iterator_group in range(0, total_nodes): additional_groups = 1 if remain_groups > 0 else 0 remain_groups -= 1 # save the total of groups in a array # split according to the total of nodes # generate the file f = """HOST = "wfSciwoncWiki:enw1989@172.31.29.101:27001,172.31.29.102:27001,172.31.29.103:27001,172.31.29.104:27001,172.31.29.105:27001,172.31.29.106:27001,172.31.29.107:27001,172.31.29.108:27001,172.31.29.109:27001/?authSource=admin" PORT = "" USER = "" PASSWORD = "" DATABASE = "wiki" READ_PREFERENCE = "primary" COLLECTION_INPUT = "sessions" COLLECTION_OUTPUT = "user_sessions" PREFIX_COLUMN = "w_" ATTRIBUTES = ["timestamp", "contributor_username"] SORT = ["timestamp"] OPERATION_TYPE = "GROUP_BY_COLUMN" COLUMN = "contributor_username" VALUE = """ print "\n Iterating" print initial size_group = total_groups_per_node + additional_groups print initial+size_group groups = [ json.dumps(group) for group in contributors[initial: (initial+size_group)] ] initial += size_group # str_groups = str(groups).replace("'\"", "\"").replace("\"'", "\"") str_groups = str(groups) str_groups = re.sub(r'(?<!\\)\'"', r'"', str_groups) str_groups = re.sub(r'"\'', r'"', str_groups) str_groups = re.sub(r'\\\\"',r'\\"',str_groups) str_groups = re.sub(r'\\\'',r"'",str_groups) str_groups = re.sub(r'\\"(?=,)', r'\\\\"', str_groups) str_groups = re.sub(r'(?<=\[)"', r'u"', str_groups) str_groups = re.sub(r'", "', r'", u"', str_groups) str_groups = re.sub(r'\\\\u(?!ser)', r'\\u', str_groups) str_groups = re.sub(r'(?!\w)\\\\\\\\(?=\w")', r'\\\\', str_groups) f += str_groups f +=""" INPUT_FILE = "session" OUTPUT_FILE = "user_""" f += str(iterator_group) + '"' filename = template_filename.replace(".py","_"+str(iterator_group)+".py") with open(filename, 'w') as writer: writer.write(f)
gpl-3.0
danidee10/Votr
api/api.py
1
3600
from os import getenv from models import db, Users, Polls, Topics, Options, UserPolls from flask import Blueprint, request, jsonify, session from datetime import datetime from config import SQLALCHEMY_DATABASE_URI if getenv('APP_MODE') == 'PRODUCTION': from production_settings import SQLALCHEMY_DATABASE_URI api = Blueprint('api', 'api', url_prefix='/api') @api.route('/polls', methods=['GET', 'POST']) # retrieves/adds polls from/to the database def api_polls(): if request.method == 'POST': # get the poll and save it in the database poll = request.get_json() # simple validation to check if all values are properly set for key, value in poll.items(): if not value: return jsonify({'message': 'value for {} is empty'.format(key)}) title = poll['title'] options_query = lambda option: Options.query.filter(Options.name.like(option)) options = [Polls(option=Options(name=option)) if options_query(option).count() == 0 else Polls(option=options_query(option).first()) for option in poll['options'] ] eta = datetime.utcfromtimestamp(poll['close_date']) new_topic = Topics(title=title, options=options, close_date=eta) db.session.add(new_topic) db.session.commit() # run the task from tasks import close_poll close_poll.apply_async((new_topic.id, SQLALCHEMY_DATABASE_URI), eta=eta) return jsonify({'message': 'Poll was created succesfully'}) else: # it's a GET request, return dict representations of the API polls = Topics.query.filter_by(status=True).join(Polls).order_by(Topics.id.desc()).all() all_polls = {'Polls': [poll.to_json() for poll in polls]} return jsonify(all_polls) @api.route('/polls/options') def api_polls_options(): all_options = [option.to_json() for option in Options.query.all()] return jsonify(all_options) @api.route('/poll/vote', methods=['PATCH']) def api_poll_vote(): poll = request.get_json() poll_title, option = (poll['poll_title'], poll['option']) join_tables = Polls.query.join(Topics).join(Options) # Get topic and username from the database topic = Topics.query.filter_by(title=poll_title, status=True).first() user = Users.query.filter_by(username=session['user']).first() # if poll was closed in the background before user voted if not topic: return jsonify({'message': 'Sorry! this poll has been closed'}) # filter options option = join_tables.filter(Topics.title.like(poll_title), Topics.status == True).filter(Options.name.like(option)).first() # check if the user has voted on this poll poll_count = UserPolls.query.filter_by(topic_id=topic.id).filter_by(user_id=user.id).count() if poll_count > 0: return jsonify({'message': 'Sorry! multiple votes are not allowed'}) if option: # record user and poll user_poll = UserPolls(topic_id=topic.id, user_id=user.id) db.session.add(user_poll) # increment vote_count by 1 if the option was found option.vote_count += 1 db.session.commit() return jsonify({'message': 'Thank you for voting'}) return jsonify({'message': 'option or poll was not found please try again'}) @api.route('/poll/<poll_name>') def api_poll(poll_name): poll = Topics.query.filter(Topics.title.like(poll_name)).first() return jsonify({'Polls': [poll.to_json()]}) if poll else jsonify({'message': 'poll not found'})
gpl-3.0