repo_name
stringlengths
5
100
path
stringlengths
4
375
copies
stringclasses
991 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
AloneRoad/Inforlearn
console/app/pygments/filters/__init__.py
20
9503
# -*- coding: utf-8 -*- """ pygments.filters ~~~~~~~~~~~~~~~~ Module containing filter lookup functions and default filters. :copyright: 2006-2007 by Armin Ronacher, Georg Brandl. :license: BSD, see LICENSE for more details. """ try: set except NameError: from sets import Set as set import re from pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \ string_to_tokentype from pygments.filter import Filter from pygments.util import get_list_opt, get_int_opt, get_bool_opt, get_choice_opt, \ ClassNotFound, OptionError from pygments.plugin import find_plugin_filters def find_filter_class(filtername): """ Lookup a filter by name. Return None if not found. """ if filtername in FILTERS: return FILTERS[filtername] for name, cls in find_plugin_filters(): if name == filtername: return cls return None def get_filter_by_name(filtername, **options): """ Return an instantiated filter. Options are passed to the filter initializer if wanted. Raise a ClassNotFound if not found. """ cls = find_filter_class(filtername) if cls: return cls(**options) else: raise ClassNotFound('filter %r not found' % filtername) def get_all_filters(): """ Return a generator of all filter names. """ for name in FILTERS: yield name for name, _ in find_plugin_filters(): yield name def _replace_special(ttype, value, regex, specialttype, replacefunc=lambda x: x): last = 0 for match in regex.finditer(value): start, end = match.start(), match.end() if start != last: yield ttype, value[last:start] yield specialttype, replacefunc(value[start:end]) last = end if last != len(value): yield ttype, value[last:] class CodeTagFilter(Filter): """ Highlight special code tags in comments and docstrings. Options accepted: `codetags` : list of strings A list of strings that are flagged as code tags. The default is to highlight ``XXX``, ``TODO``, ``BUG`` and ``NOTE``. """ def __init__(self, **options): Filter.__init__(self, **options) tags = get_list_opt(options, 'codetags', ['XXX', 'TODO', 'BUG', 'NOTE']) self.tag_re = re.compile(r'(%s)' % '|'.join([ re.escape(tag) for tag in tags if tag ])) def filter(self, lexer, stream): regex = self.tag_re for ttype, value in stream: if ttype in String.Doc or \ ttype in Comment and \ ttype not in Comment.Preproc: for sttype, svalue in _replace_special(ttype, value, regex, Comment.Special): yield sttype, svalue else: yield ttype, value class KeywordCaseFilter(Filter): """ Convert keywords to lowercase or uppercase or capitalize them, which means first letter uppercase, rest lowercase. This can be useful e.g. if you highlight Pascal code and want to adapt the code to your styleguide. Options accepted: `case` : string The casing to convert keywords to. Must be one of ``'lower'``, ``'upper'`` or ``'capitalize'``. The default is ``'lower'``. """ def __init__(self, **options): Filter.__init__(self, **options) case = get_choice_opt(options, 'case', ['lower', 'upper', 'capitalize'], 'lower') self.convert = getattr(unicode, case) def filter(self, lexer, stream): for ttype, value in stream: if ttype in Keyword: yield ttype, self.convert(value) else: yield ttype, value class NameHighlightFilter(Filter): """ Highlight a normal Name token with a different token type. Example:: filter = NameHighlightFilter( names=['foo', 'bar', 'baz'], tokentype=Name.Function, ) This would highlight the names "foo", "bar" and "baz" as functions. `Name.Function` is the default token type. Options accepted: `names` : list of strings A list of names that should be given the different token type. There is no default. `tokentype` : TokenType or string A token type or a string containing a token type name that is used for highlighting the strings in `names`. The default is `Name.Function`. """ def __init__(self, **options): Filter.__init__(self, **options) self.names = set(get_list_opt(options, 'names', [])) tokentype = options.get('tokentype') if tokentype: self.tokentype = string_to_tokentype(tokentype) else: self.tokentype = Name.Function def filter(self, lexer, stream): for ttype, value in stream: if ttype is Name and value in self.names: yield self.tokentype, value else: yield ttype, value class ErrorToken(Exception): pass class RaiseOnErrorTokenFilter(Filter): """ Raise an exception when the lexer generates an error token. Options accepted: `excclass` : Exception class The exception class to raise. The default is `pygments.filters.ErrorToken`. *New in Pygments 0.8.* """ def __init__(self, **options): Filter.__init__(self, **options) self.exception = options.get('excclass', ErrorToken) try: # issubclass() will raise TypeError if first argument is not a class if not issubclass(self.exception, Exception): raise TypeError except TypeError: raise OptionError('excclass option is not an exception class') def filter(self, lexer, stream): for ttype, value in stream: if ttype is Error: raise self.exception(value) yield ttype, value class VisibleWhitespaceFilter(Filter): """ Convert tabs, newlines and/or spaces to visible characters. Options accepted: `spaces` : string or bool If this is a one-character string, spaces will be replaces by this string. If it is another true value, spaces will be replaced by ``·`` (unicode MIDDLE DOT). If it is a false value, spaces will not be replaced. The default is ``False``. `tabs` : string or bool The same as for `spaces`, but the default replacement character is ``»`` (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value is ``False``. Note: this will not work if the `tabsize` option for the lexer is nonzero, as tabs will already have been expanded then. `tabsize` : int If tabs are to be replaced by this filter (see the `tabs` option), this is the total number of characters that a tab should be expanded to. The default is ``8``. `newlines` : string or bool The same as for `spaces`, but the default replacement character is ``¶`` (unicode PILCROW SIGN). The default value is ``False``. `wstokentype` : bool If true, give whitespace the special `Whitespace` token type. This allows styling the visible whitespace differently (e.g. greyed out), but it can disrupt background colors. The default is ``True``. *New in Pygments 0.8.* """ def __init__(self, **options): Filter.__init__(self, **options) for name, default in {'spaces': u'·', 'tabs': u'»', 'newlines': u'¶'}.items(): opt = options.get(name, False) if isinstance(opt, basestring) and len(opt) == 1: setattr(self, name, opt) else: setattr(self, name, (opt and default or '')) tabsize = get_int_opt(options, 'tabsize', 8) if self.tabs: self.tabs += ' '*(tabsize-1) if self.newlines: self.newlines += '\n' self.wstt = get_bool_opt(options, 'wstokentype', True) def filter(self, lexer, stream): if self.wstt: spaces = self.spaces or ' ' tabs = self.tabs or '\t' newlines = self.newlines or '\n' regex = re.compile(r'\s') def replacefunc(wschar): if wschar == ' ': return spaces elif wschar == '\t': return tabs elif wschar == '\n': return newlines return wschar for ttype, value in stream: for sttype, svalue in _replace_special(ttype, value, regex, Whitespace, replacefunc): yield sttype, svalue else: spaces, tabs, newlines = self.spaces, self.tabs, self.newlines # simpler processing for ttype, value in stream: if spaces: value = value.replace(' ', spaces) if tabs: value = value.replace('\t', tabs) if newlines: value = value.replace('\n', newlines) yield ttype, value FILTERS = { 'codetagify': CodeTagFilter, 'keywordcase': KeywordCaseFilter, 'highlight': NameHighlightFilter, 'raiseonerror': RaiseOnErrorTokenFilter, 'whitespace': VisibleWhitespaceFilter, }
apache-2.0
csparpa/robograph
robograph/sample_graphs/drawing.py
1
1240
from robograph.datamodel.base import graph from robograph.datamodel.nodes import plotter from robograph.datamodel.nodes.lib import value, printer, buffers, maths def plot(): v1 = value.Value(value=[9, -3, 8.7], name='v1') v2 = value.Value(value=[86, -0.43], name='v2') s = maths.Sum(name='sum') m = maths.Product(name='product') b = buffers.Buffer(name='buffer') p = printer.ConsolePrinter(name='printer') g = graph.Graph('sum_and_product', [v1, v2, s, m, p, b]) g.connect(p, b, 'message') g.connect(b, s, 'sum of v1') g.connect(b, m, 'product of v2') g.connect(s, v1, 'argument') g.connect(m, v2, 'argument') plotter.show_plot(g) def plot_to_file(outputfile): v1 = value.Value(value=[9, -3, 8.7], name='v1') v2 = value.Value(value=[86, -0.43], name='v2') s = maths.Sum(name='sum') m = maths.Product(name='product') b = buffers.Buffer(name='buffer') p = printer.ConsolePrinter(name='printer') g = graph.Graph('sum_and_product', [v1, v2, s, m, p, b]) g.connect(p, b, 'message') g.connect(b, s, 'sum of v1') g.connect(b, m, 'product of v2') g.connect(s, v1, 'argument') g.connect(m, v2, 'argument') plotter.save_plot(outputfile)
apache-2.0
Zhongqilong/mykbengineer
kbe/src/lib/python/Lib/concurrent/futures/_base.py
88
19638
# Copyright 2009 Brian Quinlan. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. __author__ = 'Brian Quinlan (brian@sweetapp.com)' import collections import logging import threading import time FIRST_COMPLETED = 'FIRST_COMPLETED' FIRST_EXCEPTION = 'FIRST_EXCEPTION' ALL_COMPLETED = 'ALL_COMPLETED' _AS_COMPLETED = '_AS_COMPLETED' # Possible future states (for internal use by the futures package). PENDING = 'PENDING' RUNNING = 'RUNNING' # The future was cancelled by the user... CANCELLED = 'CANCELLED' # ...and _Waiter.add_cancelled() was called by a worker. CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED' FINISHED = 'FINISHED' _FUTURE_STATES = [ PENDING, RUNNING, CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED ] _STATE_TO_DESCRIPTION_MAP = { PENDING: "pending", RUNNING: "running", CANCELLED: "cancelled", CANCELLED_AND_NOTIFIED: "cancelled", FINISHED: "finished" } # Logger for internal use by the futures package. LOGGER = logging.getLogger("concurrent.futures") class Error(Exception): """Base class for all future-related exceptions.""" pass class CancelledError(Error): """The Future was cancelled.""" pass class TimeoutError(Error): """The operation exceeded the given deadline.""" pass class _Waiter(object): """Provides the event that wait() and as_completed() block on.""" def __init__(self): self.event = threading.Event() self.finished_futures = [] def add_result(self, future): self.finished_futures.append(future) def add_exception(self, future): self.finished_futures.append(future) def add_cancelled(self, future): self.finished_futures.append(future) class _AsCompletedWaiter(_Waiter): """Used by as_completed().""" def __init__(self): super(_AsCompletedWaiter, self).__init__() self.lock = threading.Lock() def add_result(self, future): with self.lock: super(_AsCompletedWaiter, self).add_result(future) self.event.set() def add_exception(self, future): with self.lock: super(_AsCompletedWaiter, self).add_exception(future) self.event.set() def add_cancelled(self, future): with self.lock: super(_AsCompletedWaiter, self).add_cancelled(future) self.event.set() class _FirstCompletedWaiter(_Waiter): """Used by wait(return_when=FIRST_COMPLETED).""" def add_result(self, future): super().add_result(future) self.event.set() def add_exception(self, future): super().add_exception(future) self.event.set() def add_cancelled(self, future): super().add_cancelled(future) self.event.set() class _AllCompletedWaiter(_Waiter): """Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED).""" def __init__(self, num_pending_calls, stop_on_exception): self.num_pending_calls = num_pending_calls self.stop_on_exception = stop_on_exception self.lock = threading.Lock() super().__init__() def _decrement_pending_calls(self): with self.lock: self.num_pending_calls -= 1 if not self.num_pending_calls: self.event.set() def add_result(self, future): super().add_result(future) self._decrement_pending_calls() def add_exception(self, future): super().add_exception(future) if self.stop_on_exception: self.event.set() else: self._decrement_pending_calls() def add_cancelled(self, future): super().add_cancelled(future) self._decrement_pending_calls() class _AcquireFutures(object): """A context manager that does an ordered acquire of Future conditions.""" def __init__(self, futures): self.futures = sorted(futures, key=id) def __enter__(self): for future in self.futures: future._condition.acquire() def __exit__(self, *args): for future in self.futures: future._condition.release() def _create_and_install_waiters(fs, return_when): if return_when == _AS_COMPLETED: waiter = _AsCompletedWaiter() elif return_when == FIRST_COMPLETED: waiter = _FirstCompletedWaiter() else: pending_count = sum( f._state not in [CANCELLED_AND_NOTIFIED, FINISHED] for f in fs) if return_when == FIRST_EXCEPTION: waiter = _AllCompletedWaiter(pending_count, stop_on_exception=True) elif return_when == ALL_COMPLETED: waiter = _AllCompletedWaiter(pending_count, stop_on_exception=False) else: raise ValueError("Invalid return condition: %r" % return_when) for f in fs: f._waiters.append(waiter) return waiter def as_completed(fs, timeout=None): """An iterator over the given futures that yields each as it completes. Args: fs: The sequence of Futures (possibly created by different Executors) to iterate over. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. Returns: An iterator that yields the given Futures as they complete (finished or cancelled). If any given Futures are duplicated, they will be returned once. Raises: TimeoutError: If the entire result iterator could not be generated before the given timeout. """ if timeout is not None: end_time = timeout + time.time() fs = set(fs) with _AcquireFutures(fs): finished = set( f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]) pending = fs - finished waiter = _create_and_install_waiters(fs, _AS_COMPLETED) try: yield from finished while pending: if timeout is None: wait_timeout = None else: wait_timeout = end_time - time.time() if wait_timeout < 0: raise TimeoutError( '%d (of %d) futures unfinished' % ( len(pending), len(fs))) waiter.event.wait(wait_timeout) with waiter.lock: finished = waiter.finished_futures waiter.finished_futures = [] waiter.event.clear() for future in finished: yield future pending.remove(future) finally: for f in fs: with f._condition: f._waiters.remove(waiter) DoneAndNotDoneFutures = collections.namedtuple( 'DoneAndNotDoneFutures', 'done not_done') def wait(fs, timeout=None, return_when=ALL_COMPLETED): """Wait for the futures in the given sequence to complete. Args: fs: The sequence of Futures (possibly created by different Executors) to wait upon. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. return_when: Indicates when this function should return. The options are: FIRST_COMPLETED - Return when any future finishes or is cancelled. FIRST_EXCEPTION - Return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to ALL_COMPLETED. ALL_COMPLETED - Return when all futures finish or are cancelled. Returns: A named 2-tuple of sets. The first set, named 'done', contains the futures that completed (is finished or cancelled) before the wait completed. The second set, named 'not_done', contains uncompleted futures. """ with _AcquireFutures(fs): done = set(f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]) not_done = set(fs) - done if (return_when == FIRST_COMPLETED) and done: return DoneAndNotDoneFutures(done, not_done) elif (return_when == FIRST_EXCEPTION) and done: if any(f for f in done if not f.cancelled() and f.exception() is not None): return DoneAndNotDoneFutures(done, not_done) if len(done) == len(fs): return DoneAndNotDoneFutures(done, not_done) waiter = _create_and_install_waiters(fs, return_when) waiter.event.wait(timeout) for f in fs: with f._condition: f._waiters.remove(waiter) done.update(waiter.finished_futures) return DoneAndNotDoneFutures(done, set(fs) - done) class Future(object): """Represents the result of an asynchronous computation.""" def __init__(self): """Initializes the future. Should not be called by clients.""" self._condition = threading.Condition() self._state = PENDING self._result = None self._exception = None self._waiters = [] self._done_callbacks = [] def _invoke_callbacks(self): for callback in self._done_callbacks: try: callback(self) except Exception: LOGGER.exception('exception calling callback for %r', self) def __repr__(self): with self._condition: if self._state == FINISHED: if self._exception: return '<Future at %s state=%s raised %s>' % ( hex(id(self)), _STATE_TO_DESCRIPTION_MAP[self._state], self._exception.__class__.__name__) else: return '<Future at %s state=%s returned %s>' % ( hex(id(self)), _STATE_TO_DESCRIPTION_MAP[self._state], self._result.__class__.__name__) return '<Future at %s state=%s>' % ( hex(id(self)), _STATE_TO_DESCRIPTION_MAP[self._state]) def cancel(self): """Cancel the future if possible. Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed. """ with self._condition: if self._state in [RUNNING, FINISHED]: return False if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: return True self._state = CANCELLED self._condition.notify_all() self._invoke_callbacks() return True def cancelled(self): """Return True if the future was cancelled.""" with self._condition: return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED] def running(self): """Return True if the future is currently executing.""" with self._condition: return self._state == RUNNING def done(self): """Return True of the future was cancelled or finished executing.""" with self._condition: return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED] def __get_result(self): if self._exception: raise self._exception else: return self._result def add_done_callback(self, fn): """Attaches a callable that will be called when the future finishes. Args: fn: A callable that will be called with this future as its only argument when the future completes or is cancelled. The callable will always be called by a thread in the same process in which it was added. If the future has already completed or been cancelled then the callable will be called immediately. These callables are called in the order that they were added. """ with self._condition: if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]: self._done_callbacks.append(fn) return fn(self) def result(self, timeout=None): """Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. Returns: The result of the call that the future represents. Raises: CancelledError: If the future was cancelled. TimeoutError: If the future didn't finish executing before the given timeout. Exception: If the call raised then that exception will be raised. """ with self._condition: if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self.__get_result() self._condition.wait(timeout) if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self.__get_result() else: raise TimeoutError() def exception(self, timeout=None): """Return the exception raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn't done. If None, then there is no limit on the wait time. Returns: The exception raised by the call that the future represents or None if the call completed without raising. Raises: CancelledError: If the future was cancelled. TimeoutError: If the future didn't finish executing before the given timeout. """ with self._condition: if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self._exception self._condition.wait(timeout) if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self._exception else: raise TimeoutError() # The following methods should only be used by Executors and in tests. def set_running_or_notify_cancel(self): """Mark the future as running or process any cancel notifications. Should only be used by Executor implementations and unit tests. If the future has been cancelled (cancel() was called and returned True) then any threads waiting on the future completing (though calls to as_completed() or wait()) are notified and False is returned. If the future was not cancelled then it is put in the running state (future calls to running() will return True) and True is returned. This method should be called by Executor implementations before executing the work associated with this future. If this method returns False then the work should not be executed. Returns: False if the Future was cancelled, True otherwise. Raises: RuntimeError: if this method was already called or if set_result() or set_exception() was called. """ with self._condition: if self._state == CANCELLED: self._state = CANCELLED_AND_NOTIFIED for waiter in self._waiters: waiter.add_cancelled(self) # self._condition.notify_all() is not necessary because # self.cancel() triggers a notification. return False elif self._state == PENDING: self._state = RUNNING return True else: LOGGER.critical('Future %s in unexpected state: %s', id(self), self._state) raise RuntimeError('Future in unexpected state') def set_result(self, result): """Sets the return value of work associated with the future. Should only be used by Executor implementations and unit tests. """ with self._condition: self._result = result self._state = FINISHED for waiter in self._waiters: waiter.add_result(self) self._condition.notify_all() self._invoke_callbacks() def set_exception(self, exception): """Sets the result of the future as being the given exception. Should only be used by Executor implementations and unit tests. """ with self._condition: self._exception = exception self._state = FINISHED for waiter in self._waiters: waiter.add_exception(self) self._condition.notify_all() self._invoke_callbacks() class Executor(object): """This is an abstract base class for concrete asynchronous executors.""" def submit(self, fn, *args, **kwargs): """Submits a callable to be executed with the given arguments. Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. Returns: A Future representing the given call. """ raise NotImplementedError() def map(self, fn, *iterables, timeout=None): """Returns a iterator equivalent to map(fn, iter). Args: fn: A callable that will take as many arguments as there are passed iterables. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. Returns: An iterator equivalent to: map(func, *iterables) but the calls may be evaluated out-of-order. Raises: TimeoutError: If the entire result iterator could not be generated before the given timeout. Exception: If fn(*args) raises for any values. """ if timeout is not None: end_time = timeout + time.time() fs = [self.submit(fn, *args) for args in zip(*iterables)] # Yield must be hidden in closure so that the futures are submitted # before the first iterator value is required. def result_iterator(): try: for future in fs: if timeout is None: yield future.result() else: yield future.result(end_time - time.time()) finally: for future in fs: future.cancel() return result_iterator() def shutdown(self, wait=True): """Clean-up the resources associated with the Executor. It is safe to call this method several times. Otherwise, no other methods can be called after this one. Args: wait: If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed. """ pass def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.shutdown(wait=True) return False
lgpl-3.0
Ted1993/Flasky
venv/lib/python2.7/site-packages/setuptools/tests/__init__.py
147
11160
"""Tests for the 'setuptools' package""" import sys import os import distutils.core import distutils.cmd from distutils.errors import DistutilsOptionError, DistutilsPlatformError from distutils.errors import DistutilsSetupError from distutils.core import Extension from distutils.version import LooseVersion from setuptools.compat import func_code import pytest import setuptools.dist import setuptools.depends as dep from setuptools import Feature from setuptools.depends import Require def makeSetup(**args): """Return distribution from 'setup(**args)', without executing commands""" distutils.core._setup_stop_after = "commandline" # Don't let system command line leak into tests! args.setdefault('script_args',['install']) try: return setuptools.setup(**args) finally: distutils.core._setup_stop_after = None needs_bytecode = pytest.mark.skipif( not hasattr(dep, 'get_module_constant'), reason="bytecode support not available", ) class TestDepends: def testExtractConst(self): if not hasattr(dep, 'extract_constant'): # skip on non-bytecode platforms return def f1(): global x, y, z x = "test" y = z fc = func_code(f1) # unrecognized name assert dep.extract_constant(fc,'q', -1) is None # constant assigned dep.extract_constant(fc,'x', -1) == "test" # expression assigned dep.extract_constant(fc,'y', -1) == -1 # recognized name, not assigned dep.extract_constant(fc,'z', -1) is None def testFindModule(self): with pytest.raises(ImportError): dep.find_module('no-such.-thing') with pytest.raises(ImportError): dep.find_module('setuptools.non-existent') f,p,i = dep.find_module('setuptools.tests') f.close() @needs_bytecode def testModuleExtract(self): from email import __version__ assert dep.get_module_constant('email','__version__') == __version__ assert dep.get_module_constant('sys','version') == sys.version assert dep.get_module_constant('setuptools.tests','__doc__') == __doc__ @needs_bytecode def testRequire(self): req = Require('Email','1.0.3','email') assert req.name == 'Email' assert req.module == 'email' assert req.requested_version == '1.0.3' assert req.attribute == '__version__' assert req.full_name() == 'Email-1.0.3' from email import __version__ assert req.get_version() == __version__ assert req.version_ok('1.0.9') assert not req.version_ok('0.9.1') assert not req.version_ok('unknown') assert req.is_present() assert req.is_current() req = Require('Email 3000','03000','email',format=LooseVersion) assert req.is_present() assert not req.is_current() assert not req.version_ok('unknown') req = Require('Do-what-I-mean','1.0','d-w-i-m') assert not req.is_present() assert not req.is_current() req = Require('Tests', None, 'tests', homepage="http://example.com") assert req.format is None assert req.attribute is None assert req.requested_version is None assert req.full_name() == 'Tests' assert req.homepage == 'http://example.com' paths = [os.path.dirname(p) for p in __path__] assert req.is_present(paths) assert req.is_current(paths) class TestDistro: def setup_method(self, method): self.e1 = Extension('bar.ext',['bar.c']) self.e2 = Extension('c.y', ['y.c']) self.dist = makeSetup( packages=['a', 'a.b', 'a.b.c', 'b', 'c'], py_modules=['b.d','x'], ext_modules = (self.e1, self.e2), package_dir = {}, ) def testDistroType(self): assert isinstance(self.dist,setuptools.dist.Distribution) def testExcludePackage(self): self.dist.exclude_package('a') assert self.dist.packages == ['b','c'] self.dist.exclude_package('b') assert self.dist.packages == ['c'] assert self.dist.py_modules == ['x'] assert self.dist.ext_modules == [self.e1, self.e2] self.dist.exclude_package('c') assert self.dist.packages == [] assert self.dist.py_modules == ['x'] assert self.dist.ext_modules == [self.e1] # test removals from unspecified options makeSetup().exclude_package('x') def testIncludeExclude(self): # remove an extension self.dist.exclude(ext_modules=[self.e1]) assert self.dist.ext_modules == [self.e2] # add it back in self.dist.include(ext_modules=[self.e1]) assert self.dist.ext_modules == [self.e2, self.e1] # should not add duplicate self.dist.include(ext_modules=[self.e1]) assert self.dist.ext_modules == [self.e2, self.e1] def testExcludePackages(self): self.dist.exclude(packages=['c','b','a']) assert self.dist.packages == [] assert self.dist.py_modules == ['x'] assert self.dist.ext_modules == [self.e1] def testEmpty(self): dist = makeSetup() dist.include(packages=['a'], py_modules=['b'], ext_modules=[self.e2]) dist = makeSetup() dist.exclude(packages=['a'], py_modules=['b'], ext_modules=[self.e2]) def testContents(self): assert self.dist.has_contents_for('a') self.dist.exclude_package('a') assert not self.dist.has_contents_for('a') assert self.dist.has_contents_for('b') self.dist.exclude_package('b') assert not self.dist.has_contents_for('b') assert self.dist.has_contents_for('c') self.dist.exclude_package('c') assert not self.dist.has_contents_for('c') def testInvalidIncludeExclude(self): with pytest.raises(DistutilsSetupError): self.dist.include(nonexistent_option='x') with pytest.raises(DistutilsSetupError): self.dist.exclude(nonexistent_option='x') with pytest.raises(DistutilsSetupError): self.dist.include(packages={'x':'y'}) with pytest.raises(DistutilsSetupError): self.dist.exclude(packages={'x':'y'}) with pytest.raises(DistutilsSetupError): self.dist.include(ext_modules={'x':'y'}) with pytest.raises(DistutilsSetupError): self.dist.exclude(ext_modules={'x':'y'}) with pytest.raises(DistutilsSetupError): self.dist.include(package_dir=['q']) with pytest.raises(DistutilsSetupError): self.dist.exclude(package_dir=['q']) class TestFeatures: def setup_method(self, method): self.req = Require('Distutils','1.0.3','distutils') self.dist = makeSetup( features={ 'foo': Feature("foo",standard=True,require_features=['baz',self.req]), 'bar': Feature("bar", standard=True, packages=['pkg.bar'], py_modules=['bar_et'], remove=['bar.ext'], ), 'baz': Feature( "baz", optional=False, packages=['pkg.baz'], scripts = ['scripts/baz_it'], libraries=[('libfoo','foo/foofoo.c')] ), 'dwim': Feature("DWIM", available=False, remove='bazish'), }, script_args=['--without-bar', 'install'], packages = ['pkg.bar', 'pkg.foo'], py_modules = ['bar_et', 'bazish'], ext_modules = [Extension('bar.ext',['bar.c'])] ) def testDefaults(self): assert not Feature( "test",standard=True,remove='x',available=False ).include_by_default() assert Feature("test",standard=True,remove='x').include_by_default() # Feature must have either kwargs, removes, or require_features with pytest.raises(DistutilsSetupError): Feature("test") def testAvailability(self): with pytest.raises(DistutilsPlatformError): self.dist.features['dwim'].include_in(self.dist) def testFeatureOptions(self): dist = self.dist assert ( ('with-dwim',None,'include DWIM') in dist.feature_options ) assert ( ('without-dwim',None,'exclude DWIM (default)') in dist.feature_options ) assert ( ('with-bar',None,'include bar (default)') in dist.feature_options ) assert ( ('without-bar',None,'exclude bar') in dist.feature_options ) assert dist.feature_negopt['without-foo'] == 'with-foo' assert dist.feature_negopt['without-bar'] == 'with-bar' assert dist.feature_negopt['without-dwim'] == 'with-dwim' assert (not 'without-baz' in dist.feature_negopt) def testUseFeatures(self): dist = self.dist assert dist.with_foo == 1 assert dist.with_bar == 0 assert dist.with_baz == 1 assert (not 'bar_et' in dist.py_modules) assert (not 'pkg.bar' in dist.packages) assert ('pkg.baz' in dist.packages) assert ('scripts/baz_it' in dist.scripts) assert (('libfoo','foo/foofoo.c') in dist.libraries) assert dist.ext_modules == [] assert dist.require_features == [self.req] # If we ask for bar, it should fail because we explicitly disabled # it on the command line with pytest.raises(DistutilsOptionError): dist.include_feature('bar') def testFeatureWithInvalidRemove(self): with pytest.raises(SystemExit): makeSetup(features={'x':Feature('x', remove='y')}) class TestCommandTests: def testTestIsCommand(self): test_cmd = makeSetup().get_command_obj('test') assert (isinstance(test_cmd, distutils.cmd.Command)) def testLongOptSuiteWNoDefault(self): ts1 = makeSetup(script_args=['test','--test-suite=foo.tests.suite']) ts1 = ts1.get_command_obj('test') ts1.ensure_finalized() assert ts1.test_suite == 'foo.tests.suite' def testDefaultSuite(self): ts2 = makeSetup(test_suite='bar.tests.suite').get_command_obj('test') ts2.ensure_finalized() assert ts2.test_suite == 'bar.tests.suite' def testDefaultWModuleOnCmdLine(self): ts3 = makeSetup( test_suite='bar.tests', script_args=['test','-m','foo.tests'] ).get_command_obj('test') ts3.ensure_finalized() assert ts3.test_module == 'foo.tests' assert ts3.test_suite == 'foo.tests.test_suite' def testConflictingOptions(self): ts4 = makeSetup( script_args=['test','-m','bar.tests', '-s','foo.tests.suite'] ).get_command_obj('test') with pytest.raises(DistutilsOptionError): ts4.ensure_finalized() def testNoSuite(self): ts5 = makeSetup().get_command_obj('test') ts5.ensure_finalized() assert ts5.test_suite == None
mit
zahodi/ansible
test/units/parsing/vault/test_vault.py
52
16031
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import six import binascii import io import os from binascii import hexlify from nose.plugins.skip import SkipTest from ansible.compat.tests import unittest from ansible import errors from ansible.parsing.vault import VaultLib from ansible.parsing import vault from ansible.module_utils._text import to_bytes, to_text # Counter import fails for 2.0.1, requires >= 2.6.1 from pip try: from Crypto.Util import Counter HAS_COUNTER = True except ImportError: HAS_COUNTER = False # KDF import fails for 2.0.1, requires >= 2.6.1 from pip try: from Crypto.Protocol.KDF import PBKDF2 HAS_PBKDF2 = True except ImportError: HAS_PBKDF2 = False # AES IMPORTS try: from Crypto.Cipher import AES as AES HAS_AES = True except ImportError: HAS_AES = False class TestVaultIsEncrypted(unittest.TestCase): def test_bytes_not_encrypted(self): b_data = b"foobar" self.assertFalse(vault.is_encrypted(b_data)) def test_bytes_encrypted(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible") self.assertTrue(vault.is_encrypted(b_data)) def test_text_not_encrypted(self): b_data = to_text(b"foobar") self.assertFalse(vault.is_encrypted(b_data)) def test_text_encrypted(self): b_data = to_text(b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible")) self.assertTrue(vault.is_encrypted(b_data)) def test_invalid_text_not_ascii(self): data = u"$ANSIBLE_VAULT;9.9;TEST\n%s"% u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " self.assertFalse(vault.is_encrypted(data)) def test_invalid_bytes_not_ascii(self): data = u"$ANSIBLE_VAULT;9.9;TEST\n%s"% u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " b_data = to_bytes(data, encoding='utf-8') self.assertFalse(vault.is_encrypted(b_data)) class TestVaultIsEncryptedFile(unittest.TestCase): def test_binary_file_handle_not_encrypted(self): b_data = b"foobar" b_data_fo = io.BytesIO(b_data) self.assertFalse(vault.is_encrypted_file(b_data_fo)) def test_text_file_handle_not_encrypted(self): data = u"foobar" data_fo = io.StringIO(data) self.assertFalse(vault.is_encrypted_file(data_fo)) def test_binary_file_handle_encrypted(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible") b_data_fo = io.BytesIO(b_data) self.assertTrue(vault.is_encrypted_file(b_data_fo)) def test_text_file_handle_encrypted(self): data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % to_text(hexlify(b"ansible")) data_fo = io.StringIO(data) self.assertTrue(vault.is_encrypted_file(data_fo)) def test_binary_file_handle_invalid(self): data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " b_data = to_bytes(data) b_data_fo = io.BytesIO(b_data) self.assertFalse(vault.is_encrypted_file(b_data_fo)) def test_text_file_handle_invalid(self): data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " data_fo = io.StringIO(data) self.assertFalse(vault.is_encrypted_file(data_fo)) def test_file_already_read_from_finds_header(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") b_data_fo = io.BytesIO(b_data) b_data_fo.read(42) # Arbitrary number self.assertTrue(vault.is_encrypted_file(b_data_fo)) def test_file_already_read_from_saves_file_pos(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") b_data_fo = io.BytesIO(b_data) b_data_fo.read(69) # Arbitrary number vault.is_encrypted_file(b_data_fo) self.assertEqual(b_data_fo.tell(), 69) def test_file_with_offset(self): b_data = b"JUNK$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") b_data_fo = io.BytesIO(b_data) self.assertTrue(vault.is_encrypted_file(b_data_fo, start_pos=4)) def test_file_with_count(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") vault_length = len(b_data) b_data = b_data + u'ァ ア'.encode('utf-8') b_data_fo = io.BytesIO(b_data) self.assertTrue(vault.is_encrypted_file(b_data_fo, count=vault_length)) def test_file_with_offset_and_count(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") vault_length = len(b_data) b_data = b'JUNK' + b_data + u'ァ ア'.encode('utf-8') b_data_fo = io.BytesIO(b_data) self.assertTrue(vault.is_encrypted_file(b_data_fo, start_pos=4, count=vault_length)) class TestVaultCipherAes256(unittest.TestCase): def setUp(self): self.vault_cipher = vault.VaultAES256() def test(self): self.assertIsInstance(self.vault_cipher, vault.VaultAES256) # TODO: tag these as slow tests def test_create_key(self): b_password = b'hunter42' b_salt = os.urandom(32) b_key = self.vault_cipher._create_key(b_password, b_salt, keylength=32, ivlength=16) self.assertIsInstance(b_key, six.binary_type) def test_create_key_known(self): b_password = b'hunter42' # A fixed salt b_salt = b'q' * 32 # q is the most random letter. b_key = self.vault_cipher._create_key(b_password, b_salt, keylength=32, ivlength=16) self.assertIsInstance(b_key, six.binary_type) # verify we get the same answer # we could potentially run a few iterations of this and time it to see if it's roughly constant time # and or that it exceeds some minimal time, but that would likely cause unreliable fails, esp in CI b_key_2 = self.vault_cipher._create_key(b_password, b_salt, keylength=32, ivlength=16) self.assertIsInstance(b_key, six.binary_type) self.assertEqual(b_key, b_key_2) def test_is_equal_is_equal(self): self.assertTrue(self.vault_cipher._is_equal(b'abcdefghijklmnopqrstuvwxyz', b'abcdefghijklmnopqrstuvwxyz')) def test_is_equal_unequal_length(self): self.assertFalse(self.vault_cipher._is_equal(b'abcdefghijklmnopqrstuvwxyz', b'abcdefghijklmnopqrstuvwx and sometimes y')) def test_is_equal_not_equal(self): self.assertFalse(self.vault_cipher._is_equal(b'abcdefghijklmnopqrstuvwxyz', b'AbcdefghijKlmnopQrstuvwxZ')) def test_is_equal_empty(self): self.assertTrue(self.vault_cipher._is_equal(b'', b'')) def test_is_equal_non_ascii_equal(self): utf8_data = to_bytes(u'私はガラスを食べられます。それは私を傷つけません。') self.assertTrue(self.vault_cipher._is_equal(utf8_data, utf8_data)) def test_is_equal_non_ascii_unequal(self): utf8_data = to_bytes(u'私はガラスを食べられます。それは私を傷つけません。') utf8_data2 = to_bytes(u'Pot să mănânc sticlă și ea nu mă rănește.') # Test for the len optimization path self.assertFalse(self.vault_cipher._is_equal(utf8_data, utf8_data2)) # Test for the slower, char by char comparison path self.assertFalse(self.vault_cipher._is_equal(utf8_data, utf8_data[:-1] + b'P')) def test_is_equal_non_bytes(self): """ Anything not a byte string should raise a TypeError """ self.assertRaises(TypeError, self.vault_cipher._is_equal, u"One fish", b"two fish") self.assertRaises(TypeError, self.vault_cipher._is_equal, b"One fish", u"two fish") self.assertRaises(TypeError, self.vault_cipher._is_equal, 1, b"red fish") self.assertRaises(TypeError, self.vault_cipher._is_equal, b"blue fish", 2) class TestVaultLib(unittest.TestCase): def setUp(self): self.v = VaultLib('test-vault-password') def test_encrypt(self): plaintext = u'Some text to encrypt in a café' b_vaulttext = self.v.encrypt(plaintext) self.assertIsInstance(b_vaulttext, six.binary_type) b_header = b'$ANSIBLE_VAULT;1.1;AES256\n' self.assertEqual(b_vaulttext[:len(b_header)], b_header) def test_encrypt_bytes(self): plaintext = to_bytes(u'Some text to encrypt in a café') b_vaulttext = self.v.encrypt(plaintext) self.assertIsInstance(b_vaulttext, six.binary_type) b_header = b'$ANSIBLE_VAULT;1.1;AES256\n' self.assertEqual(b_vaulttext[:len(b_header)], b_header) def test_is_encrypted(self): self.assertFalse(self.v.is_encrypted(b"foobar"), msg="encryption check on plaintext yielded false positive") b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible") self.assertTrue(self.v.is_encrypted(b_data), msg="encryption check on headered text failed") def test_format_output(self): self.v.cipher_name = "TEST" b_ciphertext = b"ansible" b_vaulttext = self.v._format_output(b_ciphertext) b_lines = b_vaulttext.split(b'\n') self.assertGreater(len(b_lines), 1, msg="failed to properly add header") b_header = b_lines[0] self.assertTrue(b_header.endswith(b';TEST'), msg="header does not end with cipher name") b_header_parts = b_header.split(b';') self.assertEqual(len(b_header_parts), 3, msg="header has the wrong number of parts") self.assertEqual(b_header_parts[0], b'$ANSIBLE_VAULT', msg="header does not start with $ANSIBLE_VAULT") self.assertEqual(b_header_parts[1], self.v.b_version, msg="header version is incorrect") self.assertEqual(b_header_parts[2], b'TEST', msg="header does not end with cipher name") def test_split_header(self): b_vaulttext = b"$ANSIBLE_VAULT;9.9;TEST\nansible" b_ciphertext = self.v._split_header(b_vaulttext) b_lines = b_ciphertext.split(b'\n') self.assertEqual(b_lines[0], b"ansible", msg="Payload was not properly split from the header") self.assertEqual(self.v.cipher_name, u'TEST', msg="cipher name was not properly set") self.assertEqual(self.v.b_version, b"9.9", msg="version was not properly set") def test_encrypt_decrypt_aes(self): if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2: raise SkipTest self.v.cipher_name = u'AES' self.v.b_password = b'ansible' # AES encryption code has been removed, so this is old output for # AES-encrypted 'foobar' with password 'ansible'. b_vaulttext = b'''$ANSIBLE_VAULT;1.1;AES 53616c7465645f5fc107ce1ef4d7b455e038a13b053225776458052f8f8f332d554809d3f150bfa3 fe3db930508b65e0ff5947e4386b79af8ab094017629590ef6ba486814cf70f8e4ab0ed0c7d2587e 786a5a15efeb787e1958cbdd480d076c ''' b_plaintext = self.v.decrypt(b_vaulttext) self.assertEqual(b_plaintext, b"foobar", msg="decryption failed") def test_encrypt_decrypt_aes256(self): if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2: raise SkipTest self.v.cipher_name = u'AES256' plaintext = u"foobar" b_vaulttext = self.v.encrypt(plaintext) b_plaintext = self.v.decrypt(b_vaulttext) self.assertNotEqual(b_vaulttext, b"foobar", msg="encryption failed") self.assertEqual(b_plaintext, b"foobar", msg="decryption failed") def test_encrypt_decrypt_aes256_existing_vault(self): if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2: raise SkipTest self.v.cipher_name = u'AES256' b_orig_plaintext = b"Setec Astronomy" vaulttext = u'''$ANSIBLE_VAULT;1.1;AES256 33363965326261303234626463623963633531343539616138316433353830356566396130353436 3562643163366231316662386565383735653432386435610a306664636137376132643732393835 63383038383730306639353234326630666539346233376330303938323639306661313032396437 6233623062366136310a633866373936313238333730653739323461656662303864663666653563 3138''' b_plaintext = self.v.decrypt(vaulttext) self.assertEqual(b_plaintext, b_plaintext, msg="decryption failed") b_vaulttext = to_bytes(vaulttext, encoding='ascii', errors='strict') b_plaintext = self.v.decrypt(b_vaulttext) self.assertEqual(b_plaintext, b_orig_plaintext, msg="decryption failed") def test_encrypt_decrypt_aes256_bad_hmac(self): # FIXME This test isn't working quite yet. raise SkipTest if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2: raise SkipTest self.v.cipher_name = 'AES256' # plaintext = "Setec Astronomy" enc_data = '''$ANSIBLE_VAULT;1.1;AES256 33363965326261303234626463623963633531343539616138316433353830356566396130353436 3562643163366231316662386565383735653432386435610a306664636137376132643732393835 63383038383730306639353234326630666539346233376330303938323639306661313032396437 6233623062366136310a633866373936313238333730653739323461656662303864663666653563 3138''' b_data = to_bytes(enc_data, errors='strict', encoding='utf-8') b_data = self.v._split_header(b_data) foo = binascii.unhexlify(b_data) lines = foo.splitlines() # line 0 is salt, line 1 is hmac, line 2+ is ciphertext b_salt = lines[0] b_hmac = lines[1] b_ciphertext_data = b'\n'.join(lines[2:]) b_ciphertext = binascii.unhexlify(b_ciphertext_data) # b_orig_ciphertext = b_ciphertext[:] # now muck with the text # b_munged_ciphertext = b_ciphertext[:10] + b'\x00' + b_ciphertext[11:] # b_munged_ciphertext = b_ciphertext # assert b_orig_ciphertext != b_munged_ciphertext b_ciphertext_data = binascii.hexlify(b_ciphertext) b_payload = b'\n'.join([b_salt, b_hmac, b_ciphertext_data]) # reformat b_invalid_ciphertext = self.v._format_output(b_payload) # assert we throw an error self.v.decrypt(b_invalid_ciphertext) def test_encrypt_encrypted(self): if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2: raise SkipTest self.v.cipher_name = u'AES' b_vaulttext = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible") vaulttext = to_text(b_vaulttext, errors='strict') self.assertRaises(errors.AnsibleError, self.v.encrypt, b_vaulttext) self.assertRaises(errors.AnsibleError, self.v.encrypt, vaulttext) def test_decrypt_decrypted(self): if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2: raise SkipTest plaintext = u"ansible" self.assertRaises(errors.AnsibleError, self.v.decrypt, plaintext) b_plaintext = b"ansible" self.assertRaises(errors.AnsibleError, self.v.decrypt, b_plaintext) def test_cipher_not_set(self): # not setting the cipher should default to AES256 if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2: raise SkipTest plaintext = u"ansible" self.v.encrypt(plaintext) self.assertEquals(self.v.cipher_name, "AES256")
gpl-3.0
globber-torpes/formula1
tests/test_formula1.py
1
8805
from unittest import TestCase from src.Piloto import Piloto from src.Escuderia import Escuderia from src.CampeonatoMundial import CampeonatoMundial from src.Circuito import Circuito from src.GranPremio import GranPremio from src.Formula1 import Formula1 from mockito import * __author__ = 'MAMISHO' class TestFormula1(TestCase): """ Test Formula 1 Este test prueba las funcionalidades del modulo de Formula1. Para realizar las mismas, es necesario tener una bateria de atributos definidos para todas las pruebas. :param p1: Piloto de prueba :param p2: Piloto de prueba :param p3: Piloto de prueba :param p4: Piloto de prueba :param p5: Piloto de prueba :param p6: Piloto de prueba :param e1: Escuderia de prueba :param e2: Escuderia de prueba :param e3: Escuderia de prueba """ p1 = Piloto("AAA", "Piloto A") p2 = Piloto("BBB", "Piloto B") p3 = Piloto("CCC", "Piloto C") p4 = Piloto("DDD", "Piloto D") p5 = Piloto("EEE", "Piloto E") p6 = Piloto("FFF", "Piloto F") e1 = Escuderia("Escuderia 1") e2 = Escuderia("Escuderia 2") e3 = Escuderia("Escuderia 3") e1.agregar_piloto(p1) e1.agregar_piloto(p2) e2.agregar_piloto(p3) e2.agregar_piloto(p4) e3.agregar_piloto(p5) e3.agregar_piloto(p6) def test_crear_campeonato_mundial(self): """ Test Crear un campeonato mundial El test comprueba que formula 1 pueda crear un campeonato mundial de forma correcta, para esto se comparan dos clases CampeonatoMundial, el primero lo creamos de forma manual y el segundo es el que creara el modulo de formula1. Luego comparamos las clases que tienen sus mismo atributos. :param f1: Formula 1 que va a crear el campeonato mundial :param es: Diccionario de escuderias necesario para construir un campeonato mundial :param cm1: Campeonato mundial creado de forma manual :param cm2: Campeonato mundial creado por formula 1 """ print("\ntest_crear_campeonato_mundial") f1 = Formula1() es = {self.e1.nombre: self.e1, self.e2.nombre: self.e2, self.e3.nombre: self.e3} cm1 = CampeonatoMundial(1, es) cm2 = f1.crear_campeonato_mundial(1, es) self.assertEqual(cm1.__class__, cm2.__class__) def test_agregar_campeonato_mundial_1(self): """ Test agregar campeonato mundial a Formula 1 Este test comprueba que un campeonato mundial sea agregado correctamente en la formula 1 cumpliendo con el esquema de datos requerido :param f1: Formula 1 al que se agrega el campeonat mundial :param es: Diccionario de escuderias que se requiere para crear un campeonato mundial :param cm: campeonato mundial que se agrega a la formula 1 """ print ("\ntest_agregar_campeonato_mundial_1") f1 = Formula1() es = {self.e1.nombre: self.e1, self.e2.nombre: self.e2, self.e3.nombre: self.e3} cm = CampeonatoMundial(1, es) self.assertEqual(f1.agregar_campeonato_mundial(cm), True) def test_agregar_campeonato_mundial_2(self): """ Test agregar campeonato mundial repetido Este test comprueba que no pueda se agregado un campeonato mundial que ya existe en la formula 1. La prueba se va a realizar con un solo campeonato mundial en este caso cm. Se invoca dos veces a el metodo agregar_campeonato_mundial con el mismo parametro. :param f1: Formula1 al que se agrega el campeonato mundial :param es: Diccionario de escuderias que se requiere para crear un campeonato mundial :param cm: Campeonato mundial que se agrega a la formula 1 """ print ("\ntest_agregar_campeonato_mundial_2") f1 = Formula1() es = {self.e1.nombre: self.e1, self.e2.nombre: self.e2, self.e3.nombre: self.e3} cm = CampeonatoMundial(1, es) f1.agregar_campeonato_mundial(cm) self.assertEqual(f1.agregar_campeonato_mundial(cm), False) def test_agregar_campeonato_mundial_3(self): """ Test agregar campeonato mundial invalido Este metodo comprueba que el nuevo campeonato mundial sea correcto, es decir que cumpla con los requerimientos de un campeonato mundial. En esta prueba vamos a simular un campeonato mundial, el cual no debe pasar la prueba porque, aunque sea simulado, no es un campeonato mundial. :param f1: Formula1 al que se agrega el campeonato mundial :param cm: mock que simula un campeonato mundial. """ print ("\ntest_agregar_campeonato_mundial_3") f1 = Formula1() cm = mock(CampeonatoMundial) self.assertEqual(f1.agregar_campeonato_mundial(cm), False) def test_eliminar_campeonato_mundial_1(self): """ Test eliminar campeonato mundial existente Este test comprueba que un campeonato mundial existente y que cumple con los requisitos sea eliminado de la formula 1. :param f1: formula 1 de donde se elimina el campeonato mundial :param es: Escuderia de prueba para crear campeonatos mundiales :param cm1: Campeoanto mundial de prueba :param cm2: Campeoanto mundial de prueba :param cm3: Campeoanto mundial de prueba :param cm4: Campeoanto mundial de prueba :param cm5: Campeoanto mundial de prueba """ print("\ntest_eliminar_campeonato_mundial_1") f1 = Formula1() es = {self.e1.nombre: self.e1, self.e2.nombre: self.e2, self.e3.nombre: self.e3} cm1 = CampeonatoMundial(1, es) cm2 = CampeonatoMundial(2, es) cm3 = CampeonatoMundial(3, es) cm4 = CampeonatoMundial(4, es) cm5 = CampeonatoMundial(5, es) f1.agregar_campeonato_mundial(cm1) f1.agregar_campeonato_mundial(cm2) f1.agregar_campeonato_mundial(cm3) f1.agregar_campeonato_mundial(cm4) f1.agregar_campeonato_mundial(cm5) self.assertEqual(f1.eliminar_campeonato_mundial(cm1), True) def test_eliminar_campeonato_mundial_2(self): """ Test eliminar campeonato mundial No existente Este test comprueba que un campeonato mundial debe existir para ser pasado como parametro y ser eliminado de la formula 1 :param f1: formula 1 de donde se elimina el campeonato mundial :param es: Escuderia de prueba para crear campeonatos mundiales :param cm1: Campeoanto mundial No existente en la formula 1 :param cm2: Campeoanto mundial existente en f1 :param cm3: Campeoanto mundial existente en f1 :param cm4: Campeoanto mundial existente en f1 :param cm5: Campeoanto mundial existente en f1 """ print("\ntest_eliminar_campeonato_mundial_2") f1 = Formula1() es = {self.e1.nombre: self.e1, self.e2.nombre: self.e2, self.e3.nombre: self.e3} cm1 = CampeonatoMundial(1, es) cm2 = CampeonatoMundial(2, es) cm3 = CampeonatoMundial(3, es) cm4 = CampeonatoMundial(4, es) cm5 = CampeonatoMundial(5, es) f1.agregar_campeonato_mundial(cm2) f1.agregar_campeonato_mundial(cm3) f1.agregar_campeonato_mundial(cm4) f1.agregar_campeonato_mundial(cm5) self.assertEqual(f1.eliminar_campeonato_mundial(cm1), False) def test_eliminar_campeonato_mundial_3(self): """ Test eliminar campeonato mundial no valido Este test comprueba que el campeonato mundial que va a ser eliminado, sea un campeonato mundial valido. Para este test usaremos un mock de tipo campeonato Mundial y la formula 1 no debe permitir agregarlo porque, aunque sea simulado, no es un objeto propio de CampeonatoMundial :param f1: Formula 1 de donde se va a eliminar el campeonato mundial :param es: Diccionario de escuderias para crear los campeonatos mundiales :param cm1: Campeonato mundial de f1 :param cm2: Campeonato mundial de f1 :param cm3: mock que simula un campeonato mundial """ print("\ntest_eliminar_campeonato_mundial_3") f1 = Formula1() es = {self.e1.nombre: self.e1, self.e2.nombre: self.e2, self.e3.nombre: self.e3} cm1 = CampeonatoMundial(1, es) cm2 = CampeonatoMundial(2, es) cm3 = mock(CampeonatoMundial) f1.agregar_campeonato_mundial(cm1) f1.agregar_campeonato_mundial(cm2) self.assertEqual(f1.eliminar_campeonato_mundial(cm3), False)
mit
40223229/2015cd_midterm2
static/Brython3.1.1-20150328-091302/Lib/datetime.py
628
75044
"""Concrete date/time and related types. See http://www.iana.org/time-zones/repository/tz-link.html for time zone and DST data sources. """ import time as _time import math as _math def _cmp(x, y): return 0 if x == y else 1 if x > y else -1 MINYEAR = 1 MAXYEAR = 9999 _MAXORDINAL = 3652059 # date.max.toordinal() # Utility functions, adapted from Python's Demo/classes/Dates.py, which # also assumes the current Gregorian calendar indefinitely extended in # both directions. Difference: Dates.py calls January 1 of year 0 day # number 1. The code here calls January 1 of year 1 day number 1. This is # to match the definition of the "proleptic Gregorian" calendar in Dershowitz # and Reingold's "Calendrical Calculations", where it's the base calendar # for all computations. See the book for algorithms for converting between # proleptic Gregorian ordinals and many other calendar systems. _DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] _DAYS_BEFORE_MONTH = [None] dbm = 0 for dim in _DAYS_IN_MONTH[1:]: _DAYS_BEFORE_MONTH.append(dbm) dbm += dim del dbm, dim def _is_leap(year): "year -> 1 if leap year, else 0." return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def _days_before_year(year): "year -> number of days before January 1st of year." y = year - 1 return y*365 + y//4 - y//100 + y//400 def _days_in_month(year, month): "year, month -> number of days in that month in that year." assert 1 <= month <= 12, month if month == 2 and _is_leap(year): return 29 return _DAYS_IN_MONTH[month] def _days_before_month(year, month): "year, month -> number of days in year preceding first day of month." assert 1 <= month <= 12, 'month must be in 1..12' return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year)) def _ymd2ord(year, month, day): "year, month, day -> ordinal, considering 01-Jan-0001 as day 1." assert 1 <= month <= 12, 'month must be in 1..12' dim = _days_in_month(year, month) assert 1 <= day <= dim, ('day must be in 1..%d' % dim) return (_days_before_year(year) + _days_before_month(year, month) + day) _DI400Y = _days_before_year(401) # number of days in 400 years _DI100Y = _days_before_year(101) # " " " " 100 " _DI4Y = _days_before_year(5) # " " " " 4 " # A 4-year cycle has an extra leap day over what we'd get from pasting # together 4 single years. assert _DI4Y == 4 * 365 + 1 # Similarly, a 400-year cycle has an extra leap day over what we'd get from # pasting together 4 100-year cycles. assert _DI400Y == 4 * _DI100Y + 1 # OTOH, a 100-year cycle has one fewer leap day than we'd get from # pasting together 25 4-year cycles. assert _DI100Y == 25 * _DI4Y - 1 def _ord2ymd(n): "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1." # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years # repeats exactly every 400 years. The basic strategy is to find the # closest 400-year boundary at or before n, then work with the offset # from that boundary to n. Life is much clearer if we subtract 1 from # n first -- then the values of n at 400-year boundaries are exactly # those divisible by _DI400Y: # # D M Y n n-1 # -- --- ---- ---------- ---------------- # 31 Dec -400 -_DI400Y -_DI400Y -1 # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary # ... # 30 Dec 000 -1 -2 # 31 Dec 000 0 -1 # 1 Jan 001 1 0 400-year boundary # 2 Jan 001 2 1 # 3 Jan 001 3 2 # ... # 31 Dec 400 _DI400Y _DI400Y -1 # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary n -= 1 n400, n = divmod(n, _DI400Y) year = n400 * 400 + 1 # ..., -399, 1, 401, ... # Now n is the (non-negative) offset, in days, from January 1 of year, to # the desired date. Now compute how many 100-year cycles precede n. # Note that it's possible for n100 to equal 4! In that case 4 full # 100-year cycles precede the desired day, which implies the desired # day is December 31 at the end of a 400-year cycle. n100, n = divmod(n, _DI100Y) # Now compute how many 4-year cycles precede it. n4, n = divmod(n, _DI4Y) # And now how many single years. Again n1 can be 4, and again meaning # that the desired day is December 31 at the end of the 4-year cycle. n1, n = divmod(n, 365) year += n100 * 100 + n4 * 4 + n1 if n1 == 4 or n100 == 4: assert n == 0 return year-1, 12, 31 # Now the year is correct, and n is the offset from January 1. We find # the month via an estimate that's either exact or one too large. leapyear = n1 == 3 and (n4 != 24 or n100 == 3) assert leapyear == _is_leap(year) month = (n + 50) >> 5 preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear) if preceding > n: # estimate is too large month -= 1 preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear) n -= preceding assert 0 <= n < _days_in_month(year, month) # Now the year and month are correct, and n is the offset from the # start of that month: we're done! return year, month, n+1 # Month and day names. For localized versions, see the calendar module. _MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] _DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] def _build_struct_time(y, m, d, hh, mm, ss, dstflag): wday = (_ymd2ord(y, m, d) + 6) % 7 dnum = _days_before_month(y, m) + d return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag)) def _format_time(hh, mm, ss, us): # Skip trailing microseconds when us==0. result = "%02d:%02d:%02d" % (hh, mm, ss) if us: result += ".%06d" % us return result # Correctly substitute for %z and %Z escapes in strftime formats. def _wrap_strftime(object, format, timetuple): # Don't call utcoffset() or tzname() unless actually needed. freplace = None # the string to use for %f zreplace = None # the string to use for %z Zreplace = None # the string to use for %Z # Scan format for %z and %Z escapes, replacing as needed. newformat = [] push = newformat.append i, n = 0, len(format) while i < n: ch = format[i] i += 1 if ch == '%': if i < n: ch = format[i] i += 1 if ch == 'f': if freplace is None: freplace = '%06d' % getattr(object, 'microsecond', 0) newformat.append(freplace) elif ch == 'z': if zreplace is None: zreplace = "" if hasattr(object, "utcoffset"): offset = object.utcoffset() if offset is not None: sign = '+' if offset.days < 0: offset = -offset sign = '-' h, m = divmod(offset, timedelta(hours=1)) assert not m % timedelta(minutes=1), "whole minute" m //= timedelta(minutes=1) zreplace = '%c%02d%02d' % (sign, h, m) assert '%' not in zreplace newformat.append(zreplace) elif ch == 'Z': if Zreplace is None: Zreplace = "" if hasattr(object, "tzname"): s = object.tzname() if s is not None: # strftime is going to have at this: escape % Zreplace = s.replace('%', '%%') newformat.append(Zreplace) else: push('%') push(ch) else: push('%') else: push(ch) newformat = "".join(newformat) return _time.strftime(newformat, timetuple) def _call_tzinfo_method(tzinfo, methname, tzinfoarg): if tzinfo is None: return None return getattr(tzinfo, methname)(tzinfoarg) # Just raise TypeError if the arg isn't None or a string. def _check_tzname(name): if name is not None and not isinstance(name, str): raise TypeError("tzinfo.tzname() must return None or string, " "not '%s'" % type(name)) # name is the offset-producing method, "utcoffset" or "dst". # offset is what it returned. # If offset isn't None or timedelta, raises TypeError. # If offset is None, returns None. # Else offset is checked for being in range, and a whole # of minutes. # If it is, its integer value is returned. Else ValueError is raised. def _check_utc_offset(name, offset): assert name in ("utcoffset", "dst") if offset is None: return if not isinstance(offset, timedelta): raise TypeError("tzinfo.%s() must return None " "or timedelta, not '%s'" % (name, type(offset))) if offset % timedelta(minutes=1) or offset.microseconds: raise ValueError("tzinfo.%s() must return a whole number " "of minutes, got %s" % (name, offset)) if not -timedelta(1) < offset < timedelta(1): raise ValueError("%s()=%s, must be must be strictly between" " -timedelta(hours=24) and timedelta(hours=24)" % (name, offset)) def _check_date_fields(year, month, day): if not isinstance(year, int): raise TypeError('int expected') if not MINYEAR <= year <= MAXYEAR: raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year) if not 1 <= month <= 12: raise ValueError('month must be in 1..12', month) dim = _days_in_month(year, month) if not 1 <= day <= dim: raise ValueError('day must be in 1..%d' % dim, day) def _check_time_fields(hour, minute, second, microsecond): if not isinstance(hour, int): raise TypeError('int expected') if not 0 <= hour <= 23: raise ValueError('hour must be in 0..23', hour) if not 0 <= minute <= 59: raise ValueError('minute must be in 0..59', minute) if not 0 <= second <= 59: raise ValueError('second must be in 0..59', second) if not 0 <= microsecond <= 999999: raise ValueError('microsecond must be in 0..999999', microsecond) def _check_tzinfo_arg(tz): if tz is not None and not isinstance(tz, tzinfo): raise TypeError("tzinfo argument must be None or of a tzinfo subclass") def _cmperror(x, y): raise TypeError("can't compare '%s' to '%s'" % ( type(x).__name__, type(y).__name__)) class timedelta: """Represent the difference between two datetime objects. Supported operators: - add, subtract timedelta - unary plus, minus, abs - compare to timedelta - multiply, divide by int In addition, datetime supports subtraction of two datetime objects returning a timedelta, and addition or subtraction of a datetime and a timedelta giving a datetime. Representation: (days, seconds, microseconds). Why? Because I felt like it. """ __slots__ = '_days', '_seconds', '_microseconds' def __new__(cls, days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): # Doing this efficiently and accurately in C is going to be difficult # and error-prone, due to ubiquitous overflow possibilities, and that # C double doesn't have enough bits of precision to represent # microseconds over 10K years faithfully. The code here tries to make # explicit where go-fast assumptions can be relied on, in order to # guide the C implementation; it's way more convoluted than speed- # ignoring auto-overflow-to-long idiomatic Python could be. # XXX Check that all inputs are ints or floats. # Final values, all integer. # s and us fit in 32-bit signed ints; d isn't bounded. d = s = us = 0 # Normalize everything to days, seconds, microseconds. days += weeks*7 seconds += minutes*60 + hours*3600 microseconds += milliseconds*1000 # Get rid of all fractions, and normalize s and us. # Take a deep breath <wink>. if isinstance(days, float): dayfrac, days = _math.modf(days) daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.)) assert daysecondswhole == int(daysecondswhole) # can't overflow s = int(daysecondswhole) assert days == int(days) d = int(days) else: daysecondsfrac = 0.0 d = days assert isinstance(daysecondsfrac, float) assert abs(daysecondsfrac) <= 1.0 assert isinstance(d, int) assert abs(s) <= 24 * 3600 # days isn't referenced again before redefinition if isinstance(seconds, float): secondsfrac, seconds = _math.modf(seconds) assert seconds == int(seconds) seconds = int(seconds) secondsfrac += daysecondsfrac assert abs(secondsfrac) <= 2.0 else: secondsfrac = daysecondsfrac # daysecondsfrac isn't referenced again assert isinstance(secondsfrac, float) assert abs(secondsfrac) <= 2.0 assert isinstance(seconds, int) days, seconds = divmod(seconds, 24*3600) d += days s += int(seconds) # can't overflow assert isinstance(s, int) assert abs(s) <= 2 * 24 * 3600 # seconds isn't referenced again before redefinition usdouble = secondsfrac * 1e6 assert abs(usdouble) < 2.1e6 # exact value not critical # secondsfrac isn't referenced again if isinstance(microseconds, float): microseconds += usdouble microseconds = round(microseconds, 0) seconds, microseconds = divmod(microseconds, 1e6) assert microseconds == int(microseconds) assert seconds == int(seconds) days, seconds = divmod(seconds, 24.*3600.) assert days == int(days) assert seconds == int(seconds) d += int(days) s += int(seconds) # can't overflow assert isinstance(s, int) assert abs(s) <= 3 * 24 * 3600 else: seconds, microseconds = divmod(microseconds, 1000000) days, seconds = divmod(seconds, 24*3600) d += days s += int(seconds) # can't overflow assert isinstance(s, int) assert abs(s) <= 3 * 24 * 3600 microseconds = float(microseconds) microseconds += usdouble microseconds = round(microseconds, 0) assert abs(s) <= 3 * 24 * 3600 assert abs(microseconds) < 3.1e6 # Just a little bit of carrying possible for microseconds and seconds. assert isinstance(microseconds, float) assert int(microseconds) == microseconds us = int(microseconds) seconds, us = divmod(us, 1000000) s += seconds # cant't overflow assert isinstance(s, int) days, s = divmod(s, 24*3600) d += days assert isinstance(d, int) assert isinstance(s, int) and 0 <= s < 24*3600 assert isinstance(us, int) and 0 <= us < 1000000 self = object.__new__(cls) self._days = d self._seconds = s self._microseconds = us if abs(d) > 999999999: raise OverflowError("timedelta # of days is too large: %d" % d) return self def __repr__(self): if self._microseconds: return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__, self._days, self._seconds, self._microseconds) if self._seconds: return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__, self._days, self._seconds) return "%s(%d)" % ('datetime.' + self.__class__.__name__, self._days) def __str__(self): mm, ss = divmod(self._seconds, 60) hh, mm = divmod(mm, 60) s = "%d:%02d:%02d" % (hh, mm, ss) if self._days: def plural(n): return n, abs(n) != 1 and "s" or "" s = ("%d day%s, " % plural(self._days)) + s if self._microseconds: s = s + ".%06d" % self._microseconds return s def total_seconds(self): """Total seconds in the duration.""" return ((self.days * 86400 + self.seconds)*10**6 + self.microseconds) / 10**6 # Read-only field accessors @property def days(self): """days""" return self._days @property def seconds(self): """seconds""" return self._seconds @property def microseconds(self): """microseconds""" return self._microseconds def __add__(self, other): if isinstance(other, timedelta): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(self._days + other._days, self._seconds + other._seconds, self._microseconds + other._microseconds) return NotImplemented __radd__ = __add__ def __sub__(self, other): if isinstance(other, timedelta): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(self._days - other._days, self._seconds - other._seconds, self._microseconds - other._microseconds) return NotImplemented def __rsub__(self, other): if isinstance(other, timedelta): return -self + other return NotImplemented def __neg__(self): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(-self._days, -self._seconds, -self._microseconds) def __pos__(self): return self def __abs__(self): if self._days < 0: return -self else: return self def __mul__(self, other): if isinstance(other, int): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(self._days * other, self._seconds * other, self._microseconds * other) if isinstance(other, float): a, b = other.as_integer_ratio() return self * a / b return NotImplemented __rmul__ = __mul__ def _to_microseconds(self): return ((self._days * (24*3600) + self._seconds) * 1000000 + self._microseconds) def __floordiv__(self, other): if not isinstance(other, (int, timedelta)): return NotImplemented usec = self._to_microseconds() if isinstance(other, timedelta): return usec // other._to_microseconds() if isinstance(other, int): return timedelta(0, 0, usec // other) def __truediv__(self, other): if not isinstance(other, (int, float, timedelta)): return NotImplemented usec = self._to_microseconds() if isinstance(other, timedelta): return usec / other._to_microseconds() if isinstance(other, int): return timedelta(0, 0, usec / other) if isinstance(other, float): a, b = other.as_integer_ratio() return timedelta(0, 0, b * usec / a) def __mod__(self, other): if isinstance(other, timedelta): r = self._to_microseconds() % other._to_microseconds() return timedelta(0, 0, r) return NotImplemented def __divmod__(self, other): if isinstance(other, timedelta): q, r = divmod(self._to_microseconds(), other._to_microseconds()) return q, timedelta(0, 0, r) return NotImplemented # Comparisons of timedelta objects with other. def __eq__(self, other): if isinstance(other, timedelta): return self._cmp(other) == 0 else: return False def __ne__(self, other): if isinstance(other, timedelta): return self._cmp(other) != 0 else: return True def __le__(self, other): if isinstance(other, timedelta): return self._cmp(other) <= 0 else: _cmperror(self, other) def __lt__(self, other): if isinstance(other, timedelta): return self._cmp(other) < 0 else: _cmperror(self, other) def __ge__(self, other): if isinstance(other, timedelta): return self._cmp(other) >= 0 else: _cmperror(self, other) def __gt__(self, other): if isinstance(other, timedelta): return self._cmp(other) > 0 else: _cmperror(self, other) def _cmp(self, other): assert isinstance(other, timedelta) return _cmp(self._getstate(), other._getstate()) def __hash__(self): return hash(self._getstate()) def __bool__(self): return (self._days != 0 or self._seconds != 0 or self._microseconds != 0) # Pickle support. def _getstate(self): return (self._days, self._seconds, self._microseconds) def __reduce__(self): return (self.__class__, self._getstate()) timedelta.min = timedelta(-999999999) timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999) timedelta.resolution = timedelta(microseconds=1) class date: """Concrete date type. Constructors: __new__() fromtimestamp() today() fromordinal() Operators: __repr__, __str__ __cmp__, __hash__ __add__, __radd__, __sub__ (add/radd only with timedelta arg) Methods: timetuple() toordinal() weekday() isoweekday(), isocalendar(), isoformat() ctime() strftime() Properties (readonly): year, month, day """ __slots__ = '_year', '_month', '_day' def __new__(cls, year, month=None, day=None): """Constructor. Arguments: year, month, day (required, base 1) """ if (isinstance(year, bytes) and len(year) == 4 and 1 <= year[2] <= 12 and month is None): # Month is sane # Pickle support self = object.__new__(cls) self.__setstate(year) return self _check_date_fields(year, month, day) self = object.__new__(cls) self._year = year self._month = month self._day = day return self # Additional constructors @classmethod def fromtimestamp(cls, t): "Construct a date from a POSIX timestamp (like time.time())." y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t) return cls(y, m, d) @classmethod def today(cls): "Construct a date from time.time()." t = _time.time() return cls.fromtimestamp(t) @classmethod def fromordinal(cls, n): """Contruct a date from a proleptic Gregorian ordinal. January 1 of year 1 is day 1. Only the year, month and day are non-zero in the result. """ y, m, d = _ord2ymd(n) return cls(y, m, d) # Conversions to string def __repr__(self): """Convert to formal string, for repr(). >>> dt = datetime(2010, 1, 1) >>> repr(dt) 'datetime.datetime(2010, 1, 1, 0, 0)' >>> dt = datetime(2010, 1, 1, tzinfo=timezone.utc) >>> repr(dt) 'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)' """ return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__, self._year, self._month, self._day) # XXX These shouldn't depend on time.localtime(), because that # clips the usable dates to [1970 .. 2038). At least ctime() is # easily done without using strftime() -- that's better too because # strftime("%c", ...) is locale specific. def ctime(self): "Return ctime() style string." weekday = self.toordinal() % 7 or 7 return "%s %s %2d 00:00:00 %04d" % ( _DAYNAMES[weekday], _MONTHNAMES[self._month], self._day, self._year) def strftime(self, fmt): "Format using strftime()." return _wrap_strftime(self, fmt, self.timetuple()) def __format__(self, fmt): if len(fmt) != 0: return self.strftime(fmt) return str(self) def isoformat(self): """Return the date formatted according to ISO. This is 'YYYY-MM-DD'. References: - http://www.w3.org/TR/NOTE-datetime - http://www.cl.cam.ac.uk/~mgk25/iso-time.html """ return "%04d-%02d-%02d" % (self._year, self._month, self._day) __str__ = isoformat # Read-only field accessors @property def year(self): """year (1-9999)""" return self._year @property def month(self): """month (1-12)""" return self._month @property def day(self): """day (1-31)""" return self._day # Standard conversions, __cmp__, __hash__ (and helpers) def timetuple(self): "Return local time tuple compatible with time.localtime()." return _build_struct_time(self._year, self._month, self._day, 0, 0, 0, -1) def toordinal(self): """Return proleptic Gregorian ordinal for the year, month and day. January 1 of year 1 is day 1. Only the year, month and day values contribute to the result. """ return _ymd2ord(self._year, self._month, self._day) def replace(self, year=None, month=None, day=None): """Return a new date with new values for the specified fields.""" if year is None: year = self._year if month is None: month = self._month if day is None: day = self._day _check_date_fields(year, month, day) return date(year, month, day) # Comparisons of date objects with other. def __eq__(self, other): if isinstance(other, date): return self._cmp(other) == 0 return NotImplemented def __ne__(self, other): if isinstance(other, date): return self._cmp(other) != 0 return NotImplemented def __le__(self, other): if isinstance(other, date): return self._cmp(other) <= 0 return NotImplemented def __lt__(self, other): if isinstance(other, date): return self._cmp(other) < 0 return NotImplemented def __ge__(self, other): if isinstance(other, date): return self._cmp(other) >= 0 return NotImplemented def __gt__(self, other): if isinstance(other, date): return self._cmp(other) > 0 return NotImplemented def _cmp(self, other): assert isinstance(other, date) y, m, d = self._year, self._month, self._day y2, m2, d2 = other._year, other._month, other._day return _cmp((y, m, d), (y2, m2, d2)) def __hash__(self): "Hash." return hash(self._getstate()) # Computations def __add__(self, other): "Add a date to a timedelta." if isinstance(other, timedelta): o = self.toordinal() + other.days if 0 < o <= _MAXORDINAL: return date.fromordinal(o) raise OverflowError("result out of range") return NotImplemented __radd__ = __add__ def __sub__(self, other): """Subtract two dates, or a date and a timedelta.""" if isinstance(other, timedelta): return self + timedelta(-other.days) if isinstance(other, date): days1 = self.toordinal() days2 = other.toordinal() return timedelta(days1 - days2) return NotImplemented def weekday(self): "Return day of the week, where Monday == 0 ... Sunday == 6." return (self.toordinal() + 6) % 7 # Day-of-the-week and week-of-the-year, according to ISO def isoweekday(self): "Return day of the week, where Monday == 1 ... Sunday == 7." # 1-Jan-0001 is a Monday return self.toordinal() % 7 or 7 def isocalendar(self): """Return a 3-tuple containing ISO year, week number, and weekday. The first ISO week of the year is the (Mon-Sun) week containing the year's first Thursday; everything else derives from that. The first week is 1; Monday is 1 ... Sunday is 7. ISO calendar algorithm taken from http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm """ year = self._year week1monday = _isoweek1monday(year) today = _ymd2ord(self._year, self._month, self._day) # Internally, week and day have origin 0 week, day = divmod(today - week1monday, 7) if week < 0: year -= 1 week1monday = _isoweek1monday(year) week, day = divmod(today - week1monday, 7) elif week >= 52: if today >= _isoweek1monday(year+1): year += 1 week = 0 return year, week+1, day+1 # Pickle support. def _getstate(self): yhi, ylo = divmod(self._year, 256) return bytes([yhi, ylo, self._month, self._day]), def __setstate(self, string): if len(string) != 4 or not (1 <= string[2] <= 12): raise TypeError("not enough arguments") yhi, ylo, self._month, self._day = string self._year = yhi * 256 + ylo def __reduce__(self): return (self.__class__, self._getstate()) _date_class = date # so functions w/ args named "date" can get at the class date.min = date(1, 1, 1) date.max = date(9999, 12, 31) date.resolution = timedelta(days=1) class tzinfo: """Abstract base class for time zone info classes. Subclasses must override the name(), utcoffset() and dst() methods. """ __slots__ = () def tzname(self, dt): "datetime -> string name of time zone." raise NotImplementedError("tzinfo subclass must override tzname()") def utcoffset(self, dt): "datetime -> minutes east of UTC (negative for west of UTC)" raise NotImplementedError("tzinfo subclass must override utcoffset()") def dst(self, dt): """datetime -> DST offset in minutes east of UTC. Return 0 if DST not in effect. utcoffset() must include the DST offset. """ raise NotImplementedError("tzinfo subclass must override dst()") def fromutc(self, dt): "datetime in UTC -> datetime in local time." if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") dtoff = dt.utcoffset() if dtoff is None: raise ValueError("fromutc() requires a non-None utcoffset() " "result") # See the long comment block at the end of this file for an # explanation of this algorithm. dtdst = dt.dst() if dtdst is None: raise ValueError("fromutc() requires a non-None dst() result") delta = dtoff - dtdst if delta: dt += delta dtdst = dt.dst() if dtdst is None: raise ValueError("fromutc(): dt.dst gave inconsistent " "results; cannot convert") return dt + dtdst # Pickle support. def __reduce__(self): getinitargs = getattr(self, "__getinitargs__", None) if getinitargs: args = getinitargs() else: args = () getstate = getattr(self, "__getstate__", None) if getstate: state = getstate() else: state = getattr(self, "__dict__", None) or None if state is None: return (self.__class__, args) else: return (self.__class__, args, state) _tzinfo_class = tzinfo class time: """Time with time zone. Constructors: __new__() Operators: __repr__, __str__ __cmp__, __hash__ Methods: strftime() isoformat() utcoffset() tzname() dst() Properties (readonly): hour, minute, second, microsecond, tzinfo """ def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): """Constructor. Arguments: hour, minute (required) second, microsecond (default to zero) tzinfo (default to None) """ self = object.__new__(cls) if isinstance(hour, bytes) and len(hour) == 6: # Pickle support self.__setstate(hour, minute or None) return self _check_tzinfo_arg(tzinfo) _check_time_fields(hour, minute, second, microsecond) self._hour = hour self._minute = minute self._second = second self._microsecond = microsecond self._tzinfo = tzinfo return self # Read-only field accessors @property def hour(self): """hour (0-23)""" return self._hour @property def minute(self): """minute (0-59)""" return self._minute @property def second(self): """second (0-59)""" return self._second @property def microsecond(self): """microsecond (0-999999)""" return self._microsecond @property def tzinfo(self): """timezone info object""" return self._tzinfo # Standard conversions, __hash__ (and helpers) # Comparisons of time objects with other. def __eq__(self, other): if isinstance(other, time): return self._cmp(other, allow_mixed=True) == 0 else: return False def __ne__(self, other): if isinstance(other, time): return self._cmp(other, allow_mixed=True) != 0 else: return True def __le__(self, other): if isinstance(other, time): return self._cmp(other) <= 0 else: _cmperror(self, other) def __lt__(self, other): if isinstance(other, time): return self._cmp(other) < 0 else: _cmperror(self, other) def __ge__(self, other): if isinstance(other, time): return self._cmp(other) >= 0 else: _cmperror(self, other) def __gt__(self, other): if isinstance(other, time): return self._cmp(other) > 0 else: _cmperror(self, other) def _cmp(self, other, allow_mixed=False): assert isinstance(other, time) mytz = self._tzinfo ottz = other._tzinfo myoff = otoff = None if mytz is ottz: base_compare = True else: myoff = self.utcoffset() otoff = other.utcoffset() base_compare = myoff == otoff if base_compare: return _cmp((self._hour, self._minute, self._second, self._microsecond), (other._hour, other._minute, other._second, other._microsecond)) if myoff is None or otoff is None: if allow_mixed: return 2 # arbitrary non-zero value else: raise TypeError("cannot compare naive and aware times") myhhmm = self._hour * 60 + self._minute - myoff//timedelta(minutes=1) othhmm = other._hour * 60 + other._minute - otoff//timedelta(minutes=1) return _cmp((myhhmm, self._second, self._microsecond), (othhmm, other._second, other._microsecond)) def __hash__(self): """Hash.""" tzoff = self.utcoffset() if not tzoff: # zero or None return hash(self._getstate()[0]) h, m = divmod(timedelta(hours=self.hour, minutes=self.minute) - tzoff, timedelta(hours=1)) assert not m % timedelta(minutes=1), "whole minute" m //= timedelta(minutes=1) if 0 <= h < 24: return hash(time(h, m, self.second, self.microsecond)) return hash((h, m, self.second, self.microsecond)) # Conversion to string def _tzstr(self, sep=":"): """Return formatted timezone offset (+xx:xx) or None.""" off = self.utcoffset() if off is not None: if off.days < 0: sign = "-" off = -off else: sign = "+" hh, mm = divmod(off, timedelta(hours=1)) assert not mm % timedelta(minutes=1), "whole minute" mm //= timedelta(minutes=1) assert 0 <= hh < 24 off = "%s%02d%s%02d" % (sign, hh, sep, mm) return off def __repr__(self): """Convert to formal string, for repr().""" if self._microsecond != 0: s = ", %d, %d" % (self._second, self._microsecond) elif self._second != 0: s = ", %d" % self._second else: s = "" s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__, self._hour, self._minute, s) if self._tzinfo is not None: assert s[-1:] == ")" s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")" return s def isoformat(self): """Return the time formatted according to ISO. This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if self.microsecond == 0. """ s = _format_time(self._hour, self._minute, self._second, self._microsecond) tz = self._tzstr() if tz: s += tz return s __str__ = isoformat def strftime(self, fmt): """Format using strftime(). The date part of the timestamp passed to underlying strftime should not be used. """ # The year must be >= 1000 else Python's strftime implementation # can raise a bogus exception. timetuple = (1900, 1, 1, self._hour, self._minute, self._second, 0, 1, -1) return _wrap_strftime(self, fmt, timetuple) def __format__(self, fmt): if len(fmt) != 0: return self.strftime(fmt) return str(self) # Timezone functions def utcoffset(self): """Return the timezone offset in minutes east of UTC (negative west of UTC).""" if self._tzinfo is None: return None offset = self._tzinfo.utcoffset(None) _check_utc_offset("utcoffset", offset) return offset def tzname(self): """Return the timezone name. Note that the name is 100% informational -- there's no requirement that it mean anything in particular. For example, "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies. """ if self._tzinfo is None: return None name = self._tzinfo.tzname(None) _check_tzname(name) return name def dst(self): """Return 0 if DST is not in effect, or the DST offset (in minutes eastward) if DST is in effect. This is purely informational; the DST offset has already been added to the UTC offset returned by utcoffset() if applicable, so there's no need to consult dst() unless you're interested in displaying the DST info. """ if self._tzinfo is None: return None offset = self._tzinfo.dst(None) _check_utc_offset("dst", offset) return offset def replace(self, hour=None, minute=None, second=None, microsecond=None, tzinfo=True): """Return a new time with new values for the specified fields.""" if hour is None: hour = self.hour if minute is None: minute = self.minute if second is None: second = self.second if microsecond is None: microsecond = self.microsecond if tzinfo is True: tzinfo = self.tzinfo _check_time_fields(hour, minute, second, microsecond) _check_tzinfo_arg(tzinfo) return time(hour, minute, second, microsecond, tzinfo) def __bool__(self): if self.second or self.microsecond: return True offset = self.utcoffset() or timedelta(0) return timedelta(hours=self.hour, minutes=self.minute) != offset # Pickle support. def _getstate(self): us2, us3 = divmod(self._microsecond, 256) us1, us2 = divmod(us2, 256) basestate = bytes([self._hour, self._minute, self._second, us1, us2, us3]) if self._tzinfo is None: return (basestate,) else: return (basestate, self._tzinfo) def __setstate(self, string, tzinfo): if len(string) != 6 or string[0] >= 24: raise TypeError("an integer is required") (self._hour, self._minute, self._second, us1, us2, us3) = string self._microsecond = (((us1 << 8) | us2) << 8) | us3 if tzinfo is None or isinstance(tzinfo, _tzinfo_class): self._tzinfo = tzinfo else: raise TypeError("bad tzinfo state arg %r" % tzinfo) def __reduce__(self): return (time, self._getstate()) _time_class = time # so functions w/ args named "time" can get at the class time.min = time(0, 0, 0) time.max = time(23, 59, 59, 999999) time.resolution = timedelta(microseconds=1) class datetime(date): """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints. """ __slots__ = date.__slots__ + ( '_hour', '_minute', '_second', '_microsecond', '_tzinfo') def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): if isinstance(year, bytes) and len(year) == 10: # Pickle support self = date.__new__(cls, year[:4]) self.__setstate(year, month) return self _check_tzinfo_arg(tzinfo) _check_time_fields(hour, minute, second, microsecond) self = date.__new__(cls, year, month, day) self._hour = hour self._minute = minute self._second = second self._microsecond = microsecond self._tzinfo = tzinfo return self # Read-only field accessors @property def hour(self): """hour (0-23)""" return self._hour @property def minute(self): """minute (0-59)""" return self._minute @property def second(self): """second (0-59)""" return self._second @property def microsecond(self): """microsecond (0-999999)""" return self._microsecond @property def tzinfo(self): """timezone info object""" return self._tzinfo @classmethod def fromtimestamp(cls, t, tz=None): """Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well. """ _check_tzinfo_arg(tz) converter = _time.localtime if tz is None else _time.gmtime t, frac = divmod(t, 1.0) us = int(frac * 1e6) # If timestamp is less than one microsecond smaller than a # full second, us can be rounded up to 1000000. In this case, # roll over to seconds, otherwise, ValueError is raised # by the constructor. if us == 1000000: t += 1 us = 0 y, m, d, hh, mm, ss, weekday, jday, dst = converter(t) ss = min(ss, 59) # clamp out leap seconds if the platform has them result = cls(y, m, d, hh, mm, ss, us, tz) if tz is not None: result = tz.fromutc(result) return result @classmethod def utcfromtimestamp(cls, t): "Construct a UTC datetime from a POSIX timestamp (like time.time())." t, frac = divmod(t, 1.0) us = int(frac * 1e6) # If timestamp is less than one microsecond smaller than a # full second, us can be rounded up to 1000000. In this case, # roll over to seconds, otherwise, ValueError is raised # by the constructor. if us == 1000000: t += 1 us = 0 y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t) ss = min(ss, 59) # clamp out leap seconds if the platform has them return cls(y, m, d, hh, mm, ss, us) # XXX This is supposed to do better than we *can* do by using time.time(), # XXX if the platform supports a more accurate way. The C implementation # XXX uses gettimeofday on platforms that have it, but that isn't # XXX available from Python. So now() may return different results # XXX across the implementations. @classmethod def now(cls, tz=None): "Construct a datetime from time.time() and optional time zone info." t = _time.time() return cls.fromtimestamp(t, tz) @classmethod def utcnow(cls): "Construct a UTC datetime from time.time()." t = _time.time() return cls.utcfromtimestamp(t) @classmethod def combine(cls, date, time): "Construct a datetime from a given date and a given time." if not isinstance(date, _date_class): raise TypeError("date argument must be a date instance") if not isinstance(time, _time_class): raise TypeError("time argument must be a time instance") return cls(date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond, time.tzinfo) def timetuple(self): "Return local time tuple compatible with time.localtime()." dst = self.dst() if dst is None: dst = -1 elif dst: dst = 1 else: dst = 0 return _build_struct_time(self.year, self.month, self.day, self.hour, self.minute, self.second, dst) def timestamp(self): "Return POSIX timestamp as float" if self._tzinfo is None: return _time.mktime((self.year, self.month, self.day, self.hour, self.minute, self.second, -1, -1, -1)) + self.microsecond / 1e6 else: return (self - _EPOCH).total_seconds() def utctimetuple(self): "Return UTC time tuple compatible with time.gmtime()." offset = self.utcoffset() if offset: self -= offset y, m, d = self.year, self.month, self.day hh, mm, ss = self.hour, self.minute, self.second return _build_struct_time(y, m, d, hh, mm, ss, 0) def date(self): "Return the date part." return date(self._year, self._month, self._day) def time(self): "Return the time part, with tzinfo None." return time(self.hour, self.minute, self.second, self.microsecond) def timetz(self): "Return the time part, with same tzinfo." return time(self.hour, self.minute, self.second, self.microsecond, self._tzinfo) def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=True): """Return a new datetime with new values for the specified fields.""" if year is None: year = self.year if month is None: month = self.month if day is None: day = self.day if hour is None: hour = self.hour if minute is None: minute = self.minute if second is None: second = self.second if microsecond is None: microsecond = self.microsecond if tzinfo is True: tzinfo = self.tzinfo _check_date_fields(year, month, day) _check_time_fields(hour, minute, second, microsecond) _check_tzinfo_arg(tzinfo) return datetime(year, month, day, hour, minute, second, microsecond, tzinfo) def astimezone(self, tz=None): if tz is None: if self.tzinfo is None: raise ValueError("astimezone() requires an aware datetime") ts = (self - _EPOCH) // timedelta(seconds=1) localtm = _time.localtime(ts) local = datetime(*localtm[:6]) try: # Extract TZ data if available gmtoff = localtm.tm_gmtoff zone = localtm.tm_zone except AttributeError: # Compute UTC offset and compare with the value implied # by tm_isdst. If the values match, use the zone name # implied by tm_isdst. delta = local - datetime(*_time.gmtime(ts)[:6]) dst = _time.daylight and localtm.tm_isdst > 0 gmtoff = -(_time.altzone if dst else _time.timezone) if delta == timedelta(seconds=gmtoff): tz = timezone(delta, _time.tzname[dst]) else: tz = timezone(delta) else: tz = timezone(timedelta(seconds=gmtoff), zone) elif not isinstance(tz, tzinfo): raise TypeError("tz argument must be an instance of tzinfo") mytz = self.tzinfo if mytz is None: raise ValueError("astimezone() requires an aware datetime") if tz is mytz: return self # Convert self to UTC, and attach the new time zone object. myoffset = self.utcoffset() if myoffset is None: raise ValueError("astimezone() requires an aware datetime") utc = (self - myoffset).replace(tzinfo=tz) # Convert from UTC to tz's local time. return tz.fromutc(utc) # Ways to produce a string. def ctime(self): "Return ctime() style string." weekday = self.toordinal() % 7 or 7 return "%s %s %2d %02d:%02d:%02d %04d" % ( _DAYNAMES[weekday], _MONTHNAMES[self._month], self._day, self._hour, self._minute, self._second, self._year) def isoformat(self, sep='T'): """Return the time formatted according to ISO. This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if self.microsecond == 0. If self.tzinfo is not None, the UTC offset is also attached, giving 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'. Optional argument sep specifies the separator between date and time, default 'T'. """ s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day, sep) + _format_time(self._hour, self._minute, self._second, self._microsecond)) off = self.utcoffset() if off is not None: if off.days < 0: sign = "-" off = -off else: sign = "+" hh, mm = divmod(off, timedelta(hours=1)) assert not mm % timedelta(minutes=1), "whole minute" mm //= timedelta(minutes=1) s += "%s%02d:%02d" % (sign, hh, mm) return s def __repr__(self): """Convert to formal string, for repr().""" L = [self._year, self._month, self._day, # These are never zero self._hour, self._minute, self._second, self._microsecond] if L[-1] == 0: del L[-1] if L[-1] == 0: del L[-1] s = ", ".join(map(str, L)) s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s) if self._tzinfo is not None: assert s[-1:] == ")" s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")" return s def __str__(self): "Convert to string, for str()." return self.isoformat(sep=' ') @classmethod def strptime(cls, date_string, format): 'string, format -> new datetime parsed from a string (like time.strptime()).' import _strptime return _strptime._strptime_datetime(cls, date_string, format) def utcoffset(self): """Return the timezone offset in minutes east of UTC (negative west of UTC).""" if self._tzinfo is None: return None offset = self._tzinfo.utcoffset(self) _check_utc_offset("utcoffset", offset) return offset def tzname(self): """Return the timezone name. Note that the name is 100% informational -- there's no requirement that it mean anything in particular. For example, "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies. """ name = _call_tzinfo_method(self._tzinfo, "tzname", self) _check_tzname(name) return name def dst(self): """Return 0 if DST is not in effect, or the DST offset (in minutes eastward) if DST is in effect. This is purely informational; the DST offset has already been added to the UTC offset returned by utcoffset() if applicable, so there's no need to consult dst() unless you're interested in displaying the DST info. """ if self._tzinfo is None: return None offset = self._tzinfo.dst(self) _check_utc_offset("dst", offset) return offset # Comparisons of datetime objects with other. def __eq__(self, other): if isinstance(other, datetime): return self._cmp(other, allow_mixed=True) == 0 elif not isinstance(other, date): return NotImplemented else: return False def __ne__(self, other): if isinstance(other, datetime): return self._cmp(other, allow_mixed=True) != 0 elif not isinstance(other, date): return NotImplemented else: return True def __le__(self, other): if isinstance(other, datetime): return self._cmp(other) <= 0 elif not isinstance(other, date): return NotImplemented else: _cmperror(self, other) def __lt__(self, other): if isinstance(other, datetime): return self._cmp(other) < 0 elif not isinstance(other, date): return NotImplemented else: _cmperror(self, other) def __ge__(self, other): if isinstance(other, datetime): return self._cmp(other) >= 0 elif not isinstance(other, date): return NotImplemented else: _cmperror(self, other) def __gt__(self, other): if isinstance(other, datetime): return self._cmp(other) > 0 elif not isinstance(other, date): return NotImplemented else: _cmperror(self, other) def _cmp(self, other, allow_mixed=False): assert isinstance(other, datetime) mytz = self._tzinfo ottz = other._tzinfo myoff = otoff = None if mytz is ottz: base_compare = True else: myoff = self.utcoffset() otoff = other.utcoffset() base_compare = myoff == otoff if base_compare: return _cmp((self._year, self._month, self._day, self._hour, self._minute, self._second, self._microsecond), (other._year, other._month, other._day, other._hour, other._minute, other._second, other._microsecond)) if myoff is None or otoff is None: if allow_mixed: return 2 # arbitrary non-zero value else: raise TypeError("cannot compare naive and aware datetimes") # XXX What follows could be done more efficiently... diff = self - other # this will take offsets into account if diff.days < 0: return -1 return diff and 1 or 0 def __add__(self, other): "Add a datetime and a timedelta." if not isinstance(other, timedelta): return NotImplemented delta = timedelta(self.toordinal(), hours=self._hour, minutes=self._minute, seconds=self._second, microseconds=self._microsecond) delta += other hour, rem = divmod(delta.seconds, 3600) minute, second = divmod(rem, 60) if 0 < delta.days <= _MAXORDINAL: return datetime.combine(date.fromordinal(delta.days), time(hour, minute, second, delta.microseconds, tzinfo=self._tzinfo)) raise OverflowError("result out of range") __radd__ = __add__ def __sub__(self, other): "Subtract two datetimes, or a datetime and a timedelta." if not isinstance(other, datetime): if isinstance(other, timedelta): return self + -other return NotImplemented days1 = self.toordinal() days2 = other.toordinal() secs1 = self._second + self._minute * 60 + self._hour * 3600 secs2 = other._second + other._minute * 60 + other._hour * 3600 base = timedelta(days1 - days2, secs1 - secs2, self._microsecond - other._microsecond) if self._tzinfo is other._tzinfo: return base myoff = self.utcoffset() otoff = other.utcoffset() if myoff == otoff: return base if myoff is None or otoff is None: raise TypeError("cannot mix naive and timezone-aware time") return base + otoff - myoff def __hash__(self): tzoff = self.utcoffset() if tzoff is None: return hash(self._getstate()[0]) days = _ymd2ord(self.year, self.month, self.day) seconds = self.hour * 3600 + self.minute * 60 + self.second return hash(timedelta(days, seconds, self.microsecond) - tzoff) # Pickle support. def _getstate(self): yhi, ylo = divmod(self._year, 256) us2, us3 = divmod(self._microsecond, 256) us1, us2 = divmod(us2, 256) basestate = bytes([yhi, ylo, self._month, self._day, self._hour, self._minute, self._second, us1, us2, us3]) if self._tzinfo is None: return (basestate,) else: return (basestate, self._tzinfo) def __setstate(self, string, tzinfo): (yhi, ylo, self._month, self._day, self._hour, self._minute, self._second, us1, us2, us3) = string self._year = yhi * 256 + ylo self._microsecond = (((us1 << 8) | us2) << 8) | us3 if tzinfo is None or isinstance(tzinfo, _tzinfo_class): self._tzinfo = tzinfo else: raise TypeError("bad tzinfo state arg %r" % tzinfo) def __reduce__(self): return (self.__class__, self._getstate()) datetime.min = datetime(1, 1, 1) datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999) datetime.resolution = timedelta(microseconds=1) def _isoweek1monday(year): # Helper to calculate the day number of the Monday starting week 1 # XXX This could be done more efficiently THURSDAY = 3 firstday = _ymd2ord(year, 1, 1) firstweekday = (firstday + 6) % 7 # See weekday() above week1monday = firstday - firstweekday if firstweekday > THURSDAY: week1monday += 7 return week1monday class timezone(tzinfo): __slots__ = '_offset', '_name' # Sentinel value to disallow None _Omitted = object() def __new__(cls, offset, name=_Omitted): if not isinstance(offset, timedelta): raise TypeError("offset must be a timedelta") if name is cls._Omitted: if not offset: return cls.utc name = None elif not isinstance(name, str): raise TypeError("name must be a string") if not cls._minoffset <= offset <= cls._maxoffset: raise ValueError("offset must be a timedelta" " strictly between -timedelta(hours=24) and" " timedelta(hours=24).") if (offset.microseconds != 0 or offset.seconds % 60 != 0): raise ValueError("offset must be a timedelta" " representing a whole number of minutes") return cls._create(offset, name) @classmethod def _create(cls, offset, name=None): self = tzinfo.__new__(cls) self._offset = offset self._name = name return self def __getinitargs__(self): """pickle support""" if self._name is None: return (self._offset,) return (self._offset, self._name) def __eq__(self, other): if type(other) != timezone: return False return self._offset == other._offset def __hash__(self): return hash(self._offset) def __repr__(self): """Convert to formal string, for repr(). >>> tz = timezone.utc >>> repr(tz) 'datetime.timezone.utc' >>> tz = timezone(timedelta(hours=-5), 'EST') >>> repr(tz) "datetime.timezone(datetime.timedelta(-1, 68400), 'EST')" """ if self is self.utc: return 'datetime.timezone.utc' if self._name is None: return "%s(%r)" % ('datetime.' + self.__class__.__name__, self._offset) return "%s(%r, %r)" % ('datetime.' + self.__class__.__name__, self._offset, self._name) def __str__(self): return self.tzname(None) def utcoffset(self, dt): if isinstance(dt, datetime) or dt is None: return self._offset raise TypeError("utcoffset() argument must be a datetime instance" " or None") def tzname(self, dt): if isinstance(dt, datetime) or dt is None: if self._name is None: return self._name_from_offset(self._offset) return self._name raise TypeError("tzname() argument must be a datetime instance" " or None") def dst(self, dt): if isinstance(dt, datetime) or dt is None: return None raise TypeError("dst() argument must be a datetime instance" " or None") def fromutc(self, dt): if isinstance(dt, datetime): if dt.tzinfo is not self: raise ValueError("fromutc: dt.tzinfo " "is not self") return dt + self._offset raise TypeError("fromutc() argument must be a datetime instance" " or None") _maxoffset = timedelta(hours=23, minutes=59) _minoffset = -_maxoffset @staticmethod def _name_from_offset(delta): if delta < timedelta(0): sign = '-' delta = -delta else: sign = '+' hours, rest = divmod(delta, timedelta(hours=1)) minutes = rest // timedelta(minutes=1) return 'UTC{}{:02d}:{:02d}'.format(sign, hours, minutes) timezone.utc = timezone._create(timedelta(0)) timezone.min = timezone._create(timezone._minoffset) timezone.max = timezone._create(timezone._maxoffset) _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) """ Some time zone algebra. For a datetime x, let x.n = x stripped of its timezone -- its naive time. x.o = x.utcoffset(), and assuming that doesn't raise an exception or return None x.d = x.dst(), and assuming that doesn't raise an exception or return None x.s = x's standard offset, x.o - x.d Now some derived rules, where k is a duration (timedelta). 1. x.o = x.s + x.d This follows from the definition of x.s. 2. If x and y have the same tzinfo member, x.s = y.s. This is actually a requirement, an assumption we need to make about sane tzinfo classes. 3. The naive UTC time corresponding to x is x.n - x.o. This is again a requirement for a sane tzinfo class. 4. (x+k).s = x.s This follows from #2, and that datimetimetz+timedelta preserves tzinfo. 5. (x+k).n = x.n + k Again follows from how arithmetic is defined. Now we can explain tz.fromutc(x). Let's assume it's an interesting case (meaning that the various tzinfo methods exist, and don't blow up or return None when called). The function wants to return a datetime y with timezone tz, equivalent to x. x is already in UTC. By #3, we want y.n - y.o = x.n [1] The algorithm starts by attaching tz to x.n, and calling that y. So x.n = y.n at the start. Then it wants to add a duration k to y, so that [1] becomes true; in effect, we want to solve [2] for k: (y+k).n - (y+k).o = x.n [2] By #1, this is the same as (y+k).n - ((y+k).s + (y+k).d) = x.n [3] By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start. Substituting that into [3], x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving k - (y+k).s - (y+k).d = 0; rearranging, k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so k = y.s - (y+k).d On the RHS, (y+k).d can't be computed directly, but y.s can be, and we approximate k by ignoring the (y+k).d term at first. Note that k can't be very large, since all offset-returning methods return a duration of magnitude less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must be 0, so ignoring it has no consequence then. In any case, the new value is z = y + y.s [4] It's helpful to step back at look at [4] from a higher level: it's simply mapping from UTC to tz's standard time. At this point, if z.n - z.o = x.n [5] we have an equivalent time, and are almost done. The insecurity here is at the start of daylight time. Picture US Eastern for concreteness. The wall time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good sense then. The docs ask that an Eastern tzinfo class consider such a time to be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST on the day DST starts. We want to return the 1:MM EST spelling because that's the only spelling that makes sense on the local wall clock. In fact, if [5] holds at this point, we do have the standard-time spelling, but that takes a bit of proof. We first prove a stronger result. What's the difference between the LHS and RHS of [5]? Let diff = x.n - (z.n - z.o) [6] Now z.n = by [4] (y + y.s).n = by #5 y.n + y.s = since y.n = x.n x.n + y.s = since z and y are have the same tzinfo member, y.s = z.s by #2 x.n + z.s Plugging that back into [6] gives diff = x.n - ((x.n + z.s) - z.o) = expanding x.n - x.n - z.s + z.o = cancelling - z.s + z.o = by #2 z.d So diff = z.d. If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time spelling we wanted in the endcase described above. We're done. Contrarily, if z.d = 0, then we have a UTC equivalent, and are also done. If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to add to z (in effect, z is in tz's standard time, and we need to shift the local clock into tz's daylight time). Let z' = z + z.d = z + diff [7] and we can again ask whether z'.n - z'.o = x.n [8] If so, we're done. If not, the tzinfo class is insane, according to the assumptions we've made. This also requires a bit of proof. As before, let's compute the difference between the LHS and RHS of [8] (and skipping some of the justifications for the kinds of substitutions we've done several times already): diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7] x.n - (z.n + diff - z'.o) = replacing diff via [6] x.n - (z.n + x.n - (z.n - z.o) - z'.o) = x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n - z.n + z.n - z.o + z'.o = cancel z.n - z.o + z'.o = #1 twice -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo z'.d - z.d So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal, we've found the UTC-equivalent so are done. In fact, we stop with [7] and return z', not bothering to compute z'.d. How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by a dst() offset, and starting *from* a time already in DST (we know z.d != 0), would have to change the result dst() returns: we start in DST, and moving a little further into it takes us out of DST. There isn't a sane case where this can happen. The closest it gets is at the end of DST, where there's an hour in UTC with no spelling in a hybrid tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM UTC) because the docs insist on that, but 0:MM is taken as being in daylight time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in standard time. Since that's what the local clock *does*, we want to map both UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous in local time, but so it goes -- it's the way the local clock works. When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0, so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going. z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8] (correctly) concludes that z' is not UTC-equivalent to x. Because we know z.d said z was in daylight time (else [5] would have held and we would have stopped then), and we know z.d != z'.d (else [8] would have held and we have stopped then), and there are only 2 possible values dst() can return in Eastern, it follows that z'.d must be 0 (which it is in the example, but the reasoning doesn't depend on the example -- it depends on there being two possible dst() outcomes, one zero and the other non-zero). Therefore z' must be in standard time, and is the spelling we want in this case. Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is concerned (because it takes z' as being in standard time rather than the daylight time we intend here), but returning it gives the real-life "local clock repeats an hour" behavior when mapping the "unspellable" UTC hour into tz. When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with the 1:MM standard time spelling we want. So how can this break? One of the assumptions must be violated. Two possibilities: 1) [2] effectively says that y.s is invariant across all y belong to a given time zone. This isn't true if, for political reasons or continental drift, a region decides to change its base offset from UTC. 2) There may be versions of "double daylight" time where the tail end of the analysis gives up a step too early. I haven't thought about that enough to say. In any case, it's clear that the default fromutc() is strong enough to handle "almost all" time zones: so long as the standard offset is invariant, it doesn't matter if daylight time transition points change from year to year, or if daylight time is skipped in some years; it doesn't matter how large or small dst() may get within its bounds; and it doesn't even matter if some perverse time zone returns a negative dst()). So a breaking case must be pretty bizarre, and a tzinfo subclass can override fromutc() if it is. """ #brython does not have a _datetime, so lets comment this out for now. #try: # from _datetime import * #except ImportError: # pass #else: # # Clean up unused names # del (_DAYNAMES, _DAYS_BEFORE_MONTH, _DAYS_IN_MONTH, # _DI100Y, _DI400Y, _DI4Y, _MAXORDINAL, _MONTHNAMES, # _build_struct_time, _call_tzinfo_method, _check_date_fields, # _check_time_fields, _check_tzinfo_arg, _check_tzname, # _check_utc_offset, _cmp, _cmperror, _date_class, _days_before_month, # _days_before_year, _days_in_month, _format_time, _is_leap, # _isoweek1monday, _math, _ord2ymd, _time, _time_class, _tzinfo_class, # _wrap_strftime, _ymd2ord) # # XXX Since import * above excludes names that start with _, # # docstring does not get overwritten. In the future, it may be # # appropriate to maintain a single module level docstring and # # remove the following line. # #from _datetime import __doc__
gpl-2.0
skurochkin/selenium
py/test/selenium/webdriver/common/proxy_tests.py
65
5759
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC 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 unittest from selenium.webdriver.common.proxy import Proxy, ProxyType class ProxyTests(unittest.TestCase): MANUAL_PROXY = { 'httpProxy': 'some.url:1234', 'ftpProxy': 'ftp.proxy', 'noProxy': 'localhost, foo.localhost', 'sslProxy': 'ssl.proxy:1234', 'socksProxy': 'socks.proxy:65555', 'socksUsername': 'test', 'socksPassword': 'test', } PAC_PROXY = { 'proxyAutoconfigUrl': 'http://pac.url:1234', } AUTODETECT_PROXY = { 'autodetect': True, } def testCanAddManualProxyToDesiredCapabilities(self): proxy = Proxy() proxy.http_proxy = self.MANUAL_PROXY['httpProxy'] proxy.ftp_proxy = self.MANUAL_PROXY['ftpProxy'] proxy.no_proxy = self.MANUAL_PROXY['noProxy'] proxy.sslProxy = self.MANUAL_PROXY['sslProxy'] proxy.socksProxy = self.MANUAL_PROXY['socksProxy'] proxy.socksUsername = self.MANUAL_PROXY['socksUsername'] proxy.socksPassword = self.MANUAL_PROXY['socksPassword'] desired_capabilities = {} proxy.add_to_capabilities(desired_capabilities) proxy_capabilities = self.MANUAL_PROXY.copy() proxy_capabilities['proxyType'] = 'MANUAL' expected_capabilities = {'proxy': proxy_capabilities} self.assertEqual(expected_capabilities, desired_capabilities) def testCanAddAutodetectProxyToDesiredCapabilities(self): proxy = Proxy() proxy.auto_detect = self.AUTODETECT_PROXY['autodetect'] desired_capabilities = {} proxy.add_to_capabilities(desired_capabilities) proxy_capabilities = self.AUTODETECT_PROXY.copy() proxy_capabilities['proxyType'] = 'AUTODETECT' expected_capabilities = {'proxy': proxy_capabilities} self.assertEqual(expected_capabilities, desired_capabilities) def testCanAddPACProxyToDesiredCapabilities(self): proxy = Proxy() proxy.proxy_autoconfig_url = self.PAC_PROXY['proxyAutoconfigUrl'] desired_capabilities = {} proxy.add_to_capabilities(desired_capabilities) proxy_capabilities = self.PAC_PROXY.copy() proxy_capabilities['proxyType'] = 'PAC' expected_capabilities = {'proxy': proxy_capabilities} self.assertEqual(expected_capabilities, desired_capabilities) def testCanNotChangeInitializedProxyType(self): proxy = Proxy(raw={'proxyType': 'direct'}) try: proxy.proxy_type = ProxyType.SYSTEM raise Exception("Change of already initialized proxy type should raise exception") except Exception as e: pass proxy = Proxy(raw={'proxyType': ProxyType.DIRECT}) try: proxy.proxy_type = ProxyType.SYSTEM raise Exception("Change of already initialized proxy type should raise exception") except Exception as e: pass def testCanInitManualProxy(self): proxy = Proxy(raw=self.MANUAL_PROXY) self.assertEqual(ProxyType.MANUAL, proxy.proxy_type) self.assertEqual(self.MANUAL_PROXY['httpProxy'], proxy.http_proxy) self.assertEqual(self.MANUAL_PROXY['ftpProxy'], proxy.ftp_proxy) self.assertEqual(self.MANUAL_PROXY['noProxy'], proxy.no_proxy) self.assertEqual(self.MANUAL_PROXY['sslProxy'], proxy.sslProxy) self.assertEqual(self.MANUAL_PROXY['socksProxy'], proxy.socksProxy) self.assertEqual(self.MANUAL_PROXY['socksUsername'], proxy.socksUsername) self.assertEqual(self.MANUAL_PROXY['socksPassword'], proxy.socksPassword) def testCanAddAutodetectProxyToDesiredCapabilities(self): proxy = Proxy(raw=self.AUTODETECT_PROXY) self.assertEqual(ProxyType.AUTODETECT, proxy.proxy_type) self.assertEqual(self.AUTODETECT_PROXY['autodetect'], proxy.auto_detect) def testCanAddPACProxyToDesiredCapabilities(self): proxy = Proxy(raw=self.PAC_PROXY) self.assertEqual(ProxyType.PAC, proxy.proxy_type) self.assertEqual(self.PAC_PROXY['proxyAutoconfigUrl'], proxy.proxy_autoconfig_url) def testCanInitEmptyProxy(self): proxy = Proxy() self.assertEqual(ProxyType.UNSPECIFIED, proxy.proxy_type) self.assertEqual('', proxy.http_proxy) self.assertEqual('', proxy.ftp_proxy) self.assertEqual('', proxy.no_proxy) self.assertEqual('', proxy.sslProxy) self.assertEqual('', proxy.socksProxy) self.assertEqual('', proxy.socksUsername) self.assertEqual('', proxy.socksPassword) self.assertEqual(False, proxy.auto_detect) self.assertEqual('', proxy.proxy_autoconfig_url) desired_capabilities = {} proxy.add_to_capabilities(desired_capabilities) proxy_capabilities = {} proxy_capabilities['proxyType'] = 'UNSPECIFIED' expected_capabilities = {'proxy': proxy_capabilities} self.assertEqual(expected_capabilities, desired_capabilities)
apache-2.0
shawncaojob/LC
QUESTIONS/149_max_points_on_a_line_v2.py
1
1940
# 149. Max Points on a Line QuestionEditorial Solution My Submissions # Total Accepted: 69049 # Total Submissions: 450757 # Difficulty: Hard # Contributors: Admin # Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. # # Subscribe to see which companies asked this question # Definition for a point. class Point(object): def __init__(self, a=0, b=0): self.x = a self.y = b class Solution(object): def maxPoints(self, points): """ :type points: List[Point] :rtype: int """ if not points: return 0 if len(points) == 1: return 1 n = len(points) dic = {} res = 0 for i in xrange(n): for j in xrange(i+1, n): key = self.getKey(points[i], points[j]) if key in dic: dic[key].add(i) dic[key].add(j) else: dic[key] = set([i, j]) print(i, j, dic) res = max(res, len(dic[key])) return res def getKey(self, a, b): if a.x == b.x and a.y == b.y: return "A" + str(a.x) + str(a.y) if a.y == b.y: return "B" + str(a.y) if a.x == b.x: return "C" + str(a.x) slope = (b.y - a.y) / (b.x - a.x) b = a.y - slope * a.x return str(slope) + "D" + str(b) if __name__ == "__main__": #A = [[0,-12],[5,2],[2,5],[0,-5],[1,5],[2,-2],[5,-4],[3,4],[-2,4],[-1,4],[0,-5],[0,-8],[-2,-1],[0,-11],[0,-9]] #A = [[0,0],[1,1],[1,-1]] # A = [[84,250],[0,0],[1,0],[0,-70],[0,-70],[1,-1],[21,10],[42,90],[-42,-230]] A = [[3,10],[0,2],[0,2],[3,10]] print(A) points = [] for i, j in A: cur = Point(i, j) points.append(cur) # for point in points: # print(point.x, point.y) print(Solution().maxPoints(points))
gpl-3.0
nrkumar93/bnr_workspace
label_training_detection/scripts/imrotate.py
1
1583
#!/usr/bin/env python # -*- coding: utf-8 -*- # # imrotate.py # # Copyright 2016 Ramkumar Natarajan <ram@ramkumar-ubuntu> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # from PIL import Image from os import listdir, walk from os.path import isfile, join import shutil if __name__ == '__main__': srcFolder = "/home/prasanna/workspace_ram/dataset/lowes/label_training/big_blue_box/src/test/"; dst = "/home/prasanna/workspace_ram/dataset/lowes/label_training/big_blue_box/src/test_rot/"; filepath = [] srcfiles = [] #~ srcfiles = [f for f in listdir(srcFolder) if isfile(join(srcFolder, f))]; for root, dirs, files in walk(srcFolder): for f in files: filepath.append(join(root, f)) srcfiles.append(f) i=0 for f in filepath: src = f; img = Image.open(src); rot = img.rotate(-90); dst_name = dst + srcfiles[i]; rot.save(dst_name) i+=1
gpl-3.0
hectord/lettuce
tests/integration/django/dill/leaves/models.py
18
1285
from django.db import models class Garden(models.Model): name = models.CharField(max_length=100) area = models.IntegerField() raining = models.BooleanField() @property def howbig(self): if self.area < 50: return 'small' elif self.area < 150: return 'medium' else: return 'big' class Field(models.Model): name = models.CharField(max_length=100) class Fruit(models.Model): name = models.CharField(max_length=100) garden = models.ForeignKey(Garden) ripe_by = models.DateField() fields = models.ManyToManyField(Field) class Bee(models.Model): name = models.CharField(max_length=100) pollinated_fruit = models.ManyToManyField(Fruit, related_name='pollinated_by') class Goose(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "geese" class Harvester(models.Model): make = models.CharField(max_length=100) rego = models.CharField(max_length=100) class Panda(models.Model): """ Not part of a garden, but still an important part of any good application """ name = models.CharField(max_length=100) location = models.CharField(max_length=100)
gpl-3.0
kouaw/CouchPotatoServer
libs/requests/adapters.py
21
16075
# -*- coding: utf-8 -*- """ requests.adapters ~~~~~~~~~~~~~~~~~ This module contains the transport adapters that Requests uses to define and maintain connections. """ import socket from .models import Response from .packages.urllib3 import Retry from .packages.urllib3.poolmanager import PoolManager, proxy_from_url from .packages.urllib3.response import HTTPResponse from .packages.urllib3.util import Timeout as TimeoutSauce from .compat import urlparse, basestring, urldefrag from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers, prepend_scheme_if_needed, get_auth_from_url) from .structures import CaseInsensitiveDict from .packages.urllib3.exceptions import ConnectTimeoutError from .packages.urllib3.exceptions import HTTPError as _HTTPError from .packages.urllib3.exceptions import MaxRetryError from .packages.urllib3.exceptions import ProxyError as _ProxyError from .packages.urllib3.exceptions import ReadTimeoutError from .packages.urllib3.exceptions import SSLError as _SSLError from .cookies import extract_cookies_to_jar from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError, ProxyError) from .auth import _basic_auth_str DEFAULT_POOLBLOCK = False DEFAULT_POOLSIZE = 10 DEFAULT_RETRIES = 0 class BaseAdapter(object): """The Base Transport Adapter""" def __init__(self): super(BaseAdapter, self).__init__() def send(self): raise NotImplementedError def close(self): 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 int max_retries: The maximum number of retries each connection should attempt. Note, this applies only to failed connections and timeouts, never to requests where the server returns a response. :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): self.max_retries = 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 dict((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 # 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, **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 """ if not proxy in self.proxy_manager: proxy_headers = self.proxy_headers(proxy) 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 self.proxy_manager[proxy] 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: Whether we should actually verify the certificate. :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 = DEFAULT_CA_BUNDLE_PATH if not cert_loc: raise Exception("Could not find a suitable SSL CA certificate bundle.") conn.cert_reqs = 'CERT_REQUIRED' conn.ca_certs = cert_loc else: conn.cert_reqs = 'CERT_NONE' conn.ca_certs = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert 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. """ 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. """ proxies = proxies or {} proxy = proxies.get(urlparse(url.lower()).scheme) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') 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 just closes the PoolManager, which closes pooled connections. """ self.poolmanager.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 to proxy URLs. """ proxies = proxies or {} scheme = urlparse(request.url).scheme proxy = proxies.get(scheme) if proxy and scheme != 'https': url, _ = urldefrag(request.url) else: url = request.path_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 proxies: The url of the proxy being used for this request. :param kwargs: Optional additional keyword arguments. """ headers = {} username, password = get_auth_from_url(proxy) if username and password: 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) The timeout on the request. :type timeout: float or tuple (connect timeout, read timeout), eg (3.1, 20) :param verify: (optional) Whether to verify SSL certificates. :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. """ conn = self.get_connection(request.url, proxies) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers(request) 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 {0}. Pass a (connect, read) " "timeout tuple, or a single float to set " "both timeouts to the same value".format(timeout)) raise ValueError(err) 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=Retry(self.max_retries, read=False), timeout=timeout ) # Send the request. else: if hasattr(conn, 'proxy_pool'): conn = conn.proxy_pool low_conn = conn._get_conn(timeout=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') 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 else: # All is well, return the connection to the pool. conn._put_conn(low_conn) except socket.error as sockerr: raise ConnectionError(sockerr, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): raise ConnectTimeout(e, request=request) raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) else: raise return self.build_response(request, resp)
gpl-3.0
pandeyop/tempest
tempest/scenario/test_snapshot_pattern.py
27
3352
# Copyright 2013 NEC Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_log import log import testtools from tempest import config from tempest.scenario import manager from tempest import test CONF = config.CONF LOG = log.getLogger(__name__) class TestSnapshotPattern(manager.ScenarioTest): """ This test is for snapshotting an instance and booting with it. The following is the scenario outline: * boot a instance and create a timestamp file in it * snapshot the instance * boot a second instance from the snapshot * check the existence of the timestamp file in the second instance """ def _boot_image(self, image_id): security_groups = [{'name': self.security_group['name']}] create_kwargs = { 'key_name': self.keypair['name'], 'security_groups': security_groups } return self.create_server(image=image_id, create_kwargs=create_kwargs) def _add_keypair(self): self.keypair = self.create_keypair() def _write_timestamp(self, server_or_ip): ssh_client = self.get_remote_client(server_or_ip) ssh_client.exec_command('date > /tmp/timestamp; sync') self.timestamp = ssh_client.exec_command('cat /tmp/timestamp') def _check_timestamp(self, server_or_ip): ssh_client = self.get_remote_client(server_or_ip) got_timestamp = ssh_client.exec_command('cat /tmp/timestamp') self.assertEqual(self.timestamp, got_timestamp) @test.idempotent_id('608e604b-1d63-4a82-8e3e-91bc665c90b4') @testtools.skipUnless(CONF.compute_feature_enabled.snapshot, 'Snapshotting is not available.') @test.services('compute', 'network', 'image') def test_snapshot_pattern(self): # prepare for booting a instance self._add_keypair() self.security_group = self._create_security_group() # boot a instance and create a timestamp file in it server = self._boot_image(CONF.compute.image_ref) if CONF.compute.use_floatingip_for_ssh: fip_for_server = self.create_floating_ip(server) self._write_timestamp(fip_for_server['ip']) else: self._write_timestamp(server) # snapshot the instance snapshot_image = self.create_server_snapshot(server=server) # boot a second instance from the snapshot server_from_snapshot = self._boot_image(snapshot_image['id']) # check the existence of the timestamp file in the second instance if CONF.compute.use_floatingip_for_ssh: fip_for_snapshot = self.create_floating_ip(server_from_snapshot) self._check_timestamp(fip_for_snapshot['ip']) else: self._check_timestamp(server_from_snapshot)
apache-2.0
ktan2020/legacy-automation
win/Lib/site-packages/wx-3.0-msw/wx/lib/floatcanvas/Utilities/BBoxTest.py
1
17378
#!/usr/bin/env python """ Test code for the BBox Object """ import unittest from BBox import * class testCreator(unittest.TestCase): def testCreates(self): B = BBox(((0,0),(5,5))) self.failUnless(isinstance(B, BBox)) def testType(self): B = N.array(((0,0),(5,5))) self.failIf(isinstance(B, BBox)) def testDataType(self): B = BBox(((0,0),(5,5))) self.failUnless(B.dtype == N.float) def testShape(self): B = BBox((0,0,5,5)) self.failUnless(B.shape == (2,2)) def testShape2(self): self.failUnlessRaises(ValueError, BBox, (0,0,5) ) def testShape3(self): self.failUnlessRaises(ValueError, BBox, (0,0,5,6,7) ) def testArrayConstruction(self): A = N.array(((4,5),(10,12)), N.float_) B = BBox(A) self.failUnless(isinstance(B, BBox)) def testMinMax(self): self.failUnlessRaises(ValueError, BBox, (0,0,-1,6) ) def testMinMax2(self): self.failUnlessRaises(ValueError, BBox, (0,0,1,-6) ) def testMinMax(self): # OK to have a zero-sized BB B = BBox(((0,0),(0,5))) self.failUnless(isinstance(B, BBox)) def testMinMax2(self): # OK to have a zero-sized BB B = BBox(((10.0,-34),(10.0,-34.0))) self.failUnless(isinstance(B, BBox)) def testMinMax3(self): # OK to have a tiny BB B = BBox(((0,0),(1e-20,5))) self.failUnless(isinstance(B, BBox)) def testMinMax4(self): # Should catch tiny difference self.failUnlessRaises(ValueError, BBox, ((0,0), (-1e-20,5)) ) class testAsBBox(unittest.TestCase): def testPassThrough(self): B = BBox(((0,0),(5,5))) C = asBBox(B) self.failUnless(B is C) def testPassThrough2(self): B = (((0,0),(5,5))) C = asBBox(B) self.failIf(B is C) def testPassArray(self): # Different data type A = N.array( (((0,0),(5,5))) ) C = asBBox(A) self.failIf(A is C) def testPassArray2(self): # same data type -- should be a view A = N.array( (((0,0),(5,5))), N.float_ ) C = asBBox(A) A[0,0] = -10 self.failUnless(C[0,0] == A[0,0]) class testIntersect(unittest.TestCase): def testSame(self): B = BBox(((-23.5, 456),(56, 532.0))) C = BBox(((-23.5, 456),(56, 532.0))) self.failUnless(B.Overlaps(C) ) def testUpperLeft(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (0, 12),(10, 32.0) ) ) self.failUnless(B.Overlaps(C) ) def testUpperRight(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (12, 12),(25, 32.0) ) ) self.failUnless(B.Overlaps(C) ) def testLowerRight(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (12, 5),(25, 15) ) ) self.failUnless(B.Overlaps(C) ) def testLowerLeft(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (-10, 5),(8.5, 15) ) ) self.failUnless(B.Overlaps(C) ) def testBelow(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (-10, 5),(8.5, 9.2) ) ) self.failIf(B.Overlaps(C) ) def testAbove(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (-10, 25.001),(8.5, 32) ) ) self.failIf(B.Overlaps(C) ) def testLeft(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (4, 8),(4.95, 32) ) ) self.failIf(B.Overlaps(C) ) def testRight(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (17.1, 8),(17.95, 32) ) ) self.failIf(B.Overlaps(C) ) def testInside(self): B = BBox( ( (-15, -25),(-5, -10) ) ) C = BBox( ( (-12, -22), (-6, -8) ) ) self.failUnless(B.Overlaps(C) ) def testOutside(self): B = BBox( ( (-15, -25),(-5, -10) ) ) C = BBox( ( (-17, -26), (3, 0) ) ) self.failUnless(B.Overlaps(C) ) def testTouch(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (15, 8),(17.95, 32) ) ) self.failUnless(B.Overlaps(C) ) def testCorner(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (15, 25),(17.95, 32) ) ) self.failUnless(B.Overlaps(C) ) def testZeroSize(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (15, 25),(15, 25) ) ) self.failUnless(B.Overlaps(C) ) def testZeroSize2(self): B = BBox( ( (5, 10),(5, 10) ) ) C = BBox( ( (15, 25),(15, 25) ) ) self.failIf(B.Overlaps(C) ) def testZeroSize3(self): B = BBox( ( (5, 10),(5, 10) ) ) C = BBox( ( (0, 8),(10, 12) ) ) self.failUnless(B.Overlaps(C) ) def testZeroSize4(self): B = BBox( ( (5, 1),(10, 25) ) ) C = BBox( ( (8, 8),(8, 8) ) ) self.failUnless(B.Overlaps(C) ) class testEquality(unittest.TestCase): def testSame(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) C = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) self.failUnless(B == C) def testIdentical(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) self.failUnless(B == B) def testNotSame(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) C = BBox( ( (1.0, 2.0), (5.0, 10.1) ) ) self.failIf(B == C) def testWithArray(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) C = N.array( ( (1.0, 2.0), (5.0, 10.0) ) ) self.failUnless(B == C) def testWithArray2(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) C = N.array( ( (1.0, 2.0), (5.0, 10.0) ) ) self.failUnless(C == B) def testWithArray2(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) C = N.array( ( (1.01, 2.0), (5.0, 10.0) ) ) self.failIf(C == B) class testInside(unittest.TestCase): def testSame(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) C = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) self.failUnless(B.Inside(C)) def testPoint(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) C = BBox( ( (3.0, 4.0), (3.0, 4.0) ) ) self.failUnless(B.Inside(C)) def testPointOutside(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) C = BBox( ( (-3.0, 4.0), (0.10, 4.0) ) ) self.failIf(B.Inside(C)) def testUpperLeft(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (0, 12),(10, 32.0) ) ) self.failIf(B.Inside(C) ) def testUpperRight(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (12, 12),(25, 32.0) ) ) self.failIf(B.Inside(C) ) def testLowerRight(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (12, 5),(25, 15) ) ) self.failIf(B.Inside(C) ) def testLowerLeft(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (-10, 5),(8.5, 15) ) ) self.failIf(B.Inside(C) ) def testBelow(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (-10, 5),(8.5, 9.2) ) ) self.failIf(B.Inside(C) ) def testAbove(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (-10, 25.001),(8.5, 32) ) ) self.failIf(B.Inside(C) ) def testLeft(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (4, 8),(4.95, 32) ) ) self.failIf(B.Inside(C) ) def testRight(self): B = BBox( ( (5, 10),(15, 25) ) ) C = BBox( ( (17.1, 8),(17.95, 32) ) ) self.failIf(B.Inside(C) ) class testPointInside(unittest.TestCase): def testPointIn(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) P = (3.0, 4.0) self.failUnless(B.PointInside(P)) def testUpperLeft(self): B = BBox( ( (5, 10),(15, 25) ) ) P = (4, 30) self.failIf(B.PointInside(P)) def testUpperRight(self): B = BBox( ( (5, 10),(15, 25) ) ) P = (16, 30) self.failIf(B.PointInside(P)) def testLowerRight(self): B = BBox( ( (5, 10),(15, 25) ) ) P = (16, 4) self.failIf(B.PointInside(P)) def testLowerLeft(self): B = BBox( ( (5, 10),(15, 25) ) ) P = (-10, 5) self.failIf(B.PointInside(P)) def testBelow(self): B = BBox( ( (5, 10),(15, 25) ) ) P = (10, 5) self.failIf(B.PointInside(P)) def testAbove(self): B = BBox( ( (5, 10),(15, 25) ) ) P = ( 10, 25.001) self.failIf(B.PointInside(P)) def testLeft(self): B = BBox( ( (5, 10),(15, 25) ) ) P = (4, 12) self.failIf(B.PointInside(P)) def testRight(self): B = BBox( ( (5, 10),(15, 25) ) ) P = (17.1, 12.3) self.failIf(B.PointInside(P)) def testPointOnTopLine(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) P = (3.0, 10.0) self.failUnless(B.PointInside(P)) def testPointLeftTopLine(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) P = (-3.0, 10.0) self.failIf(B.PointInside(P)) def testPointOnBottomLine(self): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) P = (3.0, 5.0) self.failUnless(B.PointInside(P)) def testPointOnLeft(self): B = BBox( ( (-10.0, -10.0), (-1.0, -1.0) ) ) P = (-10, -5.0) self.failUnless(B.PointInside(P)) def testPointOnRight(self): B = BBox( ( (-10.0, -10.0), (-1.0, -1.0) ) ) P = (-1, -5.0) self.failUnless(B.PointInside(P)) def testPointOnBottomRight(self): B = BBox( ( (-10.0, -10.0), (-1.0, -1.0) ) ) P = (-1, -10.0) self.failUnless(B.PointInside(P)) class testFromPoints(unittest.TestCase): def testCreate(self): Pts = N.array( ((5,2), (3,4), (1,6), ), N.float_ ) B = fromPoints(Pts) #B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) self.failUnless(B[0,0] == 1.0 and B[0,1] == 2.0 and B[1,0] == 5.0 and B[1,1] == 6.0 ) def testCreateInts(self): Pts = N.array( ((5,2), (3,4), (1,6), ) ) B = fromPoints(Pts) self.failUnless(B[0,0] == 1.0 and B[0,1] == 2.0 and B[1,0] == 5.0 and B[1,1] == 6.0 ) def testSinglePoint(self): Pts = N.array( (5,2), N.float_ ) B = fromPoints(Pts) self.failUnless(B[0,0] == 5.0 and B[0,1] == 2.0 and B[1,0] == 5.0 and B[1,1] == 2.0 ) def testListTuples(self): Pts = [ (3, 6.5), (13, 43.2), (-4.32, -4), (65, -23), (-0.0001, 23.432), ] B = fromPoints(Pts) self.failUnless(B[0,0] == -4.32 and B[0,1] == -23.0 and B[1,0] == 65.0 and B[1,1] == 43.2 ) class testMerge(unittest.TestCase): A = BBox( ((-23.5, 456), (56, 532.0)) ) B = BBox( ((-20.3, 460), (54, 465 )) )# B should be completely inside A C = BBox( ((-23.5, 456), (58, 540.0)) )# up and to the right or A D = BBox( ((-26.5, 12), (56, 532.0)) ) def testInside(self): C = self.A.copy() C.Merge(self.B) self.failUnless(C == self.A) def testFullOutside(self): C = self.B.copy() C.Merge(self.A) self.failUnless(C == self.A) def testUpRight(self): A = self.A.copy() A.Merge(self.C) self.failUnless(A[0] == self.A[0] and A[1] == self.C[1]) def testDownLeft(self): A = self.A.copy() A.Merge(self.D) self.failUnless(A[0] == self.D[0] and A[1] == self.A[1]) class testWidthHeight(unittest.TestCase): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) def testWidth(self): self.failUnless(self.B.Width == 4.0) def testWidth(self): self.failUnless(self.B.Height == 8.0) def attemptSetWidth(self): self.B.Width = 6 def attemptSetHeight(self): self.B.Height = 6 def testSetW(self): self.failUnlessRaises(AttributeError, self.attemptSetWidth) def testSetH(self): self.failUnlessRaises(AttributeError, self.attemptSetHeight) class testCenter(unittest.TestCase): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) def testCenter(self): self.failUnless( (self.B.Center == (3.0, 6.0)).all() ) def attemptSetCenter(self): self.B.Center = (6, 5) def testSetCenter(self): self.failUnlessRaises(AttributeError, self.attemptSetCenter) class testBBarray(unittest.TestCase): BBarray = N.array( ( ((-23.5, 456), (56, 532.0)), ((-20.3, 460), (54, 465 )), ((-23.5, 456), (58, 540.0)), ((-26.5, 12), (56, 532.0)), ), dtype=N.float) BB = asBBox( ((-26.5, 12.), ( 58. , 540.)) ) def testJoin(self): BB = fromBBArray(self.BBarray) self.failUnless(BB == self.BB, "Wrong BB was created. It was:\n%s \nit should have been:\n%s"%(BB, self.BB)) class testNullBBox(unittest.TestCase): B1 = NullBBox() B2 = NullBBox() B3 = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) def testValues(self): self.failUnless( N.alltrue(N.isnan(self.B1)) ) def testIsNull(self): self.failUnless( self.B1.IsNull ) def testEquals(self): self.failUnless( (self.B1 == self.B2) == True ) def testNotEquals(self): self.failUnless ( (self.B1 == self.B3) == False, "NotEquals failed for\n%s,\n %s:%s"%(self.B1, self.B3, (self.B1 == self.B3)) ) def testNotEquals2(self): self.failUnless ( (self.B3 == self.B1) == False, "NotEquals failed for\n%s,\n %s:%s"%(self.B3, self.B1, (self.B3 == self.B1)) ) def testMerge(self): C = self.B1.copy() C.Merge(self.B3) self.failUnless( C == self.B3, "merge failed, got: %s"%C ) def testOverlaps(self): self.failUnless( self.B1.Overlaps(self.B3) == False) def testOverlaps2(self): self.failUnless( self.B3.Overlaps(self.B1) == False) class testInfBBox(unittest.TestCase): B1 = InfBBox() B2 = InfBBox() B3 = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) NB = NullBBox() def testValues(self): self.failUnless( N.alltrue(N.isinf(self.B1)) ) # def testIsNull(self): # self.failUnless( self.B1.IsNull ) def testEquals(self): self.failUnless( (self.B1 == self.B2) == True ) def testNotEquals(self): print (self.B1 == self.B3) == False self.failUnless ( (self.B1 == self.B3) == False, "NotEquals failed for\n%s,\n %s:%s"%(self.B1, self.B3, (self.B1 == self.B3)) ) def testNotEquals2(self): self.failUnless ( (self.B3 == self.B1) == False, "NotEquals failed for\n%s,\n %s:%s"%(self.B3, self.B1, (self.B3 == self.B1)) ) def testMerge(self): C = self.B1.copy() C.Merge(self.B3) self.failUnless( C == self.B2, "merge failed, got: %s"%C ) def testMerge2(self): C = self.B3.copy() C.Merge(self.B1) self.failUnless( C == self.B1, "merge failed, got: %s"%C ) def testOverlaps(self): self.failUnless( self.B1.Overlaps(self.B2) == True) def testOverlaps2(self): self.failUnless( self.B3.Overlaps(self.B1) == True) def testOverlaps3(self): self.failUnless( self.B1.Overlaps(self.B3) == True) def testOverlaps4(self): self.failUnless( self.B1.Overlaps(self.NB) == True) def testOverlaps5(self): self.failUnless( self.NB.Overlaps(self.B1) == True) class testSides(unittest.TestCase): B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) ) def testLeft(self): self.failUnless( self.B.Left == 1.0 ) def testRight(self): self.failUnless( self.B.Right == 5.0 ) def testBottom(self): self.failUnless( self.B.Bottom == 2.0 ) def testTop(self): self.failUnless( self.B.Top == 10.0 ) if __name__ == "__main__": unittest.main()
mit
hackers-terabit/portage
pym/portage/process.py
6
20975
# portage.py -- core Portage functionality # Copyright 1998-2014 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 import atexit import errno import fcntl import platform import signal import socket import struct import sys import traceback import os as _os from portage import os from portage import _encodings from portage import _unicode_encode import portage portage.proxy.lazyimport.lazyimport(globals(), 'portage.util:dump_traceback,writemsg', ) from portage.const import BASH_BINARY, SANDBOX_BINARY, FAKEROOT_BINARY from portage.exception import CommandNotFound from portage.util._ctypes import find_library, LoadLibrary, ctypes try: import resource max_fd_limit = resource.getrlimit(resource.RLIMIT_NOFILE)[0] except ImportError: max_fd_limit = 256 if sys.hexversion >= 0x3000000: # pylint: disable=W0622 basestring = str # Support PEP 446 for Python >=3.4 try: _set_inheritable = _os.set_inheritable except AttributeError: _set_inheritable = None try: _FD_CLOEXEC = fcntl.FD_CLOEXEC except AttributeError: _FD_CLOEXEC = None # Prefer /proc/self/fd if available (/dev/fd # doesn't work on solaris, see bug #474536). for _fd_dir in ("/proc/self/fd", "/dev/fd"): if os.path.isdir(_fd_dir): break else: _fd_dir = None # /dev/fd does not work on FreeBSD, see bug #478446 if platform.system() in ('FreeBSD',) and _fd_dir == '/dev/fd': _fd_dir = None if _fd_dir is not None: def get_open_fds(): return (int(fd) for fd in os.listdir(_fd_dir) if fd.isdigit()) if platform.python_implementation() == 'PyPy': # EAGAIN observed with PyPy 1.8. _get_open_fds = get_open_fds def get_open_fds(): try: return _get_open_fds() except OSError as e: if e.errno != errno.EAGAIN: raise return range(max_fd_limit) elif os.path.isdir("/proc/%s/fd" % os.getpid()): # In order for this function to work in forked subprocesses, # os.getpid() must be called from inside the function. def get_open_fds(): return (int(fd) for fd in os.listdir("/proc/%s/fd" % os.getpid()) if fd.isdigit()) else: def get_open_fds(): return range(max_fd_limit) sandbox_capable = (os.path.isfile(SANDBOX_BINARY) and os.access(SANDBOX_BINARY, os.X_OK)) fakeroot_capable = (os.path.isfile(FAKEROOT_BINARY) and os.access(FAKEROOT_BINARY, os.X_OK)) def spawn_bash(mycommand, debug=False, opt_name=None, **keywords): """ Spawns a bash shell running a specific commands @param mycommand: The command for bash to run @type mycommand: String @param debug: Turn bash debugging on (set -x) @type debug: Boolean @param opt_name: Name of the spawned process (detaults to binary name) @type opt_name: String @param keywords: Extra Dictionary arguments to pass to spawn @type keywords: Dictionary """ args = [BASH_BINARY] if not opt_name: opt_name = os.path.basename(mycommand.split()[0]) if debug: # Print commands and their arguments as they are executed. args.append("-x") args.append("-c") args.append(mycommand) return spawn(args, opt_name=opt_name, **keywords) def spawn_sandbox(mycommand, opt_name=None, **keywords): if not sandbox_capable: return spawn_bash(mycommand, opt_name=opt_name, **keywords) args = [SANDBOX_BINARY] if not opt_name: opt_name = os.path.basename(mycommand.split()[0]) args.append(mycommand) return spawn(args, opt_name=opt_name, **keywords) def spawn_fakeroot(mycommand, fakeroot_state=None, opt_name=None, **keywords): args = [FAKEROOT_BINARY] if not opt_name: opt_name = os.path.basename(mycommand.split()[0]) if fakeroot_state: open(fakeroot_state, "a").close() args.append("-s") args.append(fakeroot_state) args.append("-i") args.append(fakeroot_state) args.append("--") args.append(BASH_BINARY) args.append("-c") args.append(mycommand) return spawn(args, opt_name=opt_name, **keywords) _exithandlers = [] def atexit_register(func, *args, **kargs): """Wrapper around atexit.register that is needed in order to track what is registered. For example, when portage restarts itself via os.execv, the atexit module does not work so we have to do it manually by calling the run_exitfuncs() function in this module.""" _exithandlers.append((func, args, kargs)) def run_exitfuncs(): """This should behave identically to the routine performed by the atexit module at exit time. It's only necessary to call this function when atexit will not work (because of os.execv, for example).""" # This function is a copy of the private atexit._run_exitfuncs() # from the python 2.4.2 sources. The only difference from the # original function is in the output to stderr. exc_info = None while _exithandlers: func, targs, kargs = _exithandlers.pop() try: func(*targs, **kargs) except SystemExit: exc_info = sys.exc_info() except: # No idea what they called, so we need this broad except here. dump_traceback("Error in portage.process.run_exitfuncs", noiselevel=0) exc_info = sys.exc_info() if exc_info is not None: if sys.hexversion >= 0x3000000: raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) else: exec("raise exc_info[0], exc_info[1], exc_info[2]") atexit.register(run_exitfuncs) # It used to be necessary for API consumers to remove pids from spawned_pids, # since otherwise it would accumulate a pids endlessly. Now, spawned_pids is # just an empty dummy list, so for backward compatibility, ignore ValueError # for removal on non-existent items. class _dummy_list(list): def remove(self, item): # TODO: Trigger a DeprecationWarning here, after stable portage # has dummy spawned_pids. try: list.remove(self, item) except ValueError: pass spawned_pids = _dummy_list() def cleanup(): pass def spawn(mycommand, env={}, opt_name=None, fd_pipes=None, returnpid=False, uid=None, gid=None, groups=None, umask=None, logfile=None, path_lookup=True, pre_exec=None, close_fds=True, unshare_net=False, unshare_ipc=False, cgroup=None): """ Spawns a given command. @param mycommand: the command to execute @type mycommand: String or List (Popen style list) @param env: A dict of Key=Value pairs for env variables @type env: Dictionary @param opt_name: an optional name for the spawn'd process (defaults to the binary name) @type opt_name: String @param fd_pipes: A dict of mapping for pipes, { '0': stdin, '1': stdout } for example (default is {0:stdin, 1:stdout, 2:stderr}) @type fd_pipes: Dictionary @param returnpid: Return the Process IDs for a successful spawn. NOTE: This requires the caller clean up all the PIDs, otherwise spawn will clean them. @type returnpid: Boolean @param uid: User ID to spawn as; useful for dropping privilages @type uid: Integer @param gid: Group ID to spawn as; useful for dropping privilages @type gid: Integer @param groups: Group ID's to spawn in: useful for having the process run in multiple group contexts. @type groups: List @param umask: An integer representing the umask for the process (see man chmod for umask details) @type umask: Integer @param logfile: name of a file to use for logging purposes @type logfile: String @param path_lookup: If the binary is not fully specified then look for it in PATH @type path_lookup: Boolean @param pre_exec: A function to be called with no arguments just prior to the exec call. @type pre_exec: callable @param close_fds: If True, then close all file descriptors except those referenced by fd_pipes (default is True). @type close_fds: Boolean @param unshare_net: If True, networking will be unshared from the spawned process @type unshare_net: Boolean @param unshare_ipc: If True, IPC will be unshared from the spawned process @type unshare_ipc: Boolean @param cgroup: CGroup path to bind the process to @type cgroup: String logfile requires stdout and stderr to be assigned to this process (ie not pointed somewhere else.) """ # mycommand is either a str or a list if isinstance(mycommand, basestring): mycommand = mycommand.split() if sys.hexversion < 0x3000000: # Avoid a potential UnicodeEncodeError from os.execve(). env_bytes = {} for k, v in env.items(): env_bytes[_unicode_encode(k, encoding=_encodings['content'])] = \ _unicode_encode(v, encoding=_encodings['content']) env = env_bytes del env_bytes # If an absolute path to an executable file isn't given # search for it unless we've been told not to. binary = mycommand[0] if binary not in (BASH_BINARY, SANDBOX_BINARY, FAKEROOT_BINARY) and \ (not os.path.isabs(binary) or not os.path.isfile(binary) or not os.access(binary, os.X_OK)): binary = path_lookup and find_binary(binary) or None if not binary: raise CommandNotFound(mycommand[0]) # If we haven't been told what file descriptors to use # default to propagating our stdin, stdout and stderr. if fd_pipes is None: fd_pipes = { 0:portage._get_stdin().fileno(), 1:sys.__stdout__.fileno(), 2:sys.__stderr__.fileno(), } # mypids will hold the pids of all processes created. mypids = [] if logfile: # Using a log file requires that stdout and stderr # are assigned to the process we're running. if 1 not in fd_pipes or 2 not in fd_pipes: raise ValueError(fd_pipes) # Create a pipe (pr, pw) = os.pipe() # Create a tee process, giving it our stdout and stderr # as well as the read end of the pipe. mypids.extend(spawn(('tee', '-i', '-a', logfile), returnpid=True, fd_pipes={0:pr, 1:fd_pipes[1], 2:fd_pipes[2]})) # We don't need the read end of the pipe, so close it. os.close(pr) # Assign the write end of the pipe to our stdout and stderr. fd_pipes[1] = pw fd_pipes[2] = pw # This caches the libc library lookup in the current # process, so that it's only done once rather than # for each child process. if unshare_net or unshare_ipc: find_library("c") parent_pid = os.getpid() pid = None try: pid = os.fork() if pid == 0: try: _exec(binary, mycommand, opt_name, fd_pipes, env, gid, groups, uid, umask, pre_exec, close_fds, unshare_net, unshare_ipc, cgroup) except SystemExit: raise except Exception as e: # We need to catch _any_ exception so that it doesn't # propagate out of this function and cause exiting # with anything other than os._exit() writemsg("%s:\n %s\n" % (e, " ".join(mycommand)), noiselevel=-1) traceback.print_exc() sys.stderr.flush() finally: if pid == 0 or (pid is None and os.getpid() != parent_pid): # Call os._exit() from a finally block in order # to suppress any finally blocks from earlier # in the call stack (see bug #345289). This # finally block has to be setup before the fork # in order to avoid a race condition. os._exit(1) if not isinstance(pid, int): raise AssertionError("fork returned non-integer: %s" % (repr(pid),)) # Add the pid to our local and the global pid lists. mypids.append(pid) # If we started a tee process the write side of the pipe is no # longer needed, so close it. if logfile: os.close(pw) # If the caller wants to handle cleaning up the processes, we tell # it about all processes that were created. if returnpid: return mypids # Otherwise we clean them up. while mypids: # Pull the last reader in the pipe chain. If all processes # in the pipe are well behaved, it will die when the process # it is reading from dies. pid = mypids.pop(0) # and wait for it. retval = os.waitpid(pid, 0)[1] if retval: # If it failed, kill off anything else that # isn't dead yet. for pid in mypids: # With waitpid and WNOHANG, only check the # first element of the tuple since the second # element may vary (bug #337465). if os.waitpid(pid, os.WNOHANG)[0] == 0: os.kill(pid, signal.SIGTERM) os.waitpid(pid, 0) # If it got a signal, return the signal that was sent. if (retval & 0xff): return ((retval & 0xff) << 8) # Otherwise, return its exit code. return (retval >> 8) # Everything succeeded return 0 def _exec(binary, mycommand, opt_name, fd_pipes, env, gid, groups, uid, umask, pre_exec, close_fds, unshare_net, unshare_ipc, cgroup): """ Execute a given binary with options @param binary: Name of program to execute @type binary: String @param mycommand: Options for program @type mycommand: String @param opt_name: Name of process (defaults to binary) @type opt_name: String @param fd_pipes: Mapping pipes to destination; { 0:0, 1:1, 2:2 } @type fd_pipes: Dictionary @param env: Key,Value mapping for Environmental Variables @type env: Dictionary @param gid: Group ID to run the process under @type gid: Integer @param groups: Groups the Process should be in. @type groups: Integer @param uid: User ID to run the process under @type uid: Integer @param umask: an int representing a unix umask (see man chmod for umask details) @type umask: Integer @param pre_exec: A function to be called with no arguments just prior to the exec call. @type pre_exec: callable @param unshare_net: If True, networking will be unshared from the spawned process @type unshare_net: Boolean @param unshare_ipc: If True, IPC will be unshared from the spawned process @type unshare_ipc: Boolean @param cgroup: CGroup path to bind the process to @type cgroup: String @rtype: None @return: Never returns (calls os.execve) """ # If the process we're creating hasn't been given a name # assign it the name of the executable. if not opt_name: if binary is portage._python_interpreter: # NOTE: PyPy 1.7 will die due to "libary path not found" if argv[0] # does not contain the full path of the binary. opt_name = binary else: opt_name = os.path.basename(binary) # Set up the command's argument list. myargs = [opt_name] myargs.extend(mycommand[1:]) # Avoid a potential UnicodeEncodeError from os.execve(). myargs = [_unicode_encode(x, encoding=_encodings['fs'], errors='strict') for x in myargs] # Use default signal handlers in order to avoid problems # killing subprocesses as reported in bug #353239. signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGTERM, signal.SIG_DFL) # Quiet killing of subprocesses by SIGPIPE (see bug #309001). signal.signal(signal.SIGPIPE, signal.SIG_DFL) # Avoid issues triggered by inheritance of SIGQUIT handler from # the parent process (see bug #289486). signal.signal(signal.SIGQUIT, signal.SIG_DFL) _setup_pipes(fd_pipes, close_fds=close_fds, inheritable=True) # Add to cgroup # it's better to do it from the child since we can guarantee # it is done before we start forking children if cgroup: with open(os.path.join(cgroup, 'cgroup.procs'), 'a') as f: f.write('%d\n' % os.getpid()) # Unshare (while still uid==0) if unshare_net or unshare_ipc: filename = find_library("c") if filename is not None: libc = LoadLibrary(filename) if libc is not None: CLONE_NEWIPC = 0x08000000 CLONE_NEWNET = 0x40000000 flags = 0 if unshare_net: flags |= CLONE_NEWNET if unshare_ipc: flags |= CLONE_NEWIPC try: if libc.unshare(flags) != 0: writemsg("Unable to unshare: %s\n" % ( errno.errorcode.get(ctypes.get_errno(), '?')), noiselevel=-1) else: if unshare_net: # 'up' the loopback IFF_UP = 0x1 ifreq = struct.pack('16sh', b'lo', IFF_UP) SIOCSIFFLAGS = 0x8914 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) try: fcntl.ioctl(sock, SIOCSIFFLAGS, ifreq) except IOError as e: writemsg("Unable to enable loopback interface: %s\n" % ( errno.errorcode.get(e.errno, '?')), noiselevel=-1) sock.close() except AttributeError: # unshare() not supported by libc pass # Set requested process permissions. if gid: # Cast proxies to int, in case it matters. os.setgid(int(gid)) if groups: os.setgroups(groups) if uid: # Cast proxies to int, in case it matters. os.setuid(int(uid)) if umask: os.umask(umask) if pre_exec: pre_exec() # And switch to the new process. os.execve(binary, myargs, env) def _setup_pipes(fd_pipes, close_fds=True, inheritable=None): """Setup pipes for a forked process. Even when close_fds is False, file descriptors referenced as values in fd_pipes are automatically closed if they do not also occur as keys in fd_pipes. It is assumed that the caller will explicitly add them to the fd_pipes keys if they are intended to remain open. This allows for convenient elimination of unnecessary duplicate file descriptors. WARNING: When not followed by exec, the close_fds behavior can trigger interference from destructors that close file descriptors. This interference happens when the garbage collector intermittently executes such destructors after their corresponding file descriptors have been re-used, leading to intermittent "[Errno 9] Bad file descriptor" exceptions in forked processes. This problem has been observed with PyPy 1.8, and also with CPython under some circumstances (as triggered by xmpppy in bug #374335). In order to close a safe subset of file descriptors, see portage.locks._close_fds(). NOTE: When not followed by exec, even when close_fds is False, it's still possible for dup2() calls to cause interference in a way that's similar to the way that close_fds interferes (since dup2() has to close the target fd if it happens to be open). It's possible to avoid such interference by using allocated file descriptors as the keys in fd_pipes. For example: pr, pw = os.pipe() fd_pipes[pw] = pw By using the allocated pw file descriptor as the key in fd_pipes, it's not necessary for dup2() to close a file descriptor (it actually does nothing in this case), which avoids possible interference. """ reverse_map = {} # To protect from cases where direct assignment could # clobber needed fds ({1:2, 2:1}) we create a reverse map # in order to know when it's necessary to create temporary # backup copies with os.dup(). for newfd, oldfd in fd_pipes.items(): newfds = reverse_map.get(oldfd) if newfds is None: newfds = [] reverse_map[oldfd] = newfds newfds.append(newfd) # Assign newfds via dup2(), making temporary backups when # necessary, and closing oldfd if the caller has not # explicitly requested for it to remain open by adding # it to the keys of fd_pipes. while reverse_map: oldfd, newfds = reverse_map.popitem() old_fdflags = None for newfd in newfds: if newfd in reverse_map: # Make a temporary backup before re-assignment, assuming # that backup_fd won't collide with a key in reverse_map # (since all of the keys correspond to open file # descriptors, and os.dup() only allocates a previously # unused file discriptors). backup_fd = os.dup(newfd) reverse_map[backup_fd] = reverse_map.pop(newfd) if oldfd != newfd: os.dup2(oldfd, newfd) if _set_inheritable is not None: # Don't do this unless _set_inheritable is available, # since it's used below to ensure correct state, and # otherwise /dev/null stdin fails to inherit (at least # with Python versions from 3.1 to 3.3). if old_fdflags is None: old_fdflags = fcntl.fcntl(oldfd, fcntl.F_GETFD) fcntl.fcntl(newfd, fcntl.F_SETFD, old_fdflags) if _set_inheritable is not None: inheritable_state = None if not (old_fdflags is None or _FD_CLOEXEC is None): inheritable_state = not bool(old_fdflags & _FD_CLOEXEC) if inheritable is not None: if inheritable_state is not inheritable: _set_inheritable(newfd, inheritable) elif newfd in (0, 1, 2): if inheritable_state is not True: _set_inheritable(newfd, True) if oldfd not in fd_pipes: # If oldfd is not a key in fd_pipes, then it's safe # to close now, since we've already made all of the # requested duplicates. This also closes every # backup_fd that may have been created on previous # iterations of this loop. os.close(oldfd) if close_fds: # Then close _all_ fds that haven't been explicitly # requested to be kept open. for fd in get_open_fds(): if fd not in fd_pipes: try: os.close(fd) except OSError: pass def find_binary(binary): """ Given a binary name, find the binary in PATH @param binary: Name of the binary to find @type string @rtype: None or string @return: full path to binary or None if the binary could not be located. """ paths = os.environ.get("PATH", "") if sys.hexversion >= 0x3000000 and isinstance(binary, bytes): # return bytes when input is bytes paths = paths.encode(sys.getfilesystemencoding(), 'surrogateescape') paths = paths.split(b':') else: paths = paths.split(':') for path in paths: filename = _os.path.join(path, binary) if _os.access(filename, os.X_OK) and _os.path.isfile(filename): return filename return None
gpl-2.0
croomjm/Cubli
Phidgets/Phidgets/Devices/Stepper.py
11
37931
"""Copyright 2012 Phidgets Inc. This work is licensed under the Creative Commons Attribution 2.5 Canada License. To view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/ca/ """ __author__ = 'Adam Stelmack' __version__ = '2.1.8' __date__ = 'May 17 2010' import threading from ctypes import * from Phidgets.PhidgetLibrary import PhidgetLibrary from Phidgets.Phidget import Phidget from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException from Phidgets.Events.Events import CurrentChangeEventArgs, InputChangeEventArgs, StepperPositionChangeEventArgs, VelocityChangeEventArgs import sys class Stepper(Phidget): """This class represents a Phidget Stepper Controller. All methods to to control a stepper controller and read back stepper data are implemented in this class. The Phidget Stepper is able to control 1 or more Stepper motors. Motor Acceleration and Velocity are controllable, and micro-stepping is used for bipolar motors. The type and number of motors that can be controlled depend on the Stepper Controller. Digital inputs are available on select Phidget Stepper Controllers. See your device's User Guide for more specific API details, technical information, and revision details. The User Guide, along with other resources, can be found on the product page for your device. Extends: Phidget """ def __init__(self): """The Constructor Method for the Stepper Class Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found """ Phidget.__init__(self) self.__inputChange = None self.__velocityChange = None self.__positionChange = None self.__currentChange = None self.__onInputChange = None self.__onVelocityChange = None self.__onPositionChange = None self.__onCurrentChange = None try: PhidgetLibrary.getDll().CPhidgetStepper_create(byref(self.handle)) except RuntimeError: raise if sys.platform == 'win32': self.__INPUTCHANGEHANDLER = WINFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_int) self.__VELOCITYCHANGEHANDLER = WINFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_double) self.__POSITIONCHANGEHANDLER = WINFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_longlong) self.__CURRENTCHANGEHANDLER = WINFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_double) elif sys.platform == 'darwin' or sys.platform == 'linux2': self.__INPUTCHANGEHANDLER = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_int) self.__VELOCITYCHANGEHANDLER = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_double) self.__POSITIONCHANGEHANDLER = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_longlong) self.__CURRENTCHANGEHANDLER = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_double) def __del__(self): """The Destructor Method for the Stepper Class """ Phidget.dispose(self) def getInputCount(self): """Returns the number of digital inputs. Not all Stepper Controllers have digital inputs. Returns: The number of digital inputs available <int>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached. """ inputCount = c_int() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getInputCount(self.handle, byref(inputCount)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return inputCount.value def getInputState(self, index): """Returns the state of a digital input. True means that the input is activated, and False indicated the default state. Parameters: index<int>: The index of the input. Returns: The state of the input <boolean>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid. """ inputState = c_int() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getInputState(self.handle, c_int(index), byref(inputState)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: if inputState.value == 1: return True else: return False def __nativeInputChangeEvent(self, handle, usrptr, index, value): if self.__inputChange != None: if value == 1: state = True else: state = False self.__inputChange(InputChangeEventArgs(self, index, state)) return 0 def setOnInputChangeHandler(self, inputChangeHandler): """Set the InputChange event handler The input change handler is a method that will be called when an input on this Stepper Controller board has changed. Parameters: inputChangeHandler: hook to the inputChangeHandler callback function. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException """ if inputChangeHandler == None: self.__inputChange = None self.__onInputChange = None else: self.__inputChange = inputChangeHandler self.__onInputChange = self.__INPUTCHANGEHANDLER(self.__nativeInputChangeEvent) try: result = PhidgetLibrary.getDll().CPhidgetStepper_set_OnInputChange_Handler(self.handle, self.__onInputChange, None) except RuntimeError: self.__inputChange = None self.__onInputChange = None raise if result > 0: raise PhidgetException(result) def getMotorCount(self): """Returns the number of stepper motors supported by this Phidget. This does not neccesarily correspond to the number of motors actually attached to the board. Returns: The number of supported motors <int>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached. """ motorCount = c_int() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getMotorCount(self.handle, byref(motorCount)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return motorCount.value def getAcceleration(self, index): """Returns a motor's acceleration. The valid range is between getAccelerationMin and getAccelerationMax, and refers to how fast the Stepper Controller will change the speed of a motor. This value is in (micro)steps per second squared. The step unit will depend on the Stepper Controller. For example, the Bipolar Stepper controller has an accuracy of 16th steps, so this value would be in 16th steps per second squared. Parameters: index<int>: INdex of a motor. Returns: The acceleration of the motor <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid, or if the acceleration is unknown. """ accel = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getAcceleration(self.handle, c_int(index), byref(accel)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return accel.value def setAcceleration(self, index, value): """Sets a motor's acceleration. The valid range is between getAccelerationMin and getAccelerationMax, and refers to how fast the Stepper Controller will change the speed of a motor. This value is in (micro)steps per second squared. The step unit will depend on the Stepper Controller. For example, the Bipolar Stepper controller has an accuracy of 16th steps, so this value would be in 16th steps per second squared. Parameters: index<int>: Index of the motor. value<double>: Desired acceleration for that motor. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid, or if the acceleration is unknown. """ try: result = PhidgetLibrary.getDll().CPhidgetStepper_setAcceleration(self.handle, c_int(index), c_double(value)) except RuntimeError: raise if result > 0: raise PhidgetException(result) def getAccelerationMax(self, index): """Returns the maximum acceleration that a motor will accept, or return. This value uses the same units as setAcceleration/getAcceleration. Parameters: index<int>: Index of the motor. Returns: The maximum allowable acceleration <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or the index is invalid. """ accelMax = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getAccelerationMax(self.handle, c_int(index), byref(accelMax)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return accelMax.value def getAccelerationMin(self, index): """Returns the minimum acceleration that a motor will accept, or return. This value uses the same units as setAcceleration/getAcceleration. Parameters: index<int>: Index of the motor. Returns: The minumum allowable acceleration <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid. """ accelMin = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getAccelerationMin(self.handle, c_int(index), byref(accelMin)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return accelMin.value def getVelocityLimit(self, index): """Returns a motor's velocity limit. This is the maximum velocity that the motor will turn at. The valid range is between getVelocityMin and getVelocityMax, with 0 being stopped. This value is in (micro)steps per second. The step unit will depend on the Stepper Controller. For example, the Bipolar Stepper controller has an accuracy of 16th steps, so this value would be in 16th steps per second. Parameters: index<int>: The index of the motor. Returns: The maximum speed the motor will run at <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid. """ velocityLimit = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getVelocityLimit(self.handle, c_int(index), byref(velocityLimit)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return velocityLimit.value def setVelocityLimit(self, index, value): """Sets a motor's velocity limit. This is the maximum velocity that the motor will turn at. The valid range is between getVelocityMin and getVelocityMax, with 0 being stopped. This value is in (micro)steps per second. The step unit will depend on the Stepper Controller. For example, the Bipolar Stepper controller has an accuracy of 16th steps, so this value would be in 16th steps per second. Parameters: index<int>: The index of the motor. value<double>: Desired velocity for the motor. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index or velocity are invalid. """ try: result = PhidgetLibrary.getDll().CPhidgetStepper_setVelocityLimit(self.handle, c_int(index), c_double(value)) except RuntimeError: raise if result > 0: raise PhidgetException(result) def getVelocity(self, index): """Returns a motor's current velocity. The valid range is between getVelocityMin and getVelocityMax, with 0 being stopped. This value is in (micro)steps per second. The step unit will depend on the Stepper Controller. For example, the Bipolar Stepper controller has an accuracy of 16th steps, so this value would be in 16th steps per second. Parameters: index<int>: The index of the motor. Returns: The current velocity of the motor <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid, or if the velocity in unknown. """ velocity = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getVelocity(self.handle, c_int(index), byref(velocity)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return velocity.value def getVelocityMax(self, index): """Returns the maximum velocity that a stepper motor will accept, or return. This value uses the same units as setVelocityLimit/getVelocityLimit and getVelocity. Parameters: index<int>: The index of the motor. Returns: The maximum allowable velocity of the motor <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid. """ velocityMax = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getVelocityMax(self.handle, c_int(index), byref(velocityMax)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return velocityMax.value def getVelocityMin(self, index): """Returns the minimum velocity that a stepper motor will accept, or return. This value uses the same units as setVelocityLimit/getVelocityLimit and getVelocity. Parameters: index<int>: The index of the motor. Returns: The minimum allowable velocity of the motor <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid. """ velocityMin = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getVelocityMin(self.handle, c_int(index), byref(velocityMin)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return velocityMin.value def __nativeVelocityChangeEvent(self, handle, usrptr, index, value): if self.__velocityChange != None: self.__velocityChange(VelocityChangeEventArgs(self, index, value)) return 0 def setOnVelocityChangeHandler(self, velocityChangeHandler): """Sets the VelocityChange event handler. The velocity change handler is a method that will be called when the stepper velocity has changed. Parameters: velocityChangeHandler: hook to the velocityChangeHandler callback function. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException """ if velocityChangeHandler == None: self.__velocityChange = None self.__onVelocityChange = None else: self.__velocityChange = velocityChangeHandler self.__onVelocityChange = self.__VELOCITYCHANGEHANDLER(self.__nativeVelocityChangeEvent) try: result = PhidgetLibrary.getDll().CPhidgetStepper_set_OnVelocityChange_Handler(self.handle, self.__onVelocityChange, None) except RuntimeError: self.__velocityChange = None self.__onVelocityChange = None raise if result > 0: raise PhidgetException(result) def getTargetPosition(self, index): """Returns a motor's target position. This is the position that the motor wants to be at. If the motor is not moving, it probably has reached the target position, and this will match getCurrentPosition. The valid range is between getPositionMin and getPositionMax. This value is in (micro)steps. The step unit will depend on the Stepper Controller. For example, the Bipolar Stepper controller has an accuracy of 16th steps, so this value would be in 16th steps. Parameters: index<int>: The index of the motor. Returns: The target position of the motor <longlong>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid, or if the position in unknown. """ targetPosition = c_longlong() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getTargetPosition(self.handle, c_int(index), byref(targetPosition)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return targetPosition.value def setTargetPosition(self, index, value): """Sets a motor's target position. Use this is set the target position for the stepper. If the stepper is engaged (getEngaged) it will start moving towards this target position. The valid range is between getPositionMin and getPositionMax. This value is in (micro)steps. The step unit will depend on the Stepper Controller. For example, the Bipolar Stepper controller has an accuracy of 16th steps, so this value would be in 16th steps. Parameters: index<int>: The index of the motor. value<longlong>: The desired position for the motor. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index or position are invalid. """ try: result = PhidgetLibrary.getDll().CPhidgetStepper_setTargetPosition(self.handle, c_int(index), c_longlong(value)) except RuntimeError: raise if result > 0: raise PhidgetException(result) def getCurrentPosition(self, index): """Returns a motor's current position. This is the actual step position that the motor is at right now. The valid range is between getPositionMin and getPositionMax. This value is in (micro)steps. The step unit will depend on the Stepper Controller. For example, the Bipolar Stepper controller has an accuracy of 16th steps, so this value would be in 16th steps. Parameters: index<int>: Index of the motor. Returns: The current position of the motor <longlong>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid. """ currentPosition = c_longlong() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getCurrentPosition(self.handle, c_int(index), byref(currentPosition)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return currentPosition.value def setCurrentPosition(self, index, value): """Sets a motor's current position. Use this is (re)set the current physical position of the motor to a specific position value. This does not move the motor, and if the motor is moving, calling this will cause it to stop moving. Use setTargetPosition to move the motor to a position. The valid range is between getPositionMin and getPositionMax. This value is in (micro)steps. The step unit will depend on the Stepper Controller. For example, the Bipolar Stepper controller has an accuracy of 16th steps, so this value would be in 16th steps. Parameters: index<int>: Index of the motor. value<longlong>: The current position of the motor. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index or position are invalid. """ try: result = PhidgetLibrary.getDll().CPhidgetStepper_setCurrentPosition(self.handle, c_int(index), c_longlong(value)) except RuntimeError: raise if result > 0: raise PhidgetException(result) def getPositionMax(self, index): """Returns the maximum position that a stepper motor will accept, or return. This value uses the same usits as setTargetPosition/getTargetPosition and setCurrentPosition/getCurrentPosition. Parameters: index<int>: Index of the motor. Returns: The maximum allowable position <longlong>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid. """ positionMax = c_longlong() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getPositionMax(self.handle, c_int(index), byref(positionMax)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return positionMax.value def getPositionMin(self, index): """Returns the minimum position that a stepper motor will accept, or return. This value uses the same usits as setTargetPosition/getTargetPosition and setCurrentPosition/getCurrentPosition. Parameters: index<int>: Index of the motor. Returns: The minimum allowable position <longlong>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is invalid. """ positionMin = c_longlong() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getPositionMin(self.handle, c_int(index), byref(positionMin)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return positionMin.value def __nativePositionChangeEvent(self, handle, usrptr, index, value): if self.__positionChange != None: self.__positionChange(StepperPositionChangeEventArgs(self, index, value)) return 0 def setOnPositionChangeHandler(self, positionChangeHandler): """Sets the PositionChange event handler The position change handler is a method that will be called when the stepper position has changed. Parameters: positionChangeHandler: hook to the positionChangeHandler callback function. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException """ if positionChangeHandler == None: self.__positionChange = None self.__onPositionChange = None else: self.__positionChange = positionChangeHandler self.__onPositionChange = self.__POSITIONCHANGEHANDLER(self.__nativePositionChangeEvent) try: result = PhidgetLibrary.getDll().CPhidgetStepper_set_OnPositionChange_Handler(self.handle, self.__onPositionChange, None) except RuntimeError: self.__positionChange = None self.__onPositionChange = None raise if result > 0: raise PhidgetException(result) def getCurrentLimit(self, index): """Gets a motor's current usage limit. The valid range is between getCurrentMin and getCurrentMax. This gets the maximum current that a motor will be allowed to draw. Use this with the Bipolar stepper controller to get smooth micro stepping - see the product manual for more details. This value is in Amps. Note that this is not supported on all stepper controllers. Parameters: index<int>: Index of the motor. Returns: The Current limit for the motor <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, if the index is invalid, if the value is unknown, or if this is not supported. """ currentLimit = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getCurrentLimit(self.handle, c_int(index), byref(currentLimit)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return currentLimit.value def setCurrentLimit(self, index, value): """Sets a motor's current usage limit. The valid range is between getCurrentMin and getCurrentMax. This sets the maximum current that a motor will be allowed to draw. Use this with the Bipolar stepper controller to get smooth micro stepping - see the product manual for more details. This value is in Amps. Note that this is not supported on all stepper controllers. Parameters: index<int>: Index of the motor. value<double>: The desired Current limit for the motor. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, if the index or value are invalid, or if this is not supported. """ try: result = PhidgetLibrary.getDll().CPhidgetStepper_setCurrentLimit(self.handle, c_int(index), c_double(value)) except RuntimeError: raise if result > 0: raise PhidgetException(result) def getCurrent(self, index): """Returns a motor's current usage. The valid range is between getCurrentMin and getCurrentMax. This value is in Amps. Note that this is not supported on all stepper controllers. Parameters: index<int>: Index of the motor. Returns: The Current usage for the motor <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, if the index is invalid, if the value is unknown, or if this is not supported. """ current = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getCurrent(self.handle, c_int(index), byref(current)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return current.value def getCurrentMax(self, index): """Returns the maximum current that a stepper motor will accept, or return. This value is in Amps. Parameters: index<int>: Index of the motor. Returns: The Maximum allowable Current usage for the motor <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, if the index is invalid, or if this is not supported. """ currentMax = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getCurrentMax(self.handle, c_int(index), byref(currentMax)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return currentMax.value def getCurrentMin(self, index): """Returns the minimum current that a stepper motor will accept, or return. This value is in Amps. Parameters: index<int>: Index of the motor. Returns: The Minimum allowable Current usage for the motor <double>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, if the index is invalid, or if this is not supported. """ currentMin = c_double() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getCurrentMin(self.handle, c_int(index), byref(currentMin)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: return currentMin.value def __nativeCurrentChangeEvent(self, handle, usrptr, index, value): if self.__currentChange != None: self.__currentChange(CurrentChangeEventArgs(self, index, value)) return 0 def setOnCurrentChangeHandler(self, currentChangeHandler): """Sets the CurrentChange event handler The current change handler is a method that will be called when the stepper current has changed. Note that not all stepper controllers support current sensing. Parameters: currentChangeHandler: hook to the currentChangeHandler callback function. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this is not supported. """ if currentChangeHandler == None: self.__currentChange = None self.__onCurrentChange = None else: self.__currentChange = currentChangeHandler self.__onCurrentChange = self.__CURRENTCHANGEHANDLER(self.__nativeCurrentChangeEvent) try: result = PhidgetLibrary.getDll().CPhidgetStepper_set_OnCurrentChange_Handler(self.handle, self.__onCurrentChange, None) except RuntimeError: self.__currentChange = None self.__onCurrentChange = None raise if result > 0: raise PhidgetException(result) def getEngaged(self, index): """Returns the engaged state of a motor. Parameters: index<int>: Index of the motor. Returns: The engaged state for the motor <boolean>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is out of range. """ engagedState = c_int() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getEngaged(self.handle, c_int(index), byref(engagedState)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: if engagedState.value == 1: return True else: return False def setEngaged(self, index, state): """Engage or disengage a motor. This engages or disengages the stepper motor. The motors are by default disengaged when the stepper controller is plugged in. When the stepper is disengaged, position, velocity, etc. can all be set, but the motor will not start moving until it is engaged. If position is read when a motor is disengaged, it will throw an exception. Parameters: index<int>: Index of the motor. state<boolean>: The desired engaged state for the motor. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is out of range. """ if state == True: value = 1 else: value = 0 try: result = PhidgetLibrary.getDll().CPhidgetStepper_setEngaged(self.handle, c_int(index), c_int(value)) except RuntimeError: raise if result > 0: raise PhidgetException(result) def getStopped(self, index): """Returns the stopped state of a motor. Use this to determine if the motor is moving and/or up to date with the latest commands you have sent. If this is true, the motor is guaranteed to be stopped and to have processed every command issued. Generally, this would be polled after a target position is set to wait until that position is reached. Parameters: index<int>: Index of the motor. Returns: The stopped state of the motor <boolean>. Exceptions: RuntimeError - If current platform is not supported/phidget c dll cannot be found PhidgetException: If this Phidget is not opened and attached, or if the index is out of range. """ stoppedState = c_int() try: result = PhidgetLibrary.getDll().CPhidgetStepper_getStopped(self.handle, c_int(index), byref(stoppedState)) except RuntimeError: raise if result > 0: raise PhidgetException(result) else: if stoppedState.value == 1: return True else: return False
mit
mlperf/training_results_v0.5
v0.5.0/google/cloud_v2.8/resnet-tpuv2-8/code/resnet/model/models/official/utils/logs/hooks_helper.py
8
5801
# 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. # ============================================================================== """Hooks helper to return a list of TensorFlow hooks for training by name. More hooks can be added to this set. To add a new hook, 1) add the new hook to the registry in HOOKS, 2) add a corresponding function that parses out necessary parameters. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # pylint: disable=g-bad-import-order from official.utils.logs import hooks from official.utils.logs import logger from official.utils.logs import metric_hook _TENSORS_TO_LOG = dict((x, x) for x in ['learning_rate', 'cross_entropy', 'train_accuracy']) def get_train_hooks(name_list, use_tpu=False, **kwargs): """Factory for getting a list of TensorFlow hooks for training by name. Args: name_list: a list of strings to name desired hook classes. Allowed: LoggingTensorHook, ProfilerHook, ExamplesPerSecondHook, which are defined as keys in HOOKS use_tpu: Boolean of whether computation occurs on a TPU. This will disable hooks altogether. **kwargs: a dictionary of arguments to the hooks. Returns: list of instantiated hooks, ready to be used in a classifier.train call. Raises: ValueError: if an unrecognized name is passed. """ if not name_list: return [] if use_tpu: tf.logging.warning("hooks_helper received name_list `{}`, but a TPU is " "specified. No hooks will be used.".format(name_list)) return [] train_hooks = [] for name in name_list: hook_name = HOOKS.get(name.strip().lower()) if hook_name is None: raise ValueError('Unrecognized training hook requested: {}'.format(name)) else: train_hooks.append(hook_name(**kwargs)) return train_hooks def get_logging_tensor_hook(every_n_iter=100, tensors_to_log=None, **kwargs): # pylint: disable=unused-argument """Function to get LoggingTensorHook. Args: every_n_iter: `int`, print the values of `tensors` once every N local steps taken on the current worker. tensors_to_log: List of tensor names or dictionary mapping labels to tensor names. If not set, log _TENSORS_TO_LOG by default. **kwargs: a dictionary of arguments to LoggingTensorHook. Returns: Returns a LoggingTensorHook with a standard set of tensors that will be printed to stdout. """ if tensors_to_log is None: tensors_to_log = _TENSORS_TO_LOG return tf.train.LoggingTensorHook( tensors=tensors_to_log, every_n_iter=every_n_iter) def get_profiler_hook(model_dir, save_steps=1000, **kwargs): # pylint: disable=unused-argument """Function to get ProfilerHook. Args: model_dir: The directory to save the profile traces to. save_steps: `int`, print profile traces every N steps. **kwargs: a dictionary of arguments to ProfilerHook. Returns: Returns a ProfilerHook that writes out timelines that can be loaded into profiling tools like chrome://tracing. """ return tf.train.ProfilerHook(save_steps=save_steps, output_dir=model_dir) def get_examples_per_second_hook(every_n_steps=100, batch_size=128, warm_steps=5, **kwargs): # pylint: disable=unused-argument """Function to get ExamplesPerSecondHook. Args: every_n_steps: `int`, print current and average examples per second every N steps. batch_size: `int`, total batch size used to calculate examples/second from global time. warm_steps: skip this number of steps before logging and running average. **kwargs: a dictionary of arguments to ExamplesPerSecondHook. Returns: Returns a ProfilerHook that writes out timelines that can be loaded into profiling tools like chrome://tracing. """ return hooks.ExamplesPerSecondHook( batch_size=batch_size, every_n_steps=every_n_steps, warm_steps=warm_steps, metric_logger=logger.get_benchmark_logger()) def get_logging_metric_hook(tensors_to_log=None, every_n_secs=600, **kwargs): # pylint: disable=unused-argument """Function to get LoggingMetricHook. Args: tensors_to_log: List of tensor names or dictionary mapping labels to tensor names. If not set, log _TENSORS_TO_LOG by default. every_n_secs: `int`, the frequency for logging the metric. Default to every 10 mins. Returns: Returns a LoggingMetricHook that saves tensor values in a JSON format. """ if tensors_to_log is None: tensors_to_log = _TENSORS_TO_LOG return metric_hook.LoggingMetricHook( tensors=tensors_to_log, metric_logger=logger.get_benchmark_logger(), every_n_secs=every_n_secs) # A dictionary to map one hook name and its corresponding function HOOKS = { 'loggingtensorhook': get_logging_tensor_hook, 'profilerhook': get_profiler_hook, 'examplespersecondhook': get_examples_per_second_hook, 'loggingmetrichook': get_logging_metric_hook, }
apache-2.0
nitinitprof/odoo
addons/l10n_bo/__openerp__.py
259
1698
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012 Cubic ERP - Teradata SAC (<http://cubicerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Bolivia Localization Chart Account", "version": "1.0", "description": """ Bolivian accounting chart and tax localization. Plan contable boliviano e impuestos de acuerdo a disposiciones vigentes """, "author": "Cubic ERP", "website": "http://cubicERP.com", "category": "Localization/Account Charts", "depends": [ "account_chart", ], "data":[ "account_tax_code.xml", "l10n_bo_chart.xml", "account_tax.xml", "l10n_bo_wizard.xml", ], "demo_xml": [ ], "data": [ ], "active": False, "installable": True, "certificate" : "", } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
Deepakpatle/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/layout_tests/models/test_expectations.py
117
46271
# 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. """A helper class for reading in and dealing with tests expectations for layout tests. """ import logging import re from webkitpy.layout_tests.models.test_configuration import TestConfigurationConverter _log = logging.getLogger(__name__) # Test expectation and modifier constants. # # FIXME: range() starts with 0 which makes if expectation checks harder # as PASS is 0. (PASS, FAIL, TEXT, IMAGE, IMAGE_PLUS_TEXT, AUDIO, TIMEOUT, CRASH, SKIP, WONTFIX, SLOW, REBASELINE, MISSING, FLAKY, NOW, NONE) = range(16) # FIXME: Perhas these two routines should be part of the Port instead? BASELINE_SUFFIX_LIST = ('png', 'wav', 'txt') class ParseError(Exception): def __init__(self, warnings): super(ParseError, self).__init__() self.warnings = warnings def __str__(self): return '\n'.join(map(str, self.warnings)) def __repr__(self): return 'ParseError(warnings=%s)' % self.warnings class TestExpectationParser(object): """Provides parsing facilities for lines in the test_expectation.txt file.""" DUMMY_BUG_MODIFIER = "bug_dummy" BUG_MODIFIER_PREFIX = 'bug' BUG_MODIFIER_REGEX = 'bug\d+' REBASELINE_MODIFIER = 'rebaseline' PASS_EXPECTATION = 'pass' SKIP_MODIFIER = 'skip' SLOW_MODIFIER = 'slow' WONTFIX_MODIFIER = 'wontfix' TIMEOUT_EXPECTATION = 'timeout' MISSING_BUG_WARNING = 'Test lacks BUG modifier.' def __init__(self, port, full_test_list, allow_rebaseline_modifier): self._port = port self._test_configuration_converter = TestConfigurationConverter(set(port.all_test_configurations()), port.configuration_specifier_macros()) self._full_test_list = full_test_list self._allow_rebaseline_modifier = allow_rebaseline_modifier def parse(self, filename, expectations_string): expectation_lines = [] line_number = 0 for line in expectations_string.split("\n"): line_number += 1 test_expectation = self._tokenize_line(filename, line, line_number) self._parse_line(test_expectation) expectation_lines.append(test_expectation) return expectation_lines def expectation_for_skipped_test(self, test_name): if not self._port.test_exists(test_name): _log.warning('The following test %s from the Skipped list doesn\'t exist' % test_name) expectation_line = TestExpectationLine() expectation_line.original_string = test_name expectation_line.modifiers = [TestExpectationParser.DUMMY_BUG_MODIFIER, TestExpectationParser.SKIP_MODIFIER] # FIXME: It's not clear what the expectations for a skipped test should be; the expectations # might be different for different entries in a Skipped file, or from the command line, or from # only running parts of the tests. It's also not clear if it matters much. expectation_line.modifiers.append(TestExpectationParser.WONTFIX_MODIFIER) expectation_line.name = test_name # FIXME: we should pass in a more descriptive string here. expectation_line.filename = '<Skipped file>' expectation_line.line_number = 0 expectation_line.expectations = [TestExpectationParser.PASS_EXPECTATION] self._parse_line(expectation_line) return expectation_line def _parse_line(self, expectation_line): if not expectation_line.name: return if not self._check_test_exists(expectation_line): return expectation_line.is_file = self._port.test_isfile(expectation_line.name) if expectation_line.is_file: expectation_line.path = expectation_line.name else: expectation_line.path = self._port.normalize_test_name(expectation_line.name) self._collect_matching_tests(expectation_line) self._parse_modifiers(expectation_line) self._parse_expectations(expectation_line) def _parse_modifiers(self, expectation_line): has_wontfix = False has_bugid = False parsed_specifiers = set() modifiers = [modifier.lower() for modifier in expectation_line.modifiers] expectations = [expectation.lower() for expectation in expectation_line.expectations] if self.SLOW_MODIFIER in modifiers and self.TIMEOUT_EXPECTATION in expectations: expectation_line.warnings.append('A test can not be both SLOW and TIMEOUT. If it times out indefinitely, then it should be just TIMEOUT.') for modifier in modifiers: if modifier in TestExpectations.MODIFIERS: expectation_line.parsed_modifiers.append(modifier) if modifier == self.WONTFIX_MODIFIER: has_wontfix = True elif modifier.startswith(self.BUG_MODIFIER_PREFIX): has_bugid = True if re.match(self.BUG_MODIFIER_REGEX, modifier): expectation_line.warnings.append('BUG\d+ is not allowed, must be one of BUGCR\d+, BUGWK\d+, BUGV8_\d+, or a non-numeric bug identifier.') else: expectation_line.parsed_bug_modifiers.append(modifier) else: parsed_specifiers.add(modifier) if not expectation_line.parsed_bug_modifiers and not has_wontfix and not has_bugid and self._port.warn_if_bug_missing_in_test_expectations(): expectation_line.warnings.append(self.MISSING_BUG_WARNING) if self._allow_rebaseline_modifier and self.REBASELINE_MODIFIER in modifiers: expectation_line.warnings.append('REBASELINE should only be used for running rebaseline.py. Cannot be checked in.') expectation_line.matching_configurations = self._test_configuration_converter.to_config_set(parsed_specifiers, expectation_line.warnings) def _parse_expectations(self, expectation_line): result = set() for part in expectation_line.expectations: expectation = TestExpectations.expectation_from_string(part) if expectation is None: # Careful, PASS is currently 0. expectation_line.warnings.append('Unsupported expectation: %s' % part) continue result.add(expectation) expectation_line.parsed_expectations = result def _check_test_exists(self, expectation_line): # WebKit's way of skipping tests is to add a -disabled suffix. # So we should consider the path existing if the path or the # -disabled version exists. if not self._port.test_exists(expectation_line.name) and not self._port.test_exists(expectation_line.name + '-disabled'): # Log a warning here since you hit this case any # time you update TestExpectations without syncing # the LayoutTests directory expectation_line.warnings.append('Path does not exist.') return False return True def _collect_matching_tests(self, expectation_line): """Convert the test specification to an absolute, normalized path and make sure directories end with the OS path separator.""" # FIXME: full_test_list can quickly contain a big amount of # elements. We should consider at some point to use a more # efficient structure instead of a list. Maybe a dictionary of # lists to represent the tree of tests, leaves being test # files and nodes being categories. if not self._full_test_list: expectation_line.matching_tests = [expectation_line.path] return if not expectation_line.is_file: # this is a test category, return all the tests of the category. expectation_line.matching_tests = [test for test in self._full_test_list if test.startswith(expectation_line.path)] return # this is a test file, do a quick check if it's in the # full test suite. if expectation_line.path in self._full_test_list: expectation_line.matching_tests.append(expectation_line.path) # FIXME: Update the original modifiers and remove this once the old syntax is gone. _configuration_tokens_list = [ 'Mac', 'SnowLeopard', 'Lion', 'MountainLion', 'Win', 'XP', 'Vista', 'Win7', 'Linux', 'Android', 'Release', 'Debug', ] _configuration_tokens = dict((token, token.upper()) for token in _configuration_tokens_list) _inverted_configuration_tokens = dict((value, name) for name, value in _configuration_tokens.iteritems()) # FIXME: Update the original modifiers list and remove this once the old syntax is gone. _expectation_tokens = { 'Crash': 'CRASH', 'Failure': 'FAIL', 'ImageOnlyFailure': 'IMAGE', 'Missing': 'MISSING', 'Pass': 'PASS', 'Rebaseline': 'REBASELINE', 'Skip': 'SKIP', 'Slow': 'SLOW', 'Timeout': 'TIMEOUT', 'WontFix': 'WONTFIX', } _inverted_expectation_tokens = dict([(value, name) for name, value in _expectation_tokens.iteritems()] + [('TEXT', 'Failure'), ('IMAGE+TEXT', 'Failure'), ('AUDIO', 'Failure')]) # FIXME: Seems like these should be classmethods on TestExpectationLine instead of TestExpectationParser. @classmethod def _tokenize_line(cls, filename, expectation_string, line_number): """Tokenizes a line from TestExpectations and returns an unparsed TestExpectationLine instance using the old format. The new format for a test expectation line is: [[bugs] [ "[" <configuration modifiers> "]" <name> [ "[" <expectations> "]" ["#" <comment>] Any errant whitespace is not preserved. """ expectation_line = TestExpectationLine() expectation_line.original_string = expectation_string expectation_line.filename = filename expectation_line.line_number = line_number comment_index = expectation_string.find("#") if comment_index == -1: comment_index = len(expectation_string) else: expectation_line.comment = expectation_string[comment_index + 1:] remaining_string = re.sub(r"\s+", " ", expectation_string[:comment_index].strip()) if len(remaining_string) == 0: return expectation_line # special-case parsing this so that we fail immediately instead of treating this as a test name if remaining_string.startswith('//'): expectation_line.warnings = ['use "#" instead of "//" for comments'] return expectation_line bugs = [] modifiers = [] name = None expectations = [] warnings = [] WEBKIT_BUG_PREFIX = 'webkit.org/b/' tokens = remaining_string.split() state = 'start' for token in tokens: if token.startswith(WEBKIT_BUG_PREFIX) or token.startswith('Bug('): if state != 'start': warnings.append('"%s" is not at the start of the line.' % token) break if token.startswith(WEBKIT_BUG_PREFIX): bugs.append(token.replace(WEBKIT_BUG_PREFIX, 'BUGWK')) else: match = re.match('Bug\((\w+)\)$', token) if not match: warnings.append('unrecognized bug identifier "%s"' % token) break else: bugs.append('BUG' + match.group(1).upper()) elif token.startswith('BUG'): warnings.append('unrecognized old-style bug identifier "%s"' % token) break elif token == '[': if state == 'start': state = 'configuration' elif state == 'name_found': state = 'expectations' else: warnings.append('unexpected "["') break elif token == ']': if state == 'configuration': state = 'name' elif state == 'expectations': state = 'done' else: warnings.append('unexpected "]"') break elif token in ('//', ':', '='): warnings.append('"%s" is not legal in the new TestExpectations syntax.' % token) break elif state == 'configuration': modifiers.append(cls._configuration_tokens.get(token, token)) elif state == 'expectations': if token in ('Rebaseline', 'Skip', 'Slow', 'WontFix'): modifiers.append(token.upper()) elif token not in cls._expectation_tokens: warnings.append('Unrecognized expectation "%s"' % token) else: expectations.append(cls._expectation_tokens.get(token, token)) elif state == 'name_found': warnings.append('expecting "[", "#", or end of line instead of "%s"' % token) break else: name = token state = 'name_found' if not warnings: if not name: warnings.append('Did not find a test name.') elif state not in ('name_found', 'done'): warnings.append('Missing a "]"') if 'WONTFIX' in modifiers and 'SKIP' not in modifiers and not expectations: modifiers.append('SKIP') if 'SKIP' in modifiers and expectations: # FIXME: This is really a semantic warning and shouldn't be here. Remove when we drop the old syntax. warnings.append('A test marked Skip must not have other expectations.') elif not expectations: if 'SKIP' not in modifiers and 'REBASELINE' not in modifiers and 'SLOW' not in modifiers: modifiers.append('SKIP') expectations = ['PASS'] # FIXME: expectation line should just store bugs and modifiers separately. expectation_line.modifiers = bugs + modifiers expectation_line.expectations = expectations expectation_line.name = name expectation_line.warnings = warnings return expectation_line @classmethod def _split_space_separated(cls, space_separated_string): """Splits a space-separated string into an array.""" return [part.strip() for part in space_separated_string.strip().split(' ')] class TestExpectationLine(object): """Represents a line in test expectations file.""" def __init__(self): """Initializes a blank-line equivalent of an expectation.""" self.original_string = None self.filename = None # this is the path to the expectations file for this line self.line_number = None self.name = None # this is the path in the line itself self.path = None # this is the normpath of self.name self.modifiers = [] self.parsed_modifiers = [] self.parsed_bug_modifiers = [] self.matching_configurations = set() self.expectations = [] self.parsed_expectations = set() self.comment = None self.matching_tests = [] self.warnings = [] def is_invalid(self): return self.warnings and self.warnings != [TestExpectationParser.MISSING_BUG_WARNING] def is_flaky(self): return len(self.parsed_expectations) > 1 @staticmethod def create_passing_expectation(test): expectation_line = TestExpectationLine() expectation_line.name = test expectation_line.path = test expectation_line.parsed_expectations = set([PASS]) expectation_line.expectations = set(['PASS']) expectation_line.matching_tests = [test] return expectation_line def to_string(self, test_configuration_converter, include_modifiers=True, include_expectations=True, include_comment=True): parsed_expectation_to_string = dict([[parsed_expectation, expectation_string] for expectation_string, parsed_expectation in TestExpectations.EXPECTATIONS.items()]) if self.is_invalid(): return self.original_string or '' if self.name is None: return '' if self.comment is None else "#%s" % self.comment if test_configuration_converter and self.parsed_bug_modifiers: specifiers_list = test_configuration_converter.to_specifiers_list(self.matching_configurations) result = [] for specifiers in specifiers_list: # FIXME: this is silly that we join the modifiers and then immediately split them. modifiers = self._serialize_parsed_modifiers(test_configuration_converter, specifiers).split() expectations = self._serialize_parsed_expectations(parsed_expectation_to_string).split() result.append(self._format_line(modifiers, self.name, expectations, self.comment)) return "\n".join(result) if result else None return self._format_line(self.modifiers, self.name, self.expectations, self.comment, include_modifiers, include_expectations, include_comment) def to_csv(self): # Note that this doesn't include the comments. return '%s,%s,%s' % (self.name, ' '.join(self.modifiers), ' '.join(self.expectations)) def _serialize_parsed_expectations(self, parsed_expectation_to_string): result = [] for index in TestExpectations.EXPECTATION_ORDER: if index in self.parsed_expectations: result.append(parsed_expectation_to_string[index]) return ' '.join(result) def _serialize_parsed_modifiers(self, test_configuration_converter, specifiers): result = [] if self.parsed_bug_modifiers: result.extend(sorted(self.parsed_bug_modifiers)) result.extend(sorted(self.parsed_modifiers)) result.extend(test_configuration_converter.specifier_sorter().sort_specifiers(specifiers)) return ' '.join(result) @staticmethod def _format_line(modifiers, name, expectations, comment, include_modifiers=True, include_expectations=True, include_comment=True): bugs = [] new_modifiers = [] new_expectations = [] for modifier in modifiers: modifier = modifier.upper() if modifier.startswith('BUGWK'): bugs.append('webkit.org/b/' + modifier.replace('BUGWK', '')) elif modifier.startswith('BUGCR'): bugs.append('crbug.com/' + modifier.replace('BUGCR', '')) elif modifier.startswith('BUG'): # FIXME: we should preserve case once we can drop the old syntax. bugs.append('Bug(' + modifier[3:].lower() + ')') elif modifier in ('SLOW', 'SKIP', 'REBASELINE', 'WONTFIX'): new_expectations.append(TestExpectationParser._inverted_expectation_tokens.get(modifier)) else: new_modifiers.append(TestExpectationParser._inverted_configuration_tokens.get(modifier, modifier)) for expectation in expectations: expectation = expectation.upper() new_expectations.append(TestExpectationParser._inverted_expectation_tokens.get(expectation, expectation)) result = '' if include_modifiers and (bugs or new_modifiers): if bugs: result += ' '.join(bugs) + ' ' if new_modifiers: result += '[ %s ] ' % ' '.join(new_modifiers) result += name if include_expectations and new_expectations and set(new_expectations) != set(['Skip', 'Pass']): result += ' [ %s ]' % ' '.join(sorted(set(new_expectations))) if include_comment and comment is not None: result += " #%s" % comment return result # FIXME: Refactor API to be a proper CRUD. class TestExpectationsModel(object): """Represents relational store of all expectations and provides CRUD semantics to manage it.""" def __init__(self, shorten_filename=None): # Maps a test to its list of expectations. self._test_to_expectations = {} # Maps a test to list of its modifiers (string values) self._test_to_modifiers = {} # Maps a test to a TestExpectationLine instance. self._test_to_expectation_line = {} self._modifier_to_tests = self._dict_of_sets(TestExpectations.MODIFIERS) self._expectation_to_tests = self._dict_of_sets(TestExpectations.EXPECTATIONS) self._timeline_to_tests = self._dict_of_sets(TestExpectations.TIMELINES) self._result_type_to_tests = self._dict_of_sets(TestExpectations.RESULT_TYPES) self._shorten_filename = shorten_filename or (lambda x: x) def _dict_of_sets(self, strings_to_constants): """Takes a dict of strings->constants and returns a dict mapping each constant to an empty set.""" d = {} for c in strings_to_constants.values(): d[c] = set() return d def get_test_set(self, modifier, expectation=None, include_skips=True): if expectation is None: tests = self._modifier_to_tests[modifier] else: tests = (self._expectation_to_tests[expectation] & self._modifier_to_tests[modifier]) if not include_skips: tests = tests - self.get_test_set(SKIP, expectation) return tests def get_test_set_for_keyword(self, keyword): # FIXME: get_test_set() is an awkward public interface because it requires # callers to know the difference between modifiers and expectations. We # should replace that with this where possible. expectation_enum = TestExpectations.EXPECTATIONS.get(keyword.lower(), None) if expectation_enum is not None: return self._expectation_to_tests[expectation_enum] modifier_enum = TestExpectations.MODIFIERS.get(keyword.lower(), None) if modifier_enum is not None: return self._modifier_to_tests[modifier_enum] # We must not have an index on this modifier. matching_tests = set() for test, modifiers in self._test_to_modifiers.iteritems(): if keyword.lower() in modifiers: matching_tests.add(test) return matching_tests def get_tests_with_result_type(self, result_type): return self._result_type_to_tests[result_type] def get_tests_with_timeline(self, timeline): return self._timeline_to_tests[timeline] def get_modifiers(self, test): """This returns modifiers for the given test (the modifiers plus the BUGXXXX identifier). This is used by the LTTF dashboard.""" return self._test_to_modifiers[test] def has_modifier(self, test, modifier): return test in self._modifier_to_tests[modifier] def has_keyword(self, test, keyword): return (keyword.upper() in self.get_expectations_string(test) or keyword.lower() in self.get_modifiers(test)) def has_test(self, test): return test in self._test_to_expectation_line def get_expectation_line(self, test): return self._test_to_expectation_line.get(test) def get_expectations(self, test): return self._test_to_expectations[test] def get_expectations_string(self, test): """Returns the expectatons for the given test as an uppercase string. If there are no expectations for the test, then "PASS" is returned.""" expectations = self.get_expectations(test) retval = [] for expectation in expectations: retval.append(self.expectation_to_string(expectation)) return " ".join(retval) def expectation_to_string(self, expectation): """Return the uppercased string equivalent of a given expectation.""" for item in TestExpectations.EXPECTATIONS.items(): if item[1] == expectation: return item[0].upper() raise ValueError(expectation) def add_expectation_line(self, expectation_line, in_skipped=False): """Returns a list of warnings encountered while matching modifiers.""" if expectation_line.is_invalid(): return for test in expectation_line.matching_tests: if not in_skipped and self._already_seen_better_match(test, expectation_line): continue self._clear_expectations_for_test(test) self._test_to_expectation_line[test] = expectation_line self._add_test(test, expectation_line) def _add_test(self, test, expectation_line): """Sets the expected state for a given test. This routine assumes the test has not been added before. If it has, use _clear_expectations_for_test() to reset the state prior to calling this.""" self._test_to_expectations[test] = expectation_line.parsed_expectations for expectation in expectation_line.parsed_expectations: self._expectation_to_tests[expectation].add(test) self._test_to_modifiers[test] = expectation_line.modifiers for modifier in expectation_line.parsed_modifiers: mod_value = TestExpectations.MODIFIERS[modifier] self._modifier_to_tests[mod_value].add(test) if TestExpectationParser.WONTFIX_MODIFIER in expectation_line.parsed_modifiers: self._timeline_to_tests[WONTFIX].add(test) else: self._timeline_to_tests[NOW].add(test) if TestExpectationParser.SKIP_MODIFIER in expectation_line.parsed_modifiers: self._result_type_to_tests[SKIP].add(test) elif expectation_line.parsed_expectations == set([PASS]): self._result_type_to_tests[PASS].add(test) elif expectation_line.is_flaky(): self._result_type_to_tests[FLAKY].add(test) else: # FIXME: What is this? self._result_type_to_tests[FAIL].add(test) def _clear_expectations_for_test(self, test): """Remove prexisting expectations for this test. This happens if we are seeing a more precise path than a previous listing. """ if self.has_test(test): self._test_to_expectations.pop(test, '') self._remove_from_sets(test, self._expectation_to_tests) self._remove_from_sets(test, self._modifier_to_tests) self._remove_from_sets(test, self._timeline_to_tests) self._remove_from_sets(test, self._result_type_to_tests) def _remove_from_sets(self, test, dict_of_sets_of_tests): """Removes the given test from the sets in the dictionary. Args: test: test to look for dict: dict of sets of files""" for set_of_tests in dict_of_sets_of_tests.itervalues(): if test in set_of_tests: set_of_tests.remove(test) def _already_seen_better_match(self, test, expectation_line): """Returns whether we've seen a better match already in the file. Returns True if we've already seen a expectation_line.name that matches more of the test than this path does """ # FIXME: See comment below about matching test configs and specificity. if not self.has_test(test): # We've never seen this test before. return False prev_expectation_line = self._test_to_expectation_line[test] if prev_expectation_line.filename != expectation_line.filename: # We've moved on to a new expectation file, which overrides older ones. return False if len(prev_expectation_line.path) > len(expectation_line.path): # The previous path matched more of the test. return True if len(prev_expectation_line.path) < len(expectation_line.path): # This path matches more of the test. return False # At this point we know we have seen a previous exact match on this # base path, so we need to check the two sets of modifiers. # FIXME: This code was originally designed to allow lines that matched # more modifiers to override lines that matched fewer modifiers. # However, we currently view these as errors. # # To use the "more modifiers wins" policy, change the errors for overrides # to be warnings and return False". if prev_expectation_line.matching_configurations == expectation_line.matching_configurations: expectation_line.warnings.append('Duplicate or ambiguous entry lines %s:%d and %s:%d.' % ( self._shorten_filename(prev_expectation_line.filename), prev_expectation_line.line_number, self._shorten_filename(expectation_line.filename), expectation_line.line_number)) return True if prev_expectation_line.matching_configurations >= expectation_line.matching_configurations: expectation_line.warnings.append('More specific entry for %s on line %s:%d overrides line %s:%d.' % (expectation_line.name, self._shorten_filename(prev_expectation_line.filename), prev_expectation_line.line_number, self._shorten_filename(expectation_line.filename), expectation_line.line_number)) # FIXME: return False if we want more specific to win. return True if prev_expectation_line.matching_configurations <= expectation_line.matching_configurations: expectation_line.warnings.append('More specific entry for %s on line %s:%d overrides line %s:%d.' % (expectation_line.name, self._shorten_filename(expectation_line.filename), expectation_line.line_number, self._shorten_filename(prev_expectation_line.filename), prev_expectation_line.line_number)) return True if prev_expectation_line.matching_configurations & expectation_line.matching_configurations: expectation_line.warnings.append('Entries for %s on lines %s:%d and %s:%d match overlapping sets of configurations.' % (expectation_line.name, self._shorten_filename(prev_expectation_line.filename), prev_expectation_line.line_number, self._shorten_filename(expectation_line.filename), expectation_line.line_number)) return True # Configuration sets are disjoint, then. return False class TestExpectations(object): """Test expectations consist of lines with specifications of what to expect from layout test cases. The test cases can be directories in which case the expectations apply to all test cases in that directory and any subdirectory. The format is along the lines of: LayoutTests/fast/js/fixme.js [ Failure ] LayoutTests/fast/js/flaky.js [ Failure Pass ] LayoutTests/fast/js/crash.js [ Crash Failure Pass Timeout ] ... To add modifiers: LayoutTests/fast/js/no-good.js [ Debug ] LayoutTests/fast/js/no-good.js [ Pass Timeout ] [ Debug ] LayoutTests/fast/js/no-good.js [ Pass Skip Timeout ] [ Linux Debug ] LayoutTests/fast/js/no-good.js [ Pass Skip Timeout ] [ Linux Win ] LayoutTests/fast/js/no-good.js [ Pass Skip Timeout ] Skip: Doesn't run the test. Slow: The test takes a long time to run, but does not timeout indefinitely. WontFix: For tests that we never intend to pass on a given platform (treated like Skip). Notes: -A test cannot be both SLOW and TIMEOUT -A test can be included twice, but not via the same path. -If a test is included twice, then the more precise path wins. -CRASH tests cannot be WONTFIX """ # FIXME: Update to new syntax once the old format is no longer supported. EXPECTATIONS = {'pass': PASS, 'audio': AUDIO, 'fail': FAIL, 'image': IMAGE, 'image+text': IMAGE_PLUS_TEXT, 'text': TEXT, 'timeout': TIMEOUT, 'crash': CRASH, 'missing': MISSING, 'skip': SKIP} # (aggregated by category, pass/fail/skip, type) EXPECTATION_DESCRIPTIONS = {SKIP: 'skipped', PASS: 'passes', FAIL: 'failures', IMAGE: 'image-only failures', TEXT: 'text-only failures', IMAGE_PLUS_TEXT: 'image and text failures', AUDIO: 'audio failures', CRASH: 'crashes', TIMEOUT: 'timeouts', MISSING: 'missing results'} EXPECTATION_ORDER = (PASS, CRASH, TIMEOUT, MISSING, FAIL, IMAGE, SKIP) BUILD_TYPES = ('debug', 'release') MODIFIERS = {TestExpectationParser.SKIP_MODIFIER: SKIP, TestExpectationParser.WONTFIX_MODIFIER: WONTFIX, TestExpectationParser.SLOW_MODIFIER: SLOW, TestExpectationParser.REBASELINE_MODIFIER: REBASELINE, 'none': NONE} TIMELINES = {TestExpectationParser.WONTFIX_MODIFIER: WONTFIX, 'now': NOW} RESULT_TYPES = {'skip': SKIP, 'pass': PASS, 'fail': FAIL, 'flaky': FLAKY} @classmethod def expectation_from_string(cls, string): assert(' ' not in string) # This only handles one expectation at a time. return cls.EXPECTATIONS.get(string.lower()) @staticmethod def result_was_expected(result, expected_results, test_needs_rebaselining, test_is_skipped): """Returns whether we got a result we were expecting. Args: result: actual result of a test execution expected_results: set of results listed in test_expectations test_needs_rebaselining: whether test was marked as REBASELINE test_is_skipped: whether test was marked as SKIP""" if result in expected_results: return True if result in (TEXT, IMAGE_PLUS_TEXT, AUDIO) and (FAIL in expected_results): return True if result == MISSING and test_needs_rebaselining: return True if result == SKIP and test_is_skipped: return True return False @staticmethod def remove_pixel_failures(expected_results): """Returns a copy of the expected results for a test, except that we drop any pixel failures and return the remaining expectations. For example, if we're not running pixel tests, then tests expected to fail as IMAGE will PASS.""" expected_results = expected_results.copy() if IMAGE in expected_results: expected_results.remove(IMAGE) expected_results.add(PASS) return expected_results @staticmethod def has_pixel_failures(actual_results): return IMAGE in actual_results or FAIL in actual_results @staticmethod def suffixes_for_expectations(expectations): suffixes = set() if IMAGE in expectations: suffixes.add('png') if FAIL in expectations: suffixes.add('txt') suffixes.add('png') suffixes.add('wav') return set(suffixes) # FIXME: This constructor does too much work. We should move the actual parsing of # the expectations into separate routines so that linting and handling overrides # can be controlled separately, and the constructor can be more of a no-op. def __init__(self, port, tests=None, include_generic=True, include_overrides=True, expectations_to_lint=None): self._full_test_list = tests self._test_config = port.test_configuration() self._is_lint_mode = expectations_to_lint is not None self._model = TestExpectationsModel(self._shorten_filename) self._parser = TestExpectationParser(port, tests, self._is_lint_mode) self._port = port self._skipped_tests_warnings = [] self._expectations = [] expectations_dict = expectations_to_lint or port.expectations_dict() expectations_dict_index = 0 # Populate generic expectations (if enabled by include_generic). if port.path_to_generic_test_expectations_file() in expectations_dict: if include_generic: expectations = self._parser.parse(expectations_dict.keys()[expectations_dict_index], expectations_dict.values()[expectations_dict_index]) self._add_expectations(expectations) self._expectations += expectations expectations_dict_index += 1 # Populate default port expectations (always enabled). if len(expectations_dict) > expectations_dict_index: expectations = self._parser.parse(expectations_dict.keys()[expectations_dict_index], expectations_dict.values()[expectations_dict_index]) self._add_expectations(expectations) self._expectations += expectations expectations_dict_index += 1 # Populate override expectations (if enabled by include_overrides). while len(expectations_dict) > expectations_dict_index and include_overrides: expectations = self._parser.parse(expectations_dict.keys()[expectations_dict_index], expectations_dict.values()[expectations_dict_index]) self._add_expectations(expectations) self._expectations += expectations expectations_dict_index += 1 # FIXME: move ignore_tests into port.skipped_layout_tests() self.add_skipped_tests(port.skipped_layout_tests(tests).union(set(port.get_option('ignore_tests', [])))) self._has_warnings = False self._report_warnings() self._process_tests_without_expectations() # TODO(ojan): Allow for removing skipped tests when getting the list of # tests to run, but not when getting metrics. def model(self): return self._model def get_rebaselining_failures(self): return self._model.get_test_set(REBASELINE) # FIXME: Change the callsites to use TestExpectationsModel and remove. def get_expectations(self, test): return self._model.get_expectations(test) # FIXME: Change the callsites to use TestExpectationsModel and remove. def has_modifier(self, test, modifier): return self._model.has_modifier(test, modifier) # FIXME: Change the callsites to use TestExpectationsModel and remove. def get_tests_with_result_type(self, result_type): return self._model.get_tests_with_result_type(result_type) # FIXME: Change the callsites to use TestExpectationsModel and remove. def get_test_set(self, modifier, expectation=None, include_skips=True): return self._model.get_test_set(modifier, expectation, include_skips) # FIXME: Change the callsites to use TestExpectationsModel and remove. def get_modifiers(self, test): return self._model.get_modifiers(test) # FIXME: Change the callsites to use TestExpectationsModel and remove. def get_tests_with_timeline(self, timeline): return self._model.get_tests_with_timeline(timeline) def get_expectations_string(self, test): return self._model.get_expectations_string(test) def expectation_to_string(self, expectation): return self._model.expectation_to_string(expectation) def matches_an_expected_result(self, test, result, pixel_tests_are_enabled): expected_results = self._model.get_expectations(test) if not pixel_tests_are_enabled: expected_results = self.remove_pixel_failures(expected_results) return self.result_was_expected(result, expected_results, self.is_rebaselining(test), self._model.has_modifier(test, SKIP)) def is_rebaselining(self, test): return self._model.has_modifier(test, REBASELINE) def _shorten_filename(self, filename): if filename.startswith(self._port.path_from_webkit_base()): return self._port.host.filesystem.relpath(filename, self._port.path_from_webkit_base()) return filename def _report_warnings(self): warnings = [] for expectation in self._expectations: for warning in expectation.warnings: warnings.append('%s:%d %s %s' % (self._shorten_filename(expectation.filename), expectation.line_number, warning, expectation.name if expectation.expectations else expectation.original_string)) if warnings: self._has_warnings = True if self._is_lint_mode: raise ParseError(warnings) _log.warning('--lint-test-files warnings:') for warning in warnings: _log.warning(warning) _log.warning('') def _process_tests_without_expectations(self): if self._full_test_list: for test in self._full_test_list: if not self._model.has_test(test): self._model.add_expectation_line(TestExpectationLine.create_passing_expectation(test)) def has_warnings(self): return self._has_warnings def remove_configuration_from_test(self, test, test_configuration): expectations_to_remove = [] modified_expectations = [] for expectation in self._expectations: if expectation.name != test or expectation.is_flaky() or not expectation.parsed_expectations: continue if iter(expectation.parsed_expectations).next() not in (FAIL, IMAGE): continue if test_configuration not in expectation.matching_configurations: continue expectation.matching_configurations.remove(test_configuration) if expectation.matching_configurations: modified_expectations.append(expectation) else: expectations_to_remove.append(expectation) for expectation in expectations_to_remove: self._expectations.remove(expectation) return self.list_to_string(self._expectations, self._parser._test_configuration_converter, modified_expectations) def remove_rebaselined_tests(self, except_these_tests, filename): """Returns a copy of the expectations in the file with the tests removed.""" def without_rebaseline_modifier(expectation): return (expectation.filename == filename and not (not expectation.is_invalid() and expectation.name in except_these_tests and 'rebaseline' in expectation.parsed_modifiers)) return self.list_to_string(filter(without_rebaseline_modifier, self._expectations), reconstitute_only_these=[]) def _add_expectations(self, expectation_list): for expectation_line in expectation_list: if not expectation_line.expectations: continue if self._is_lint_mode or self._test_config in expectation_line.matching_configurations: self._model.add_expectation_line(expectation_line) def add_skipped_tests(self, tests_to_skip): if not tests_to_skip: return for test in self._expectations: if test.name and test.name in tests_to_skip: test.warnings.append('%s:%d %s is also in a Skipped file.' % (test.filename, test.line_number, test.name)) for test_name in tests_to_skip: expectation_line = self._parser.expectation_for_skipped_test(test_name) self._model.add_expectation_line(expectation_line, in_skipped=True) @staticmethod def list_to_string(expectation_lines, test_configuration_converter=None, reconstitute_only_these=None): def serialize(expectation_line): # If reconstitute_only_these is an empty list, we want to return original_string. # So we need to compare reconstitute_only_these to None, not just check if it's falsey. if reconstitute_only_these is None or expectation_line in reconstitute_only_these: return expectation_line.to_string(test_configuration_converter) return expectation_line.original_string def nones_out(expectation_line): return expectation_line is not None return "\n".join(filter(nones_out, map(serialize, expectation_lines)))
bsd-3-clause
MarcusMoeller/mfc
deb/builds/mfc1_1.0-2/mfc1-1.0/mfc1/popup.py
12
6107
#!/usr/bin/python # -*- coding: utf-8 -*- # With the MindfulClock you turn your device into a Bell of Mindfulness. # Concept, Design: Marcurs Möller # <marcus.moeller@outlook.com> # <http://apps.microsoft.com/windows/de-de/app/ # mindfulclock/58063160-9cc6-4dee-9d92-17df4ce4318a> # Programming: Andreas Ulrich # <ulrich3110@gmail.com>, # <http://erasand.jimdo.com/kontakt/> # # This file is part of the "MindfulClock". # "MindfulClock" 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. # # "MindfulClock" 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 # "MindfulClock". If not, see <http://www.gnu.org/licenses/>. import wx class Popup(wx.PopupTransientWindow): '''mfc1.Popup(parent, style, text, font, colors, icon) Show the text notification for the MindfulClock. parent = wx.window style = wx.SIMPLE_BORDER, wx.RAISED_BORDER, wx.SUNKEN_BORDER, wx.NO_BORDER text = 'notification text' font = (size, 'family', 'style', 'weight') colors = (text_color, background_color), colors in html-fomat, '#RRGGBB'. icon = 'path' to icon for close button on_close(event) Event for bitmap button. set_font(font) Set the wx.Font from the tuple font to the caption. ''' def __init__(self, parent, style, text, font, colors, icon): # subclass wx.PopupTransientWindow.__init__(self, parent=parent, style=style) # Set background color. if colors[1]: self.SetBackgroundColour(colors[1]) # Text. self.__caption = wx.StaticText(self, label=text, pos=(10, 10)) # Set font. self.set_font(font) # Set text color. if colors[0]: self.__caption.SetForegroundColour(colors[0]) # Text size. tsize = self.__caption.GetBestSize() # Close button. button = wx.BitmapButton(parent=self, bitmap=wx.Bitmap(icon)) # Bindings button.Bind(event=wx.EVT_BUTTON, handler=self.on_close) # Button size and position. bsize = button.GetBestSize() # w = widgets maximum width. if tsize.width > bsize.width: # Text is wider than the button. w = tsize.width else: # The button is wider than the text. w = bsize.width # x, y = button position x = (w - bsize.width) / 2 y = tsize.height + font[0] * 2 # h = widgets height h = y + bsize.height # Set button to position. button.SetPosition((x, y)) # Notification size. self.__size = (w + font[0], h + font[0]) self.SetSize(self.__size) def on_close(self, event): '''Event for bitmap button.''' self.Show(False) self.Destroy() def set_font(self, font): '''Set the wx.Font from the tuple font to the caption.''' # font = (size, 'family', 'style', 'weight') familydic = {'decorative': wx.FONTFAMILY_DECORATIVE, 'default': wx.FONTFAMILY_DEFAULT, 'modern': wx.FONTFAMILY_MODERN, 'roman': wx.FONTFAMILY_ROMAN, 'script': wx.FONTFAMILY_SCRIPT, 'swiss': wx.FONTFAMILY_SWISS, 'teletype': wx.FONTFAMILY_TELETYPE} styledic = {'normal': wx.NORMAL, 'slant': wx.SLANT, 'italic': wx.ITALIC} weightdic = {'normal': wx.FONTWEIGHT_NORMAL, 'light': wx.FONTWEIGHT_LIGHT, 'bold': wx.FONTWEIGHT_BOLD} textfont = self.__caption.GetFont() textfont.SetPointSize(font[0]) textfont.SetFamily(familydic[font[1]]) textfont.SetStyle(styledic[font[2]]) textfont.SetWeight(weightdic[font[3]]) self.__caption.SetFont(textfont) def get_size(self): '''Return the calculated size.''' return(self.__size) class wxTestFrame(wx.Frame): '''Test wx.Frame. show_popup() Show dialogue. ''' def __init__(self): wx.Frame.__init__(self, parent=None) wx.FutureCall(millis=100, callable=self.show_popup()) self.Centre() self.Show() def show_popup(self): '''Show dialogue.''' t = 'Please enter your message ..' popup = Popup(parent=self, style=wx.NO_BORDER, text=t, font=(20, 'default', 'italic', 'bold'), colors=(None, None), icon='icons/32/weather-clear.png') popw, poph = popup.get_size() dispw, disph = wx.GetDisplaySize() offx = (dispw - popw) / 2 offy = (disph - poph) / 2 popup.Position(ptOrigin=(0, 0), size=(offx, offy)) popup.Popup() # Test fonts # 'decorative' 'normal' 'normal' # 'default' 'slant' 'light' # 'modern' 'italic' 'bold' # 'roman' # 'script' # 'swiss' # 'teletype' # Borders: wx.SIMPLE_BORDER # wx.RAISED_BORDER # wx.SUNKEN_BORDER # wx.NO_BORDER # colors=(None, None) # colors=('#0000FF', '#FFFF00') if __name__ == '__main__': app = wx.App() frame = wxTestFrame() app.MainLoop()
gpl-3.0
michaelgugino/web_keyer
KeyerView.py
1
7127
from flask import request, session, g, redirect, url_for, abort, render_template, flash from flask.views import MethodView from models import User,KeyingTask, KeyingAnswer import cache_methods cache = cache_methods.cache from database import db_session class KeyerView(MethodView): ''' This class displays and controls keying mode. ''' def get(self, user_id): ''' "get" is the default method for entering the keying page. We do not submit form data across get, only "post." Here, we resume a previously started keying task by checking cache. This is in case the user closed their browser or navigated away during a task. If no task is found in cache, then we select a new task. First, we select something that is on second pass not keyed by the user. If nothing, we select something that is on first pass. ''' #this would be for /key/<user_id> #which is not defined right now. #testing username='mgugino' #this will load cache with user_id; if #there is no active user_id, app #will fail to 401 unauthorized. myid = cache_methods.cacheGetUserID(username=username) #Check permissions here #check to see if we already have a task we should be keying #otherwise, we need to fetch a task from the db. my_current_task = cache_methods.cacheGetAKeyingTask(userid=myid) #if we still don't have a task, that means there's nothing to key #at the moment. if my_current_task is None: flash('There are no valid keying tasks at this time, please check back later') return render_template('index.html') #Turn task into a session object so we can update it, etc. #For testing only at this point. my_current_task = db_session.merge(my_current_task) #testing area #my_current_task.png = '/static/images/demo3.png' #db_session.commit() #cache.set(str(myid)+':current_task',my_current_task,) #determine field type goes here #This information should go in fielddefs table. resource='Recipient' #This information should go in res_ourcedefs table. attributes=['id', 'lname', 'fname', 'mname'] #retrieve field resources my_dict = cache_methods.cacheGetDict(fieldtype=my_current_task.fieldtype_id, resource=resource, attributes=attributes) #flash(my_dict[1]) #return render_template('index.html') return render_template('key.html', kt=my_current_task, auto_dict=my_dict) def post(self, user_id): ''' This method is used for submission of keying data. First, the submitted task id is check against the cache. If the cache contains a keying task with the user's id, then the form is submitted. Otherwise, the user will be redirected to the index page to log in again. This is to prevent stale data from being submitted. ''' #testing username='mgugino' #this will load cache with user_id; if #there is no active user_id, app #will fail to 401 unauthorized. myid = cache_methods.cacheGetUserID(username=username) # Make sure our answer fields are all present from the form. if (request.form.get('kt_id') is None or request.form.get('pass_number') is None or request.form.get('answer') is None): abort(500, "Invalid form submitted. If you continue to see this error, contact your administrator") # check cache for 'keyingtask:<kt_id>:<pass_number>' = <myid> # This ensure's we're not keying a stale task, as well as preventing spoofing. if (cache.get('keyingtask:'+str(request.form['kt_id'])+':'+str(request.form['pass_number'])) != myid): # if no task / user_id match found in cache, exit to index. cache.delete(str(myid)+':current_task') flash("Invalid Keying Task Submitteda") return render_template('index.html') # if task was found, submit task to rabbitmq, unset user cache and task cache. #in testing, all that happens here. #Ensure we have a current task in cache. my_current_task = cache.get(str(myid)+':current_task') if (my_current_task is None): #No current task means we cannot procedure further. Fall back to index. cache.delete(str(myid)+':current_task') flash("Invalid Keying Task Submitted") return render_template('index.html') #Task is valid, submit message to process results. #-------------RabbitMQ part----------------- #Testing: Make sure warm cache is implemented before offloading db update to rabbit. my_current_task = db_session.merge(my_current_task) if (request.form['pass_number'] == str(1)): my_current_task.firstpass = 2 my_current_answer = KeyingAnswer(kt_id=request.form['kt_id'], firstanswer=request.form['answer']) db_session.add(my_current_answer) else: my_current_task.secondpass = 2 my_current_answer = db_session.query(KeyingAnswer).with_lockmode('update').filter(KeyingAnswer.kt_id == int(request.form['kt_id'])).first() my_current_answer.secondanswer = request.form['answer'] db_session.commit() #-------------End RabbitMQ part----------------- cache.delete(str(myid)+':current_task') cache.delete('keyingtask:'+str(request.form['kt_id'])+':'+str(request.form['pass_number'])) #get new task my_current_task = cache_methods.cacheGetAKeyingTask(userid=myid) if my_current_task is None: flash('There are no valid keying tasks at this time, please check back later') return render_template('index.html') #testing area #my_current_task.png = '/static/images/demo.png' #db_session.commit() #cache.set(str(myid)+':current_task',my_current_task,) #determine field type goes here #This information should go in fielddefs table. resource='Recipient' #This information should go in res_ourcedefs table. attributes=['id', 'lname', 'fname', 'mname'] #retrieve field resources my_dict = cache_methods.cacheGetDict(fieldtype=my_current_task.fieldtype_id, resource=resource, attributes=attributes) #flash(my_dict[1]) #return render_template('index.html') return render_template('key.html', kt=my_current_task, auto_dict=my_dict) def delete(self, user_id): if user_id is None: pass else: flash(user_id) return render_template('index.html') def put(self, user_id): return render_template('index.html')
gpl-3.0
alvinwan/md2py
setup.py
1
1136
import sys from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = ['tests'] def finalize_options(self): TestCommand.finalize_options(self) def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) VERSION = '0.0.1' setup( name = "md2py", version = VERSION, author = "Alvin Wan", author_email = 'hi@alvinwan.com', description = ("utility converting markdown into Python abstraction"), license = "Apache", url = "http://github.com/alvinwan/md2py", packages = ['md2py'], cmdclass = {'test': PyTest}, tests_require = ['pytest'], install_requires = ['markdown', 'beautifulsoup4'], download_url = 'https://github.com/alvinwan/md2py/archive/%s.zip' % VERSION, classifiers = [ "Topic :: Utilities", ], )
apache-2.0
luca-vercelli/odoo-modules
view_mustache/report_invoice/account_invoice.py
1
4196
# -*- coding: utf-8 -*- from odoo import api, fields, models from odoo.addons import account import logging _logger = logging.getLogger(__name__) class FakeDict(dict): def __init__(self, orig_dict={}): super(FakeDict, self).__init__(orig_dict) def __getitem__(self, key): try: return super(FakeDict, self).__getitem__(key) except KeyError: if self.__hasattr__(key): return self.display_title() #FIXME ma con che contesto???? else: raise KeyError(key) def display_title(self, invoice): _logger.info("QUI STO LEGGENDO display_title dal dict") return "TODO" class ReportAccountInvoice(models.AbstractModel): """ Printing logic Extend invoice with missing attributes. Format all fields as required... """ _name = 'report.view_mustache.view_invoice_mustache' #MUST BE: report.<module name>.<report view name (=ID)> @api.model def render_html(self, docids, data=None): report_name = 'view_mustache.view_invoice_mustache' #MUST BE: <module name>.<report view name (=ID)> report_env = self.env['report'] report = report_env._get_report_from_name(report_name) orig_docs = self.env['account.invoice'].browse(docids) docs = [] #import pdb #pdb.set_trace() for doc in orig_docs: #avoid undesired DB updates doc.write = lambda self,data: self #doc.number = (doc.number or '') #errore col lambda nel __set__ doc.display_title = self.display_title(doc) doc.display_date_due = self.display_date_due(doc) doc.display_discount = self.display_discount(doc) doc.display_tax_amount_grouped = self.display_tax_amount_grouped(doc) #doc_line.display_taxes = self.display_taxes(doc_line) docs.append(doc) docargs = { 'doc_ids': docids, 'doc_model': report.model, 'docs' : docs, #self.env['account.invoice'].browse(docids), 'company': self.env.user.company_id # needed by hewader / footer partials } return report_env.render(report_name, docargs) def display_title(self, invoice): _logger.info("QUI STO LEGGENDO _display_title") if invoice.type == 'out_invoice': #FIXME is there some kind of "switch" in Python? if invoice.state == 'open' or invoice.state == 'paid': return "Invoice" elif invoice.state == 'proforma2': return "PRO-FORMA" elif invoice.state == 'draft': return "Draft Invoice" elif invoice.state == 'cancel': return "Cancelled Invoice" elif invoice.type == 'in_refund': return "Vendor Refund" elif invoice.type == 'in_invoice': return "Vendor Invoice" else: return None #FIXME function or computed field? def display_date_due(self, invoice): return invoice.date_due and invoice.type == 'out_invoice' and (invoice.state == 'open' or invoice.state == 'paid') def display_discount(self, invoice): return any([l.discount for l in invoice.invoice_line_ids]) def display_taxes(self, invoice_line): return ', '.join([(x.description or x.name) for x in invoice_line.invoice_line_tax_ids]) def display_tax_amount_grouped(self, invoice): #cfr. _get_tax_amount_by_group() map0 = {} for line in invoice.tax_line_ids: map0.setdefault(line.tax_id.tax_group_id, 0.0) map0[line.tax_id.tax_group_id] += line.amount list0 = sorted(list(map0.items()), key=lambda l: l[0].sequence) #this line is different from _get_tax_amount_by_group: map1 = [{ 'name' : l[0].name, 'amount' : l[1]} for l in list0] #FIXME I don't understand this: if len(o.tax_line_ids) > 1 else (o.tax_line_ids.tax_id.description or o.tax_line_ids.tax_id.name) return map1
gpl-3.0
mikekap/batchy
tests/futures_tests.py
1
2383
from threading import Semaphore from unittest.case import SkipTest from batchy.runloop import coro_return, runloop_coroutine from batchy.batch_coroutine import batch_coroutine, class_batch_coroutine try: from concurrent.futures import ThreadPoolExecutor import batchy.futures as batchy_futures except ImportError: batchy_futures = None print('Futures not installed; skipping futures tests.') from . import BaseTestCase CALL_COUNT = 0 @batch_coroutine() def increment(arg_lists): def increment_single(n): return n + 1 global CALL_COUNT CALL_COUNT += 1 coro_return([increment_single(*ar, **kw) for ar, kw in arg_lists]) yield class FuturesTests(BaseTestCase): def setup(self): if not batchy_futures: raise SkipTest() self.pool = ThreadPoolExecutor(1) global CALL_COUNT CALL_COUNT = 0 def test_simple_futures(self): sema = Semaphore(0) def acq(): sema.acquire() return 1 @runloop_coroutine() def rel(): sema.release() coro_return(2) yield @runloop_coroutine() def test(): r1, r2 = yield batchy_futures.submit(self.pool, acq), rel() coro_return(r1 + r2) self.assert_equals(3, test()) def test_futures_exceptions(self): def throw(): raise ValueError() @runloop_coroutine() def test(): yield batchy_futures.submit(self.pool, throw) self.assert_raises(ValueError, test) def test_batch_with_gevent(self): def call_increment(i): return increment(i) @runloop_coroutine() def test(): a, b = yield batchy_futures.submit(self.pool, call_increment, 2), increment(3) coro_return(a + b) self.assert_equals(7, test()) self.assert_equals(2, CALL_COUNT) def test_gevent_out_of_order(self): def acq(s): s.acquire() @runloop_coroutine() def test(): s = Semaphore(0) future1 = yield batchy_futures.future(self.pool.submit(acq, s)) future2 = yield batchy_futures.future(self.pool.submit(acq, s)) s.release() yield future1 s.release() yield future2 test() # shouldn't hang
apache-2.0
junbochen/pylearn2
pylearn2/scripts/tutorials/grbm_smd/test_grbm_smd.py
44
1176
import os from nose.plugins.skip import SkipTest from theano import config import pylearn2 from pylearn2.testing import no_debug_mode from pylearn2.utils.serial import load_train_file @no_debug_mode def test_train_example(): """ tests that the grbm_smd example script runs correctly """ assert config.mode != "DEBUG_MODE" path = pylearn2.__path__[0] train_example_path = os.path.join(path, 'scripts', 'tutorials', 'grbm_smd') if not os.path.isfile(os.path.join(train_example_path, 'cifar10_preprocessed_train.pkl')): raise SkipTest cwd = os.getcwd() try: os.chdir(train_example_path) train_yaml_path = os.path.join(train_example_path, 'cifar_grbm_smd.yaml') train_object = load_train_file(train_yaml_path) # Make the termination criterion really lax so that it is quick train_object.algorithm.termination_criterion.prop_decrease = 0.5 train_object.algorithm.termination_criterion.N = 1 train_object.main_loop() finally: os.chdir(cwd) if __name__ == '__main__': test_train_example()
bsd-3-clause
lancheng/flexx
flexx/react/pyscript.py
21
10446
""" Implementation of flexx.react in JS via PyScript. """ import json from ..pyscript import py2js, evaljs, evalpy from ..pyscript.parser2 import get_class_definition from .signals import Signal, SourceSignal class HasSignalsJS: """ An implementation of the HasSignals class in PyScript. It has some boilerplate code to create signal objects in JavaScript, but otherwise shares most of the code with the Python signal classes by transpiling their methods via PyScript. This ensures that the Python and JS implementation of this reactive programming system have the same API and behave the same. The Python version of this class has a ``JSCODE`` attribute that contains the auto-generated JavaScript for this class. """ __signals__ = [] def __init__(self): self._create_signals() self.connect_signals(False) def _signal_changed(self, signal): pass # can be overloaded in subclasses def connect_signals(self, raise_on_fail=True): success = True for name in self.__signals__: if name in self.__props__: continue s = self[name] if s.not_connected: connected = s.connect(raise_on_fail) # dont combine this with next line success = success and connected return success def _create_property(obj, name, private_name, initial): def getter(): return obj[private_name] def setter(): raise ValueError(name + ' is not settable') obj[private_name] = initial opts = {'enumerable': True, 'configurable': False, 'get': getter, 'set': setter} Object.defineProperty(obj, name, opts) def _create_signals(): self.__props__ = [] # todo: get rid of this? for name in self.__signals__: func = self['_' + name + '_func'] func._name = name creator = self['_create_' + func._signal_type] signal = creator.call(self, func, func._upstream) signal.signal_type = func._signal_type self._create_property(self, name, '_' + name + '_signal', signal) def _create_PySignal(func, upstream, selff): # proxy for Pair return self._create_SourceSignal(func, upstream, selff) def _create_PyInputSignal(func, upstream, selff): # proxy for Pair return self._create_InputSignal(func, upstream, selff) def _create_SourceSignal(func, upstream, selff): selff = self._create_Signal(func, upstream, selff) SourceSignal__update_value_from_py SourceSignal__set_from_py return selff def _create_InputSignal(func, upstream): def selff(*args): if not len(args): return selff._get_value() elif len(args) == 1: return selff._set(args[0]) else: raise ValueError('Setting input signal %r requires exactly one argument.' % selff._name) return self._create_SourceSignal(func, upstream, selff) def _create_LazySignal(func, upstream, selff=None): selff = self._create_Signal(func, upstream, selff) selff._active = False return selff def _create_Signal(func, upstream, selff=None): # We create the selff function which then serves as the signal object # that we populate with attributres, properties and functions. obj = this if selff is None: def selff(*args): if not len(args): return selff._get_value() else: raise RuntimeError('Can only set signal values of InputSignal objects, ' 'which signal %r is not.' % selff._name) # Create public attributes self._create_property(selff, 'value', '_value', undefined) self._create_property(selff, 'last_value', '_last_value', undefined) self._create_property(selff, 'timestamp', '_timestamp', 0) self._create_property(selff, 'last_timestamp', '_last_timestamp', 0) self._create_property(selff, 'not_connected', '_not_connected', 'No connection attempt yet.') #self._create_property(selff, 'name', '_name', func.name) already is a property selff._name = func._name # Create private attributes selff._IS_SIGNAL = True selff._active = True selff._func = func selff._status = 3 selff._count = 0 selff.__self__ = obj # note: not a weakref... selff._upstream_given = upstream selff._upstream = [] selff._downstream = [] selff._upstream_reconnect = [] selff._downstream_reconnect = [] # Functions that we re-use from the Python implementation of signals BaseSignal_connect_from_py BaseSignal_disconnect_from_py BaseSignal__subscribe_from_py BaseSignal__unsubscribe_from_py BaseSignal__get_value_from_py BaseSignal__update_value_from_py BaseSignal__set_status_from_py BaseSignal__seek_signal_from_py # Some functions need JS specifics def _resolve_signals(): selff._upstream = [] selff._upstream_reconnect = [] for fullname in selff._upstream_given: nameparts = fullname.split('.') # Obtain first part of path from the frame that we have ob = obj[nameparts[0]] msg = selff._seek_signal(fullname, nameparts[1:], ob) if msg: selff._upstream = [] return msg return False # no error def _save_update(): try: selff() except SignalValueError: pass except Exception as err: #print('Error updating signal:', err.stack) console.error('Error updating signal: ' + err) def _set_value(value): if value is undefined: self._status = 3 if (self._count == 0) else 0 return # new tick, but no update of value selff._last_value = selff._value selff._value = value selff._last_timestamp = selff._timestamp selff._count += 1 selff._timestamp = Date().getTime() / 1000 selff._status = 0 obj._signal_changed(selff) def _call_func(*args): return func.apply(obj, args) # Put functions that we defined here on the signal selff._resolve_signals = _resolve_signals selff._save_update = _save_update selff._set_value = _set_value selff._call_func = _call_func return selff def patch_HasSignals(jscode): """ Insert code from the Python implementation of signals. """ for signal_type, cls in [('BaseSignal', Signal), ('SourceSignal', SourceSignal)]: for name in ('connect', 'disconnect', '_subscribe', '_unsubscribe', '_set', '_get_value', '_update_value', '_set_status', '_seek_signal'): if name in cls.__dict__: code = py2js(cls.__dict__[name], 'selff.' + name, indent=1, docstrings=False) template = '%s_%s_from_py;' % (signal_type, name) jscode = jscode.replace(template, code.lstrip()) assert 'from_py' not in jscode return jscode HasSignalsJS.JSCODE = patch_HasSignals(py2js(HasSignalsJS)) def create_js_signals_class(cls, cls_name, base_class='HasSignals.prototype'): """ Create the JS equivalent of a subclass of the HasSignals class. Given a Python class with signals attached to it, this creates the code for the JS version of this class. Apart from converting the signals, it also supports class constants that are int/float/str, or a tuple/list thereof. """ assert cls_name != 'HasSignals' # we need this special class above instead signals = [] total_code = [] funcs_code = [] # functions and signals go below class constants err = ('Objects on JS HasSignals classes can only be int, float, str, ' 'or a list/tuple thereof. Not %s -> %r.') total_code.extend(get_class_definition(cls_name, base_class)) prefix = '' if cls_name.count('.') else 'var ' total_code[0] = prefix + total_code[0] for name, val in sorted(cls.__dict__.items()): if isinstance(val, Signal): signals.append(name) funcname = '_' + name + '_func' # Add function def code = py2js(val._func, cls_name + '.prototype.' + funcname) code = code.replace('super()', base_class) # fix super funcs_code.append(code) # Add upstream signal names to the function object t = '%s.prototype.%s._upstream = %r;\n' funcs_code.append(t % (cls_name, funcname, val._upstream_given)) # Add type of signal too t = '%s.prototype.%s._signal_type = %r;\n' signal_type = val.__class__.__name__ funcs_code.append(t % (cls_name, funcname, signal_type)) elif callable(val): code = py2js(val, cls_name + '.prototype.' + name) code = code.replace('super()', base_class) # fix super funcs_code.append(code) elif name.startswith('__'): pass # we create our own __signals__ list else: try: serialized = json.dumps(val) except Exception as err: # pragma: no cover raise ValueError('Attributes on JS HasSignals class must be JSON compatible.\n%s' % str(err)) total_code.append('%s.prototype.%s = JSON.parse(%r)' % (cls_name, name, serialized)) # Insert __signals__ that we found if base_class in ('Object', 'HasSignals.prototype'): t = '%s.prototype.__signals__ = %r.sort();' total_code.append(t % (cls_name, signals)) else: t = '%s.prototype.__signals__ = %s.__signals__.concat(%r).sort();' total_code.append(t % (cls_name, base_class, signals)) total_code.extend(funcs_code) return '\n'.join(total_code)
bsd-2-clause
Scarygami/gae-gcs-push2deploy-secrets
lib/oauth2client/xsrfutil.py
230
3368
#!/usr/bin/python2.5 # # Copyright 2010 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """Helper methods for creating & verifying XSRF tokens.""" __authors__ = [ '"Doug Coker" <dcoker@google.com>', '"Joe Gregorio" <jcgregorio@google.com>', ] import base64 import hmac import os # for urandom import time from oauth2client import util # Delimiter character DELIMITER = ':' # 1 hour in seconds DEFAULT_TIMEOUT_SECS = 1*60*60 @util.positional(2) def generate_token(key, user_id, action_id="", when=None): """Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used. Returns: A string XSRF protection token. """ when = when or int(time.time()) digester = hmac.new(key) digester.update(str(user_id)) digester.update(DELIMITER) digester.update(action_id) digester.update(DELIMITER) digester.update(str(when)) digest = digester.digest() token = base64.urlsafe_b64encode('%s%s%d' % (digest, DELIMITER, when)) return token @util.positional(3) def validate_token(key, token, user_id, action_id="", current_time=None): """Validates that the given token authorizes the user for the action. Tokens are invalid if the time of issue is too old or if the token does not match what generateToken outputs (i.e. the token was forged). Args: key: secret key to use. token: a string of the token generated by generateToken. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. Returns: A boolean - True if the user is authorized for the action, False otherwise. """ if not token: return False try: decoded = base64.urlsafe_b64decode(str(token)) token_time = long(decoded.split(DELIMITER)[-1]) except (TypeError, ValueError): return False if current_time is None: current_time = time.time() # If the token is too old it's not valid. if current_time - token_time > DEFAULT_TIMEOUT_SECS: return False # The given token should match the generated one with the same time. expected_token = generate_token(key, user_id, action_id=action_id, when=token_time) if len(token) != len(expected_token): return False # Perform constant time comparison to avoid timing attacks different = 0 for x, y in zip(token, expected_token): different |= ord(x) ^ ord(y) if different: return False return True
apache-2.0
decvalts/landlab
landlab/grid/unstructured/status.py
1
2868
import numpy as np # Define the boundary-type codes #: Indicates a node is *core*. CORE_NODE = 0 #: Indicates a boundary node is has a fixed values. FIXED_VALUE_BOUNDARY = 1 #: Indicates a boundary node is has a fixed gradient. FIXED_GRADIENT_BOUNDARY = 2 #: Indicates a boundary node is wrap-around. TRACKS_CELL_BOUNDARY = 3 #: Indicates a boundary node is closed CLOSED_BOUNDARY = 4 BOUNDARY_STATUS_FLAGS_LIST = [ FIXED_VALUE_BOUNDARY, FIXED_GRADIENT_BOUNDARY, TRACKS_CELL_BOUNDARY, CLOSED_BOUNDARY, ] BOUNDARY_STATUS_FLAGS = set(BOUNDARY_STATUS_FLAGS_LIST) class StatusGrid(object): def __init__(self, node_status): self._node_status = np.array(node_status) @property def node_status(self): """Status of nodes Return an array of the status of a grid's nodes. The node status can be one of the following: - `CORE_NODE` - `FIXED_VALUE_BOUNDARY` - `FIXED_GRADIENT_BOUNDARY ` - `TRACKS_CELL_BOUNDARY` - `CLOSED_BOUNDARY ` """ return self._node_status @node_status.setter def node_status(self, node_status): self._node_status = node_status def active_nodes(self): """ Node IDs of all active (core & open boundary) nodes. core_nodes will return just core nodes. """ (active_node_ids, ) = np.where(self.node_status != CLOSED_BOUNDARY) return active_node_ids def core_nodes(self): """Node IDs of all core nodes. """ (core_node_ids, ) = np.where(self.node_status == CORE_NODE) return core_node_ids def boundary_nodes(self): """Node IDs of all boundary nodes. """ (boundary_node_ids, ) = np.where(self.node_status != CORE_NODE) return boundary_node_ids def open_boundary_nodes(self): """Node id of all open boundary nodes. """ (open_boundary_node_ids, ) = np.where( (self.node_status != CLOSED_BOUNDARY) & (self.node_status != CORE_NODE)) return open_boundary_node_ids def closed_boundary_nodes(self): """Node id of all closed boundary nodes. """ (closed_boundary_node_ids, ) = np.where( self.node_status == CLOSED_BOUNDARY) return closed_boundary_node_ids def fixed_gradient_boundary_nodes(self): """Node id of all fixed gradient boundary nodes """ (fixed_gradient_boundary_node_ids, ) = np.where( self.node_status == FIXED_GRADIENT_BOUNDARY) return fixed_gradient_boundary_node_ids def fixed_value_boundary_nodes(self): """Node id of all fixed value boundary nodes """ (fixed_value_boundary_node_ids, ) = np.where( self.node_status == FIXED_VALUE_BOUNDARY) return fixed_value_boundary_node_ids
mit
MoroGasper/client
client/account/verify.py
1
1761
"""Copyright (C) 2013 COLDWELL AG 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 time import gevent, requests from gevent.event import AsyncResult from ..api import proto keys = dict() def request_key(hoster): keys[hoster] = AsyncResult() proto.send("backend", command="api.getsecret", payload=dict(hoster=hoster)) return _get(hoster) def _get(hoster): try: return keys[hoster].get(timeout=8) except gevent.Timeout: print "timeout requesting secret for hoster", hoster return None, None def get_key(hoster): if hoster in keys: value, expire = _get(hoster) print value, expire if expire < time.time()-30: value, expire = request_key(hoster) else: value, expire = request_key(hoster) return value def set_secret(hoster, secret, timeleft): if hoster not in keys: keys[hoster] = AsyncResult() keys[hoster].set((secret, time.time()+timeleft)) def get_agent(hoster): default = requests.utils.default_user_agent() key = get_key(hoster) if key is None: return default else: return "{} (download.am; ID {})".format(default, get_key(hoster))
gpl-3.0
Ernesto99/odoo
addons/hr_payroll/wizard/hr_payroll_contribution_register_report.py
337
2074
# -*- 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/>. # ############################################################################## import time from datetime import datetime from dateutil import relativedelta from openerp.osv import fields, osv class payslip_lines_contribution_register(osv.osv_memory): _name = 'payslip.lines.contribution.register' _description = 'PaySlip Lines by Contribution Registers' _columns = { 'date_from': fields.date('Date From', required=True), 'date_to': fields.date('Date To', required=True), } _defaults = { 'date_from': lambda *a: time.strftime('%Y-%m-01'), 'date_to': lambda *a: str(datetime.now() + relativedelta.relativedelta(months=+1, day=1, days=-1))[:10], } def print_report(self, cr, uid, ids, context=None): datas = { 'ids': context.get('active_ids', []), 'model': 'hr.contribution.register', 'form': self.read(cr, uid, ids, context=context)[0] } return self.pool['report'].get_action( cr, uid, [], 'hr_payroll.report_contributionregister', data=datas, context=context ) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ojengwa/django-1
tests/generic_views/urls.py
194
14571
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from django.contrib.auth import views as auth_views from django.contrib.auth.decorators import login_required from django.views.decorators.cache import cache_page from django.views.generic import TemplateView from . import models, views urlpatterns = [ # TemplateView url(r'^template/no_template/$', TemplateView.as_view()), url(r'^template/login_required/$', login_required(TemplateView.as_view())), url(r'^template/simple/(?P<foo>\w+)/$', TemplateView.as_view(template_name='generic_views/about.html')), url(r'^template/custom/(?P<foo>\w+)/$', views.CustomTemplateView.as_view(template_name='generic_views/about.html')), url(r'^template/content_type/$', TemplateView.as_view(template_name='generic_views/robots.txt', content_type='text/plain')), url(r'^template/cached/(?P<foo>\w+)/$', cache_page(2.0)(TemplateView.as_view(template_name='generic_views/about.html'))), # DetailView url(r'^detail/obj/$', views.ObjectDetail.as_view()), url(r'^detail/artist/(?P<pk>[0-9]+)/$', views.ArtistDetail.as_view(), name="artist_detail"), url(r'^detail/author/(?P<pk>[0-9]+)/$', views.AuthorDetail.as_view(), name="author_detail"), url(r'^detail/author/bycustompk/(?P<foo>[0-9]+)/$', views.AuthorDetail.as_view(pk_url_kwarg='foo')), url(r'^detail/author/byslug/(?P<slug>[\w-]+)/$', views.AuthorDetail.as_view()), url(r'^detail/author/bycustomslug/(?P<foo>[\w-]+)/$', views.AuthorDetail.as_view(slug_url_kwarg='foo')), url(r'^detail/author/bypkignoreslug/(?P<pk>[0-9]+)-(?P<slug>[\w-]+)/$', views.AuthorDetail.as_view()), url(r'^detail/author/bypkandslug/(?P<pk>[0-9]+)-(?P<slug>[\w-]+)/$', views.AuthorDetail.as_view(query_pk_and_slug=True)), url(r'^detail/author/(?P<pk>[0-9]+)/template_name_suffix/$', views.AuthorDetail.as_view(template_name_suffix='_view')), url(r'^detail/author/(?P<pk>[0-9]+)/template_name/$', views.AuthorDetail.as_view(template_name='generic_views/about.html')), url(r'^detail/author/(?P<pk>[0-9]+)/context_object_name/$', views.AuthorDetail.as_view(context_object_name='thingy')), url(r'^detail/author/(?P<pk>[0-9]+)/dupe_context_object_name/$', views.AuthorDetail.as_view(context_object_name='object')), url(r'^detail/page/(?P<pk>[0-9]+)/field/$', views.PageDetail.as_view()), url(r'^detail/author/invalid/url/$', views.AuthorDetail.as_view()), url(r'^detail/author/invalid/qs/$', views.AuthorDetail.as_view(queryset=None)), url(r'^detail/nonmodel/1/$', views.NonModelDetail.as_view()), url(r'^detail/doesnotexist/(?P<pk>[0-9]+)/$', views.ObjectDoesNotExistDetail.as_view()), # FormView url(r'^contact/$', views.ContactView.as_view()), # Create/UpdateView url(r'^edit/artists/create/$', views.ArtistCreate.as_view()), url(r'^edit/artists/(?P<pk>[0-9]+)/update/$', views.ArtistUpdate.as_view()), url(r'^edit/authors/create/naive/$', views.NaiveAuthorCreate.as_view()), url(r'^edit/authors/create/redirect/$', views.NaiveAuthorCreate.as_view(success_url='/edit/authors/create/')), url(r'^edit/authors/create/interpolate_redirect/$', views.NaiveAuthorCreate.as_view(success_url='/edit/author/%(id)d/update/')), url(r'^edit/authors/create/interpolate_redirect_nonascii/$', views.NaiveAuthorCreate.as_view(success_url='/%C3%A9dit/author/{id}/update/')), url(r'^edit/authors/create/restricted/$', views.AuthorCreateRestricted.as_view()), url(r'^[eé]dit/authors/create/$', views.AuthorCreate.as_view()), url(r'^edit/authors/create/special/$', views.SpecializedAuthorCreate.as_view()), url(r'^edit/author/(?P<pk>[0-9]+)/update/naive/$', views.NaiveAuthorUpdate.as_view()), url(r'^edit/author/(?P<pk>[0-9]+)/update/redirect/$', views.NaiveAuthorUpdate.as_view(success_url='/edit/authors/create/')), url(r'^edit/author/(?P<pk>[0-9]+)/update/interpolate_redirect/$', views.NaiveAuthorUpdate.as_view(success_url='/edit/author/%(id)d/update/')), url(r'^edit/author/(?P<pk>[0-9]+)/update/interpolate_redirect_nonascii/$', views.NaiveAuthorUpdate.as_view(success_url='/%C3%A9dit/author/{id}/update/')), url(r'^[eé]dit/author/(?P<pk>[0-9]+)/update/$', views.AuthorUpdate.as_view()), url(r'^edit/author/update/$', views.OneAuthorUpdate.as_view()), url(r'^edit/author/(?P<pk>[0-9]+)/update/special/$', views.SpecializedAuthorUpdate.as_view()), url(r'^edit/author/(?P<pk>[0-9]+)/delete/naive/$', views.NaiveAuthorDelete.as_view()), url(r'^edit/author/(?P<pk>[0-9]+)/delete/redirect/$', views.NaiveAuthorDelete.as_view(success_url='/edit/authors/create/')), url(r'^edit/author/(?P<pk>[0-9]+)/delete/interpolate_redirect/$', views.NaiveAuthorDelete.as_view(success_url='/edit/authors/create/?deleted=%(id)s')), url(r'^edit/author/(?P<pk>[0-9]+)/delete/interpolate_redirect_nonascii/$', views.NaiveAuthorDelete.as_view(success_url='/%C3%A9dit/authors/create/?deleted={id}')), url(r'^edit/author/(?P<pk>[0-9]+)/delete/$', views.AuthorDelete.as_view()), url(r'^edit/author/(?P<pk>[0-9]+)/delete/special/$', views.SpecializedAuthorDelete.as_view()), # ArchiveIndexView url(r'^dates/books/$', views.BookArchive.as_view()), url(r'^dates/books/context_object_name/$', views.BookArchive.as_view(context_object_name='thingies')), url(r'^dates/books/allow_empty/$', views.BookArchive.as_view(allow_empty=True)), url(r'^dates/books/template_name/$', views.BookArchive.as_view(template_name='generic_views/list.html')), url(r'^dates/books/template_name_suffix/$', views.BookArchive.as_view(template_name_suffix='_detail')), url(r'^dates/books/invalid/$', views.BookArchive.as_view(queryset=None)), url(r'^dates/books/paginated/$', views.BookArchive.as_view(paginate_by=10)), url(r'^dates/books/reverse/$', views.BookArchive.as_view(queryset=models.Book.objects.order_by('pubdate'))), url(r'^dates/books/by_month/$', views.BookArchive.as_view(date_list_period='month')), url(r'^dates/booksignings/$', views.BookSigningArchive.as_view()), url(r'^dates/books/sortedbyname/$', views.BookArchive.as_view(ordering='name')), url(r'^dates/books/sortedbynamedec/$', views.BookArchive.as_view(ordering='-name')), # ListView url(r'^list/dict/$', views.DictList.as_view()), url(r'^list/dict/paginated/$', views.DictList.as_view(paginate_by=1)), url(r'^list/artists/$', views.ArtistList.as_view(), name="artists_list"), url(r'^list/authors/$', views.AuthorList.as_view(), name="authors_list"), url(r'^list/authors/paginated/$', views.AuthorList.as_view(paginate_by=30)), url(r'^list/authors/paginated/(?P<page>[0-9]+)/$', views.AuthorList.as_view(paginate_by=30)), url(r'^list/authors/paginated-orphaned/$', views.AuthorList.as_view(paginate_by=30, paginate_orphans=2)), url(r'^list/authors/notempty/$', views.AuthorList.as_view(allow_empty=False)), url(r'^list/authors/notempty/paginated/$', views.AuthorList.as_view(allow_empty=False, paginate_by=2)), url(r'^list/authors/template_name/$', views.AuthorList.as_view(template_name='generic_views/list.html')), url(r'^list/authors/template_name_suffix/$', views.AuthorList.as_view(template_name_suffix='_objects')), url(r'^list/authors/context_object_name/$', views.AuthorList.as_view(context_object_name='author_list')), url(r'^list/authors/dupe_context_object_name/$', views.AuthorList.as_view(context_object_name='object_list')), url(r'^list/authors/invalid/$', views.AuthorList.as_view(queryset=None)), url(r'^list/authors/paginated/custom_class/$', views.AuthorList.as_view(paginate_by=5, paginator_class=views.CustomPaginator)), url(r'^list/authors/paginated/custom_page_kwarg/$', views.AuthorList.as_view(paginate_by=30, page_kwarg='pagina')), url(r'^list/authors/paginated/custom_constructor/$', views.AuthorListCustomPaginator.as_view()), url(r'^list/books/sorted/$', views.BookList.as_view(ordering='name')), url(r'^list/books/sortedbypagesandnamedec/$', views.BookList.as_view(ordering=('pages', '-name'))), # YearArchiveView # Mixing keyword and positional captures below is intentional; the views # ought to be able to accept either. url(r'^dates/books/(?P<year>[0-9]{4})/$', views.BookYearArchive.as_view()), url(r'^dates/books/(?P<year>[0-9]{4})/make_object_list/$', views.BookYearArchive.as_view(make_object_list=True)), url(r'^dates/books/(?P<year>[0-9]{4})/allow_empty/$', views.BookYearArchive.as_view(allow_empty=True)), url(r'^dates/books/(?P<year>[0-9]{4})/allow_future/$', views.BookYearArchive.as_view(allow_future=True)), url(r'^dates/books/(?P<year>[0-9]{4})/paginated/$', views.BookYearArchive.as_view(make_object_list=True, paginate_by=30)), url(r'^dates/books/(?P<year>\d{4})/sortedbyname/$', views.BookYearArchive.as_view(make_object_list=True, ordering='name')), url(r'^dates/books/(?P<year>\d{4})/sortedbypageandnamedec/$', views.BookYearArchive.as_view(make_object_list=True, ordering=('pages', '-name'))), url(r'^dates/books/no_year/$', views.BookYearArchive.as_view()), url(r'^dates/books/(?P<year>[0-9]{4})/reverse/$', views.BookYearArchive.as_view(queryset=models.Book.objects.order_by('pubdate'))), url(r'^dates/booksignings/(?P<year>[0-9]{4})/$', views.BookSigningYearArchive.as_view()), # MonthArchiveView url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/$', views.BookMonthArchive.as_view()), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/$', views.BookMonthArchive.as_view(month_format='%m')), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/allow_empty/$', views.BookMonthArchive.as_view(allow_empty=True)), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/allow_future/$', views.BookMonthArchive.as_view(allow_future=True)), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/paginated/$', views.BookMonthArchive.as_view(paginate_by=30)), url(r'^dates/books/(?P<year>[0-9]{4})/no_month/$', views.BookMonthArchive.as_view()), url(r'^dates/booksignings/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/$', views.BookSigningMonthArchive.as_view()), # WeekArchiveView url(r'^dates/books/(?P<year>[0-9]{4})/week/(?P<week>[0-9]{1,2})/$', views.BookWeekArchive.as_view()), url(r'^dates/books/(?P<year>[0-9]{4})/week/(?P<week>[0-9]{1,2})/allow_empty/$', views.BookWeekArchive.as_view(allow_empty=True)), url(r'^dates/books/(?P<year>[0-9]{4})/week/(?P<week>[0-9]{1,2})/allow_future/$', views.BookWeekArchive.as_view(allow_future=True)), url(r'^dates/books/(?P<year>[0-9]{4})/week/(?P<week>[0-9]{1,2})/paginated/$', views.BookWeekArchive.as_view(paginate_by=30)), url(r'^dates/books/(?P<year>[0-9]{4})/week/no_week/$', views.BookWeekArchive.as_view()), url(r'^dates/books/(?P<year>[0-9]{4})/week/(?P<week>[0-9]{1,2})/monday/$', views.BookWeekArchive.as_view(week_format='%W')), url(r'^dates/booksignings/(?P<year>[0-9]{4})/week/(?P<week>[0-9]{1,2})/$', views.BookSigningWeekArchive.as_view()), # DayArchiveView url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/$', views.BookDayArchive.as_view()), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/$', views.BookDayArchive.as_view(month_format='%m')), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/allow_empty/$', views.BookDayArchive.as_view(allow_empty=True)), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/allow_future/$', views.BookDayArchive.as_view(allow_future=True)), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/allow_empty_and_future/$', views.BookDayArchive.as_view(allow_empty=True, allow_future=True)), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/paginated/$', views.BookDayArchive.as_view(paginate_by=True)), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/no_day/$', views.BookDayArchive.as_view()), url(r'^dates/booksignings/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/$', views.BookSigningDayArchive.as_view()), # TodayArchiveView url(r'^dates/books/today/$', views.BookTodayArchive.as_view()), url(r'^dates/books/today/allow_empty/$', views.BookTodayArchive.as_view(allow_empty=True)), url(r'^dates/booksignings/today/$', views.BookSigningTodayArchive.as_view()), # DateDetailView url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/(?P<pk>[0-9]+)/$', views.BookDetail.as_view()), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/(?P<pk>[0-9]+)/$', views.BookDetail.as_view(month_format='%m')), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/(?P<pk>[0-9]+)/allow_future/$', views.BookDetail.as_view(allow_future=True)), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/nopk/$', views.BookDetail.as_view()), url(r'^dates/books/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/byslug/(?P<slug>[\w-]+)/$', views.BookDetail.as_view()), url(r'^dates/books/get_object_custom_queryset/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/(?P<pk>[0-9]+)/$', views.BookDetailGetObjectCustomQueryset.as_view()), url(r'^dates/booksignings/(?P<year>[0-9]{4})/(?P<month>[a-z]{3})/(?P<day>[0-9]{1,2})/(?P<pk>[0-9]+)/$', views.BookSigningDetail.as_view()), # Useful for testing redirects url(r'^accounts/login/$', auth_views.login) ]
bsd-3-clause
sander76/home-assistant
homeassistant/helpers/debounce.py
3
3875
"""Debounce helper.""" from __future__ import annotations import asyncio from logging import Logger from typing import Any, Awaitable, Callable from homeassistant.core import HassJob, HomeAssistant, callback class Debouncer: """Class to rate limit calls to a specific command.""" def __init__( self, hass: HomeAssistant, logger: Logger, *, cooldown: float, immediate: bool, function: Callable[..., Awaitable[Any]] | None = None, ): """Initialize debounce. immediate: indicate if the function needs to be called right away and wait <cooldown> until executing next invocation. function: optional and can be instantiated later. """ self.hass = hass self.logger = logger self._function = function self.cooldown = cooldown self.immediate = immediate self._timer_task: asyncio.TimerHandle | None = None self._execute_at_end_of_timer: bool = False self._execute_lock = asyncio.Lock() self._job: HassJob | None = None if function is None else HassJob(function) @property def function(self) -> Callable[..., Awaitable[Any]] | None: """Return the function being wrapped by the Debouncer.""" return self._function @function.setter def function(self, function: Callable[..., Awaitable[Any]]) -> None: """Update the function being wrapped by the Debouncer.""" self._function = function if self._job is None or function != self._job.target: self._job = HassJob(function) async def async_call(self) -> None: """Call the function.""" assert self._job is not None if self._timer_task: if not self._execute_at_end_of_timer: self._execute_at_end_of_timer = True return # Locked means a call is in progress. Any call is good, so abort. if self._execute_lock.locked(): return if not self.immediate: self._execute_at_end_of_timer = True self._schedule_timer() return async with self._execute_lock: # Abort if timer got set while we're waiting for the lock. if self._timer_task: return task = self.hass.async_run_hass_job(self._job) if task: await task self._schedule_timer() async def _handle_timer_finish(self) -> None: """Handle a finished timer.""" assert self._job is not None self._timer_task = None if not self._execute_at_end_of_timer: return self._execute_at_end_of_timer = False # Locked means a call is in progress. Any call is good, so abort. if self._execute_lock.locked(): return async with self._execute_lock: # Abort if timer got set while we're waiting for the lock. if self._timer_task: return # type: ignore try: task = self.hass.async_run_hass_job(self._job) if task: await task except Exception: # pylint: disable=broad-except self.logger.exception("Unexpected exception from %s", self.function) self._schedule_timer() @callback def async_cancel(self) -> None: """Cancel any scheduled call.""" if self._timer_task: self._timer_task.cancel() self._timer_task = None self._execute_at_end_of_timer = False @callback def _schedule_timer(self) -> None: """Schedule a timer.""" self._timer_task = self.hass.loop.call_later( self.cooldown, lambda: self.hass.async_create_task(self._handle_timer_finish()), )
apache-2.0
adobecs5/urp2015
lib/python3.4/site-packages/setuptools/command/build_py.py
155
8644
from glob import glob from distutils.util import convert_path import distutils.command.build_py as orig import os import sys import fnmatch import textwrap try: from setuptools.lib2to3_ex import Mixin2to3 except ImportError: class Mixin2to3: def run_2to3(self, files, doctests=True): "do nothing" class build_py(orig.build_py, Mixin2to3): """Enhanced 'build_py' command that includes data files with packages The data files are specified via a 'package_data' argument to 'setup()'. See 'setuptools.dist.Distribution' for more details. Also, this version of the 'build_py' command allows you to specify both 'py_modules' and 'packages' in the same setup operation. """ def finalize_options(self): orig.build_py.finalize_options(self) self.package_data = self.distribution.package_data self.exclude_package_data = (self.distribution.exclude_package_data or {}) if 'data_files' in self.__dict__: del self.__dict__['data_files'] self.__updated_files = [] self.__doctests_2to3 = [] def run(self): """Build modules, packages, and copy data files to build directory""" if not self.py_modules and not self.packages: return if self.py_modules: self.build_modules() if self.packages: self.build_packages() self.build_package_data() self.run_2to3(self.__updated_files, False) self.run_2to3(self.__updated_files, True) self.run_2to3(self.__doctests_2to3, True) # Only compile actual .py files, using our base class' idea of what our # output files are. self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0)) def __getattr__(self, attr): if attr == 'data_files': # lazily compute data files self.data_files = files = self._get_data_files() return files return orig.build_py.__getattr__(self, attr) def build_module(self, module, module_file, package): outfile, copied = orig.build_py.build_module(self, module, module_file, package) if copied: self.__updated_files.append(outfile) return outfile, copied def _get_data_files(self): """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" self.analyze_manifest() data = [] for package in self.packages or (): # Locate package source directory src_dir = self.get_package_dir(package) # Compute package build directory build_dir = os.path.join(*([self.build_lib] + package.split('.'))) # Length of path to strip from found files plen = len(src_dir) + 1 # Strip directory from globbed filenames filenames = [ file[plen:] for file in self.find_data_files(package, src_dir) ] data.append((package, src_dir, build_dir, filenames)) return data def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" globs = (self.package_data.get('', []) + self.package_data.get(package, [])) files = self.manifest_files.get(package, [])[:] for pattern in globs: # Each pattern has to be converted to a platform-specific path files.extend(glob(os.path.join(src_dir, convert_path(pattern)))) return self.exclude_data_files(package, src_dir, files) def build_package_data(self): """Copy data files into build directory""" for package, src_dir, build_dir, filenames in self.data_files: for filename in filenames: target = os.path.join(build_dir, filename) self.mkpath(os.path.dirname(target)) srcfile = os.path.join(src_dir, filename) outf, copied = self.copy_file(srcfile, target) srcfile = os.path.abspath(srcfile) if (copied and srcfile in self.distribution.convert_2to3_doctests): self.__doctests_2to3.append(outf) def analyze_manifest(self): self.manifest_files = mf = {} if not self.distribution.include_package_data: return src_dirs = {} for package in self.packages or (): # Locate package source directory src_dirs[assert_relative(self.get_package_dir(package))] = package self.run_command('egg_info') ei_cmd = self.get_finalized_command('egg_info') for path in ei_cmd.filelist.files: d, f = os.path.split(assert_relative(path)) prev = None oldf = f while d and d != prev and d not in src_dirs: prev = d d, df = os.path.split(d) f = os.path.join(df, f) if d in src_dirs: if path.endswith('.py') and f == oldf: continue # it's a module, not data mf.setdefault(src_dirs[d], []).append(path) def get_data_files(self): pass # kludge 2.4 for lazy computation if sys.version < "2.4": # Python 2.4 already has this code def get_outputs(self, include_bytecode=1): """Return complete list of files copied to the build directory This includes both '.py' files and data files, as well as '.pyc' and '.pyo' files if 'include_bytecode' is true. (This method is needed for the 'install_lib' command to do its job properly, and to generate a correct installation manifest.) """ return orig.build_py.get_outputs(self, include_bytecode) + [ os.path.join(build_dir, filename) for package, src_dir, build_dir, filenames in self.data_files for filename in filenames ] def check_package(self, package, package_dir): """Check namespace packages' __init__ for declare_namespace""" try: return self.packages_checked[package] except KeyError: pass init_py = orig.build_py.check_package(self, package, package_dir) self.packages_checked[package] = init_py if not init_py or not self.distribution.namespace_packages: return init_py for pkg in self.distribution.namespace_packages: if pkg == package or pkg.startswith(package + '.'): break else: return init_py f = open(init_py, 'rbU') if 'declare_namespace'.encode() not in f.read(): from distutils.errors import DistutilsError raise DistutilsError( "Namespace package problem: %s is a namespace package, but " "its\n__init__.py does not call declare_namespace()! Please " 'fix it.\n(See the setuptools manual under ' '"Namespace Packages" for details.)\n"' % (package,) ) f.close() return init_py def initialize_options(self): self.packages_checked = {} orig.build_py.initialize_options(self) def get_package_dir(self, package): res = orig.build_py.get_package_dir(self, package) if self.distribution.src_root is not None: return os.path.join(self.distribution.src_root, res) return res def exclude_data_files(self, package, src_dir, files): """Filter filenames for package's data files in 'src_dir'""" globs = (self.exclude_package_data.get('', []) + self.exclude_package_data.get(package, [])) bad = [] for pattern in globs: bad.extend( fnmatch.filter( files, os.path.join(src_dir, convert_path(pattern)) ) ) bad = dict.fromkeys(bad) seen = {} return [ f for f in files if f not in bad and f not in seen and seen.setdefault(f, 1) # ditch dupes ] def assert_relative(path): if not os.path.isabs(path): return path from distutils.errors import DistutilsSetupError msg = textwrap.dedent(""" Error: setup script specifies an absolute path: %s setup() arguments must *always* be /-separated paths relative to the setup.py directory, *never* absolute paths. """).lstrip() % path raise DistutilsSetupError(msg)
apache-2.0
danieljaouen/ansible
lib/ansible/executor/powershell/module_manifest.py
13
11466
# (c) 2018 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 import base64 import json import os import pkgutil import random import re from distutils.version import LooseVersion from ansible import constants as C from ansible.errors import AnsibleError from ansible.module_utils._text import to_bytes, to_text from ansible.plugins.loader import ps_module_utils_loader class PSModuleDepFinder(object): def __init__(self): self.ps_modules = dict() self.exec_scripts = dict() # by defining an explicit dict of cs utils and where they are used, we # can potentially save time by not adding the type multiple times if it # isn't needed self.cs_utils_wrapper = dict() self.cs_utils_module = dict() self.ps_version = None self.os_version = None self.become = False self._re_cs_module = re.compile(to_bytes(r'(?i)^using\s(Ansible\..+);$')) self._re_cs_in_ps_module = re.compile(to_bytes(r'(?i)^#\s*ansiblerequires\s+-csharputil\s+(Ansible\..+)')) self._re_module = re.compile(to_bytes(r'(?i)^#\s*requires\s+\-module(?:s?)\s*(Ansible\.ModuleUtils\..+)')) self._re_wrapper = re.compile(to_bytes(r'(?i)^#\s*ansiblerequires\s+-wrapper\s+(\w*)')) self._re_ps_version = re.compile(to_bytes(r'(?i)^#requires\s+\-version\s+([0-9]+(\.[0-9]+){0,3})$')) self._re_os_version = re.compile(to_bytes(r'(?i)^#ansiblerequires\s+\-osversion\s+([0-9]+(\.[0-9]+){0,3})$')) self._re_become = re.compile(to_bytes(r'(?i)^#ansiblerequires\s+\-become$')) def scan_module(self, module_data, wrapper=False, powershell=True): lines = module_data.split(b'\n') module_utils = set() if wrapper: cs_utils = self.cs_utils_wrapper else: cs_utils = self.cs_utils_module if powershell: checks = [ # PS module contains '#Requires -Module Ansible.ModuleUtils.*' (self._re_module, self.ps_modules, ".psm1"), # PS module contains '#AnsibleRequires -CSharpUtil Ansible.*' (self._re_cs_in_ps_module, cs_utils, ".cs"), ] else: checks = [ # CS module contains 'using Ansible.*;' (self._re_cs_module, cs_utils, ".cs"), ] for line in lines: for check in checks: match = check[0].match(line) if match: # tolerate windows line endings by stripping any remaining # newline chars module_util_name = to_text(match.group(1).rstrip()) if module_util_name not in check[1].keys(): module_utils.add((module_util_name, check[2])) if powershell: ps_version_match = self._re_ps_version.match(line) if ps_version_match: self._parse_version_match(ps_version_match, "ps_version") os_version_match = self._re_os_version.match(line) if os_version_match: self._parse_version_match(os_version_match, "os_version") # once become is set, no need to keep on checking recursively if not self.become: become_match = self._re_become.match(line) if become_match: self.become = True if wrapper: wrapper_match = self._re_wrapper.match(line) if wrapper_match: self.scan_exec_script(wrapper_match.group(1).rstrip()) # recursively drill into each Requires to see if there are any more # requirements for m in set(module_utils): self._add_module(m, wrapper=wrapper) def scan_exec_script(self, name): # scans lib/ansible/executor/powershell for scripts used in the module # exec side. It also scans these scripts for any dependencies name = to_text(name) if name in self.exec_scripts.keys(): return data = pkgutil.get_data("ansible.executor.powershell", name + ".ps1") if data is None: raise AnsibleError("Could not find executor powershell script " "for '%s'" % name) b_data = to_bytes(data) # remove comments to reduce the payload size in the exec wrappers if C.DEFAULT_DEBUG: exec_script = b_data else: exec_script = _strip_comments(b_data) self.exec_scripts[name] = to_bytes(exec_script) self.scan_module(b_data, wrapper=True, powershell=True) def _add_module(self, name, wrapper=False): m, ext = name m = to_text(m) mu_path = ps_module_utils_loader.find_plugin(m, ext) if not mu_path: raise AnsibleError('Could not find imported module support code ' 'for \'%s\'' % m) module_util_data = to_bytes(_slurp(mu_path)) if ext == ".psm1": self.ps_modules[m] = module_util_data else: if wrapper: self.cs_utils_wrapper[m] = module_util_data else: self.cs_utils_module[m] = module_util_data self.scan_module(module_util_data, wrapper=wrapper, powershell=(ext == ".psm1")) def _parse_version_match(self, match, attribute): new_version = to_text(match.group(1)).rstrip() # PowerShell cannot cast a string of "1" to Version, it must have at # least the major.minor for it to be valid so we append 0 if match.group(2) is None: new_version = "%s.0" % new_version existing_version = getattr(self, attribute, None) if existing_version is None: setattr(self, attribute, new_version) else: # determine which is the latest version and set that if LooseVersion(new_version) > LooseVersion(existing_version): setattr(self, attribute, new_version) def _slurp(path): if not os.path.exists(path): raise AnsibleError("imported module support code does not exist at %s" % os.path.abspath(path)) fd = open(path, 'rb') data = fd.read() fd.close() return data def _strip_comments(source): # Strip comments and blank lines from the wrapper buf = [] start_block = False for line in source.splitlines(): l = line.strip() if start_block and l.endswith(b'#>'): start_block = False continue elif start_block: continue elif l.startswith(b'<#'): start_block = True continue elif not l or l.startswith(b'#'): continue buf.append(line) return b'\n'.join(buf) def _create_powershell_wrapper(b_module_data, module_args, environment, async_timeout, become, become_method, become_user, become_password, become_flags, substyle): # creates the manifest/wrapper used in PowerShell/C# modules to enable # things like become and async - this is also called in action/script.py # FUTURE: add process_wrapper.ps1 to run module_wrapper in a new process # if running under a persistent connection and substyle is C# so we # don't have type conflicts finder = PSModuleDepFinder() if substyle != 'script': # don't scan the module for util dependencies and other Ansible related # flags if the substyle is 'script' which is set by action/script finder.scan_module(b_module_data, powershell=(substyle == "powershell")) module_wrapper = "module_%s_wrapper" % substyle exec_manifest = dict( module_entry=to_text(base64.b64encode(b_module_data)), powershell_modules=dict(), csharp_utils=dict(), csharp_utils_module=list(), # csharp_utils only required by a module module_args=module_args, actions=[module_wrapper], environment=environment, encoded_output=False ) finder.scan_exec_script(module_wrapper) if async_timeout > 0: finder.scan_exec_script('exec_wrapper') finder.scan_exec_script('async_watchdog') finder.scan_exec_script('async_wrapper') exec_manifest["actions"].insert(0, 'async_watchdog') exec_manifest["actions"].insert(0, 'async_wrapper') exec_manifest["async_jid"] = str(random.randint(0, 999999999999)) exec_manifest["async_timeout_sec"] = async_timeout if become and become_method == 'runas': finder.scan_exec_script('exec_wrapper') finder.scan_exec_script('become_wrapper') exec_manifest["actions"].insert(0, 'become_wrapper') exec_manifest["become_user"] = become_user exec_manifest["become_password"] = become_password exec_manifest['become_flags'] = become_flags exec_manifest['min_ps_version'] = finder.ps_version exec_manifest['min_os_version'] = finder.os_version if finder.become and 'become_wrapper' not in exec_manifest['actions']: finder.scan_exec_script('exec_wrapper') finder.scan_exec_script('become_wrapper') exec_manifest['actions'].insert(0, 'become_wrapper') exec_manifest['become_user'] = 'SYSTEM' exec_manifest['become_password'] = None exec_manifest['become_flags'] = None # make sure Ansible.ModuleUtils.AddType is added if any C# utils are used if len(finder.cs_utils_wrapper) > 0 or len(finder.cs_utils_module) > 0: finder._add_module((b"Ansible.ModuleUtils.AddType", ".psm1"), wrapper=False) # exec_wrapper is only required to be part of the payload if using # become or async, to save on payload space we check if exec_wrapper has # already been added, and remove it manually if it hasn't later exec_required = "exec_wrapper" in finder.exec_scripts.keys() finder.scan_exec_script("exec_wrapper") # must contain an empty newline so it runs the begin/process/end block finder.exec_scripts["exec_wrapper"] += b"\n\n" exec_wrapper = finder.exec_scripts["exec_wrapper"] if not exec_required: finder.exec_scripts.pop("exec_wrapper") for name, data in finder.exec_scripts.items(): b64_data = to_text(base64.b64encode(data)) exec_manifest[name] = b64_data for name, data in finder.ps_modules.items(): b64_data = to_text(base64.b64encode(data)) exec_manifest['powershell_modules'][name] = b64_data cs_utils = finder.cs_utils_wrapper cs_utils.update(finder.cs_utils_module) for name, data in cs_utils.items(): b64_data = to_text(base64.b64encode(data)) exec_manifest['csharp_utils'][name] = b64_data exec_manifest['csharp_utils_module'] = list(finder.cs_utils_module.keys()) # FUTURE: smuggle this back as a dict instead of serializing here; # the connection plugin may need to modify it b_json = to_bytes(json.dumps(exec_manifest)) b_data = exec_wrapper.replace(b"$json_raw = ''", b"$json_raw = @'\r\n%s\r\n'@" % b_json) return b_data
gpl-3.0
croepha/django-filer
filer/views.py
1
5797
#-*- coding: utf-8 -*- from django import forms from django.contrib.admin import widgets from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from django.utils.translation import ugettext_lazy as _ from models import Folder, Image, Clipboard, tools, FolderRoot class NewFolderForm(forms.ModelForm): class Meta: model = Folder fields = ('name',) widgets = { 'name': widgets.AdminTextInputWidget, } def popup_status(request): return '_popup' in request.REQUEST or 'pop' in request.REQUEST def selectfolder_status(request): return 'select_folder' in request.REQUEST def popup_param(request): if popup_status(request): return "?_popup=1" else: return "" def _userperms(item, request): r = [] ps = ['read', 'edit', 'add_children'] for p in ps: attr = "has_%s_permission" % p if hasattr(item, attr): x = getattr(item, attr)(request) if x: r.append(p) return r @login_required def edit_folder(request, folder_id): # TODO: implement edit_folder view folder = None return render_to_response('admin/filer/folder/folder_edit.html', { 'folder': folder, 'is_popup': '_popup' in request.REQUEST or \ 'pop' in request.REQUEST, }, context_instance=RequestContext(request)) @login_required def edit_image(request, folder_id): # TODO: implement edit_image view folder = None return render_to_response('filer/image_edit.html', { 'folder': folder, 'is_popup': '_popup' in request.REQUEST or \ 'pop' in request.REQUEST, }, context_instance=RequestContext(request)) @login_required def make_folder(request, folder_id=None): if not folder_id: folder_id = request.REQUEST.get('parent_id', None) if folder_id: folder = Folder.objects.get(id=folder_id) else: folder = None if request.user.is_superuser: pass elif folder == None: # regular users may not add root folders raise PermissionDenied elif not folder.has_add_children_permission(request): # the user does not have the permission to add subfolders raise PermissionDenied if request.method == 'POST': new_folder_form = NewFolderForm(request.POST) if new_folder_form.is_valid(): new_folder = new_folder_form.save(commit=False) if (folder or FolderRoot()).contains_folder(new_folder.name): new_folder_form._errors['name'] = new_folder_form.error_class([_('Folder with this name already exists.')]) else: new_folder.parent = folder new_folder.owner = request.user new_folder.save() return HttpResponse('<script type="text/javascript">' + \ 'opener.dismissPopupAndReload(window);' + \ '</script>') else: new_folder_form = NewFolderForm() return render_to_response('admin/filer/folder/new_folder_form.html', { 'new_folder_form': new_folder_form, 'is_popup': '_popup' in request.REQUEST or \ 'pop' in request.REQUEST, }, context_instance=RequestContext(request)) class UploadFileForm(forms.ModelForm): class Meta: model = Image @login_required def upload(request): return render_to_response('filer/upload.html', { 'title': u'Upload files', 'is_popup': popup_status(request), }, context_instance=RequestContext(request)) @login_required def paste_clipboard_to_folder(request): if request.method == 'POST': folder = Folder.objects.get(id=request.POST.get('folder_id')) clipboard = Clipboard.objects.get(id=request.POST.get('clipboard_id')) if folder.has_add_children_permission(request): tools.move_files_from_clipboard_to_folder(clipboard, folder) tools.discard_clipboard(clipboard) else: raise PermissionDenied return HttpResponseRedirect('%s%s' % ( request.REQUEST.get('redirect_to', ''), popup_param(request))) @login_required def discard_clipboard(request): if request.method == 'POST': clipboard = Clipboard.objects.get(id=request.POST.get('clipboard_id')) tools.discard_clipboard(clipboard) return HttpResponseRedirect('%s%s' % ( request.POST.get('redirect_to', ''), popup_param(request))) @login_required def delete_clipboard(request): if request.method == 'POST': clipboard = Clipboard.objects.get(id=request.POST.get('clipboard_id')) tools.delete_clipboard(clipboard) return HttpResponseRedirect('%s%s' % ( request.POST.get('redirect_to', ''), popup_param(request))) @login_required def clone_files_from_clipboard_to_folder(request): if request.method == 'POST': clipboard = Clipboard.objects.get(id=request.POST.get('clipboard_id')) folder = Folder.objects.get(id=request.POST.get('folder_id')) tools.clone_files_from_clipboard_to_folder(clipboard, folder) return HttpResponseRedirect('%s%s' % ( request.POST.get('redirect_to', ''), popup_param(request)))
mit
wenxer/peewee
setup.py
7
1084
import os from setuptools import find_packages from setuptools import setup f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() try: from Cython.Build import cythonize except ImportError: ext_modules = None else: ext_modules = cythonize('playhouse/speedups.pyx') setup( name='peewee', version=__import__('peewee').__version__, description='a little orm', long_description=readme, author='Charles Leifer', author_email='coleifer@gmail.com', url='http://github.com/coleifer/peewee/', package_data = { 'playhouse': ['berkeley_build.sh']}, packages=['playhouse'], py_modules=['peewee', 'pwiz'], ext_modules=ext_modules, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], test_suite='tests', scripts = ['pwiz.py'], )
mit
0x46616c6b/ansible
lib/ansible/plugins/action/junos_config.py
43
4165
# # (c) 2017, 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/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import re import time import glob from ansible.plugins.action.junos import ActionModule as _ActionModule from ansible.module_utils._text import to_text from ansible.module_utils.six.moves.urllib.parse import urlsplit from ansible.utils.vars import merge_hash PRIVATE_KEYS_RE = re.compile('__.+__') class ActionModule(_ActionModule): def run(self, tmp=None, task_vars=None): if self._task.args.get('src'): try: self._handle_template() except ValueError as exc: return dict(failed=True, msg=exc.message) result = super(ActionModule, self).run(tmp, task_vars) if self._task.args.get('backup') and result.get('__backup__'): # User requested backup and no error occurred in module. # NOTE: If there is a parameter error, _backup key may not be in results. filepath = self._write_backup(task_vars['inventory_hostname'], result['__backup__']) result['backup_path'] = filepath # strip out any keys that have two leading and two trailing # underscore characters for key in result.keys(): if PRIVATE_KEYS_RE.match(key): del result[key] return result def _get_working_path(self): cwd = self._loader.get_basedir() if self._task._role is not None: cwd = self._task._role._role_path return cwd def _write_backup(self, host, contents): backup_path = self._get_working_path() + '/backup' if not os.path.exists(backup_path): os.mkdir(backup_path) for fn in glob.glob('%s/%s*' % (backup_path, host)): os.remove(fn) tstamp = time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime(time.time())) filename = '%s/%s_config.%s' % (backup_path, host, tstamp) open(filename, 'w').write(contents) return filename def _handle_template(self): src = self._task.args.get('src') working_path = self._get_working_path() if os.path.isabs(src) or urlsplit('src').scheme: source = src else: source = self._loader.path_dwim_relative(working_path, 'templates', src) if not source: source = self._loader.path_dwim_relative(working_path, src) if not os.path.exists(source): raise ValueError('path specified in src not found') try: with open(source, 'r') as f: template_data = to_text(f.read()) except IOError: return dict(failed=True, msg='unable to load src file') # Create a template search path in the following order: # [working_path, self_role_path, dependent_role_paths, dirname(source)] searchpath = [working_path] if self._task._role is not None: searchpath.append(self._task._role._role_path) if hasattr(self._task, "_block:"): dep_chain = self._task._block.get_dep_chain() if dep_chain is not None: for role in dep_chain: searchpath.append(role._role_path) searchpath.append(os.path.dirname(source)) self._templar.environment.loader.searchpath = searchpath self._task.args['src'] = self._templar.template(template_data)
gpl-3.0
pi-bot/.v2
python-code/servo.py
3
1929
import os import time #SERVOD_PATH='/home/pi/ServoBlaster1/user/servod' #SERVOD_PATH='/usr/local/sbin/servod' SERVOD_PATH='/usr/sbin/pi-blaster' SERVO_ANGLE = 0 SERVO_CONTINUOUS = 1 class Servo(object): """A Servo instance controls a single servo Parameters ---------- pin : int GPIO pin number the servo is connected to type : int The kind of servo that you use, SERVO_ANGLE or SERVO_COMTINUOUS servod_path : str Path to the "servod" executable """ def __init__(self, pin=0, type=SERVO_ANGLE, servod_path=SERVOD_PATH): self.pin = pin self.servod_path = servod_path if type == SERVO_ANGLE: self.range = (0.08,0.3) else: self.range = (0.131,0.161) if not self._servoblaster_started(): self.start() def set(self, pulse_width): """ Parameters ---------- pulse_width : int pulse width to send to the servo measured in 10s of us """ os.system('echo "{}={}" > /dev/pi-blaster'.format(self.pin, pulse_width)) # 0 = Backwards, 0.5 = Stopped, 1 = Forwards def set_normalized(self, val): min, max = self.range scale = max - min speed = min + scale * val self.set(str(speed)) def start(self): os.system('sudo {}'.format(self.servod_path)) def stop(self): servod_name = os.path.split(self.servod_path)[1] os.system('sudo killall {}'.format(servod_name)) def _servoblaster_started(self): servod_name = os.path.split(self.servod_path)[1] return servod_name in os.popen('ps -u root').read() #servo_left = Servo(pins.SERVO_LEFT_MOTOR) #servo_right = Servo(pins.SERVO_RIGHT_MOTOR) #servo_left.set_normalized(1) #servo_right.set_normalized(1) #time.sleep(1) #servo_left.set_normalized(0.5) #servo_right.set_normalized(0.5) #servo_left.stop()
gpl-3.0
jonnatas/codeschool
old/cs_courses/admin.py
2
1473
from django.contrib import admin from cs_courses import models @admin.register(models.Course) class CourseAdmin(admin.ModelAdmin): # Inline models class TimeSlotInline(admin.TabularInline): model = models.TimeSlot extra = 0 classes = ('collapse',) class LessonInline(admin.TabularInline): model = models.Lesson extra = 2 fields = ['title'] classes = ('collapse',) inlines = [TimeSlotInline, LessonInline] # Common options date_hierarchy = 'created' filter_horizontal = ('students',) list_filter = ('is_active', 'start') list_display = ( 'name', '_teacher_name', '_number_of_students', 'start', ) fieldsets = ( (None, { 'fields': ('discipline', 'teacher'), }), ('Alunos', { 'classes': ('collapse',), 'fields': ('students',), }), ('Ativação', { 'classes': ('collapse',), 'fields': ('is_active', 'start', 'end'), }), ) save_as = True search_fields = ( 'discipline__name', 'teacher__first_name', 'teacher__last_name' ) @staticmethod def _teacher_name(obj): teacher = obj.teacher return '%s %s' % (teacher.first_name, teacher.last_name) @staticmethod def _number_of_students(obj): return obj.students.count() admin.site.register(models.Discipline)
gpl-3.0
maxhome1/l10n-italy
l10n_it_ipa/__openerp__.py
3
1430
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 KTec S.r.l. # (<http://www.ktec.it>). # # Copyright (C) 2014 Associazione Odoo Italia # (<http://www.odoo-italia.org>). # # 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": "IPA Code (IndicePA)", "version": "8.0.1.0.0", "category": "Localisation/Italy", "author": "KTec S.r.l, Odoo Community Association (OCA)", "website": "http://www.ktec.it", "license": "AGPL-3", "depends": ['base'], "data": [ 'view/partner_view.xml', ], "qweb": [], "demo": [], "test": [], "active": False, 'installable': False }
agpl-3.0
avneesh91/django
tests/model_regress/models.py
25
2046
from django.db import models CHOICES = ( (1, 'first'), (2, 'second'), ) class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() status = models.IntegerField(blank=True, null=True, choices=CHOICES) misc_data = models.CharField(max_length=100, blank=True) article_text = models.TextField() class Meta: ordering = ('pub_date', 'headline') # A utf-8 verbose name (Ångström's Articles) to test they are valid. verbose_name = "\xc3\x85ngstr\xc3\xb6m's Articles" def __str__(self): return self.headline class Movie(models.Model): # Test models with non-default primary keys / AutoFields #5218 movie_id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) class Party(models.Model): when = models.DateField(null=True) class Event(models.Model): when = models.DateTimeField() class Department(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Worker(models.Model): department = models.ForeignKey(Department, models.CASCADE) name = models.CharField(max_length=200) def __str__(self): return self.name class BrokenStrMethod(models.Model): name = models.CharField(max_length=7) def __str__(self): # Intentionally broken (invalid start byte in byte string). return b'Name\xff: %s'.decode() % self.name class NonAutoPK(models.Model): name = models.CharField(max_length=10, primary_key=True) # Chained foreign keys with to_field produce incorrect query #18432 class Model1(models.Model): pkey = models.IntegerField(unique=True, db_index=True) class Model2(models.Model): model1 = models.ForeignKey(Model1, models.CASCADE, unique=True, to_field='pkey') class Model3(models.Model): model2 = models.ForeignKey(Model2, models.CASCADE, unique=True, to_field='model1')
bsd-3-clause
playfulgod/android_kernel_lge_cayman
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/SchedGui.py
12980
5411
# SchedGui.py - Python extension for perf script, basic GUI code for # traces drawing and overview. # # Copyright (C) 2010 by Frederic Weisbecker <fweisbec@gmail.com> # # This software is distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. try: import wx except ImportError: raise ImportError, "You need to install the wxpython lib for this script" class RootFrame(wx.Frame): Y_OFFSET = 100 RECT_HEIGHT = 100 RECT_SPACE = 50 EVENT_MARKING_WIDTH = 5 def __init__(self, sched_tracer, title, parent = None, id = -1): wx.Frame.__init__(self, parent, id, title) (self.screen_width, self.screen_height) = wx.GetDisplaySize() self.screen_width -= 10 self.screen_height -= 10 self.zoom = 0.5 self.scroll_scale = 20 self.sched_tracer = sched_tracer self.sched_tracer.set_root_win(self) (self.ts_start, self.ts_end) = sched_tracer.interval() self.update_width_virtual() self.nr_rects = sched_tracer.nr_rectangles() + 1 self.height_virtual = RootFrame.Y_OFFSET + (self.nr_rects * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) # whole window panel self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height)) # scrollable container self.scroll = wx.ScrolledWindow(self.panel) self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale) self.scroll.EnableScrolling(True, True) self.scroll.SetFocus() # scrollable drawing area self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width - 15, self.screen_height / 2)) self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint) self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Bind(wx.EVT_PAINT, self.on_paint) self.scroll.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Fit() self.Fit() self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, self.height_virtual, wx.SIZE_USE_EXISTING) self.txt = None self.Show(True) def us_to_px(self, val): return val / (10 ** 3) * self.zoom def px_to_us(self, val): return (val / self.zoom) * (10 ** 3) def scroll_start(self): (x, y) = self.scroll.GetViewStart() return (x * self.scroll_scale, y * self.scroll_scale) def scroll_start_us(self): (x, y) = self.scroll_start() return self.px_to_us(x) def paint_rectangle_zone(self, nr, color, top_color, start, end): offset_px = self.us_to_px(start - self.ts_start) width_px = self.us_to_px(end - self.ts_start) offset_py = RootFrame.Y_OFFSET + (nr * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) width_py = RootFrame.RECT_HEIGHT dc = self.dc if top_color is not None: (r, g, b) = top_color top_color = wx.Colour(r, g, b) brush = wx.Brush(top_color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, RootFrame.EVENT_MARKING_WIDTH) width_py -= RootFrame.EVENT_MARKING_WIDTH offset_py += RootFrame.EVENT_MARKING_WIDTH (r ,g, b) = color color = wx.Colour(r, g, b) brush = wx.Brush(color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, width_py) def update_rectangles(self, dc, start, end): start += self.ts_start end += self.ts_start self.sched_tracer.fill_zone(start, end) def on_paint(self, event): dc = wx.PaintDC(self.scroll_panel) self.dc = dc width = min(self.width_virtual, self.screen_width) (x, y) = self.scroll_start() start = self.px_to_us(x) end = self.px_to_us(x + width) self.update_rectangles(dc, start, end) def rect_from_ypixel(self, y): y -= RootFrame.Y_OFFSET rect = y / (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) height = y % (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) if rect < 0 or rect > self.nr_rects - 1 or height > RootFrame.RECT_HEIGHT: return -1 return rect def update_summary(self, txt): if self.txt: self.txt.Destroy() self.txt = wx.StaticText(self.panel, -1, txt, (0, (self.screen_height / 2) + 50)) def on_mouse_down(self, event): (x, y) = event.GetPositionTuple() rect = self.rect_from_ypixel(y) if rect == -1: return t = self.px_to_us(x) + self.ts_start self.sched_tracer.mouse_down(rect, t) def update_width_virtual(self): self.width_virtual = self.us_to_px(self.ts_end - self.ts_start) def __zoom(self, x): self.update_width_virtual() (xpos, ypos) = self.scroll.GetViewStart() xpos = self.us_to_px(x) / self.scroll_scale self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale, xpos, ypos) self.Refresh() def zoom_in(self): x = self.scroll_start_us() self.zoom *= 2 self.__zoom(x) def zoom_out(self): x = self.scroll_start_us() self.zoom /= 2 self.__zoom(x) def on_key_press(self, event): key = event.GetRawKeyCode() if key == ord("+"): self.zoom_in() return if key == ord("-"): self.zoom_out() return key = event.GetKeyCode() (x, y) = self.scroll.GetViewStart() if key == wx.WXK_RIGHT: self.scroll.Scroll(x + 1, y) elif key == wx.WXK_LEFT: self.scroll.Scroll(x - 1, y) elif key == wx.WXK_DOWN: self.scroll.Scroll(x, y + 1) elif key == wx.WXK_UP: self.scroll.Scroll(x, y - 1)
gpl-2.0
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py
13
7653
# 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. # ============================================================================== """Decorator that provides a warning if the wrapped object is never used.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import itertools import traceback import types import six # pylint: disable=unused-import from backports import weakref # pylint: disable=g-bad-import-order from tensorflow.python.platform import tf_logging from tensorflow.python.util import tf_decorator class _RefInfoField( collections.namedtuple( '_RefInfoField', ('type_', 'repr_', 'creation_stack', 'object_used'))): pass # Thread-safe up to int32max/2 thanks to python's GIL; and may be safe even for # higher values in Python 3.4+. We don't expect to ever count higher than this. # https://mail.python.org/pipermail/python-list/2005-April/342279.html _REF_ITER = itertools.count() # Dictionary mapping id(obj) => _RefInfoField. _REF_INFO = {} def _deleted(obj_id, fatal_error): obj = _REF_INFO[obj_id] del _REF_INFO[obj_id] if not obj.object_used: if fatal_error: logger = tf_logging.fatal else: logger = tf_logging.error logger( '==================================\n' 'Object was never used (type %s):\n%s\nIf you want to mark it as ' 'used call its "mark_used()" method.\nIt was originally created ' 'here:\n%s\n' '==================================' % (obj.type_, obj.repr_, obj.creation_stack)) def _add_should_use_warning(x, fatal_error=False): """Wraps object x so that if it is never used, a warning is logged. Args: x: Python object. fatal_error: Python bool. If `True`, tf.logging.fatal is raised if the returned value is never used. Returns: An instance of `TFShouldUseWarningWrapper` which subclasses `type(x)` and is a very shallow wrapper for `x` which logs access into `x`. """ if x is None: # special corner case where x is None return x if hasattr(x, '_tf_ref_id'): # this is already a TFShouldUseWarningWrapper return x def override_method(method): def fn(self, *args, **kwargs): # pylint: disable=protected-access _REF_INFO[self._tf_ref_id] = _REF_INFO[self._tf_ref_id]._replace( object_used=True) return method(self, *args, **kwargs) return fn class TFShouldUseWarningWrapper(type(x)): """Wrapper for objects that keeps track of their use.""" def __init__(self, true_self): self.__dict__ = true_self.__dict__ stack = [s.strip() for s in traceback.format_stack()] # Remove top three stack entries from adding the wrapper self.creation_stack = '\n'.join(stack[:-3]) self._tf_ref_id = next(_REF_ITER) _REF_INFO[self._tf_ref_id] = _RefInfoField( type_=type(x), repr_=repr(x), creation_stack=stack, object_used=False) # Create a finalizer for self, which will be called when self is # garbage collected. Can't add self as the args because the # loop will break garbage collection. We keep track of # ourselves via python ids. weakref.finalize(self, _deleted, self._tf_ref_id, fatal_error) # Not sure why this pylint warning is being used; this is not an # old class form. # pylint: disable=super-on-old-class def __getattribute__(self, name): if name == '_tf_ref_id': return super(TFShouldUseWarningWrapper, self).__getattribute__(name) if self._tf_ref_id in _REF_INFO: _REF_INFO[self._tf_ref_id] = _REF_INFO[self._tf_ref_id]._replace( object_used=True) return super(TFShouldUseWarningWrapper, self).__getattribute__(name) def mark_used(self, *args, **kwargs): _REF_INFO[self._tf_ref_id] = _REF_INFO[self._tf_ref_id]._replace( object_used=True) if hasattr(super(TFShouldUseWarningWrapper, self), 'mark_used'): return super(TFShouldUseWarningWrapper, self).mark_used(*args, **kwargs) # pylint: enable=super-on-old-class for name in dir(TFShouldUseWarningWrapper): method = getattr(TFShouldUseWarningWrapper, name) if not isinstance(method, types.FunctionType): continue if name in ('__init__', '__getattribute__', '__del__', 'mark_used'): continue setattr(TFShouldUseWarningWrapper, name, functools.wraps(method)(override_method(method))) wrapped = TFShouldUseWarningWrapper(x) wrapped.__doc__ = x.__doc__ # functools.wraps fails on some objects. ref_id = wrapped._tf_ref_id # pylint: disable=protected-access _REF_INFO[ref_id] = _REF_INFO[ref_id]._replace(object_used=False) return wrapped def should_use_result(fn): """Function wrapper that ensures the function's output is used. If the output is not used, a `tf.logging.error` is logged. An output is marked as used if any of its attributes are read, modified, or updated. Examples when the output is a `Tensor` include: - Using it in any capacity (e.g. `y = t + 0`, `sess.run(t)`) - Accessing a property (e.g. getting `t.name` or `t.op`). Note, certain behaviors cannot be tracked - for these the object may not be marked as used. Examples include: - `t != 0`. In this case, comparison is done on types / ids. - `isinstance(t, tf.Tensor)`. Similar to above. Args: fn: The function to wrap. Returns: The wrapped function. """ def wrapped(*args, **kwargs): return _add_should_use_warning(fn(*args, **kwargs)) return tf_decorator.make_decorator( fn, wrapped, 'should_use_result', ((fn.__doc__ or '') + ('\n\n ' '**NOTE** The output of this function should be used. If it is not, ' 'a warning will be logged. To mark the output as used, ' 'call its .mark_used() method.'))) def must_use_result_or_fatal(fn): """Function wrapper that ensures the function's output is used. If the output is not used, a `tf.logging.fatal` error is raised. An output is marked as used if any of its attributes are read, modified, or updated. Examples when the output is a `Tensor` include: - Using it in any capacity (e.g. `y = t + 0`, `sess.run(t)`) - Accessing a property (e.g. getting `t.name` or `t.op`). Note, certain behaviors cannot be tracked - for these the object may not be marked as used. Examples include: - `t != 0`. In this case, comparison is done on types / ids. - `isinstance(t, tf.Tensor)`. Similar to above. Args: fn: The function to wrap. Returns: The wrapped function. """ def wrapped(*args, **kwargs): return _add_should_use_warning(fn(*args, **kwargs), fatal_error=True) return tf_decorator.make_decorator( fn, wrapped, 'must_use_result_or_fatal', ((fn.__doc__ or '') + ('\n\n ' '**NOTE** The output of this function must be used. If it is not, ' 'a fatal error will be raised. To mark the output as used, ' 'call its .mark_used() method.')))
bsd-2-clause
conanxin/Arduino-Meets-Blender-OSC
pyOSC_examples/basic_send.py
1
2522
""" sending OSC with pyOSC https://trac.v2.nl/wiki/pyOSC example by www.ixi-audio.net based on pyOSC documentation """ import OSC import time, random """ note that if there is nobody listening in the other end we get an error like this OSC.OSCClientError: while sending: [Errno 111] Connection refused so we need to have an app listening in the receiving port for this to work properly this is a very basic example, for detailed info on pyOSC functionality check the OSC.py file or run pydoc pyOSC.py. you can also get the docs by opening a python shell and doing >>> import OSC >>> help(OSC) """ ## the most basic ## client = OSC.OSCClient() msg = OSC.OSCMessage() msg.setAddress("/print") msg.append(1234) client.sendto(msg, ('127.0.0.1', 2014)) # note that the second arg is a tupple and not two arguments ## better practice ## client = OSC.OSCClient() client.connect( ('127.0.0.1', 2014) ) # note that the argument is a tupple and not two arguments msg = OSC.OSCMessage() # we reuse the same variable msg used above overwriting it msg.setAddress("/arduino/analog") msg.append(4321) client.send(msg) # now we dont need to tell the client the address anymore ## in mode detail ## # tupple with ip, port. i dont use the () but maybe you want -> send_address = ('127.0.0.1', 9000) send_address = '127.0.0.1', 9000 # OSC basic client c = OSC.OSCClient() c.connect( send_address ) # set the address for all following messages # single message msg = OSC.OSCMessage() msg.setAddress("/print") # set OSC address msg.append(44) # int msg.append(4.5233) # float msg.append( "the white cliffs of dover" ) # string c.send(msg) # send it! # bundle : few messages sent together # use them to send many different messages on every loop for instance in a game. saves CPU and it is faster bundle = OSC.OSCBundle() bundle.append(msg) # append prev mgs bundle.append( {'addr':"/print", 'args':["bundled messages:", 2]} ) # and some more stuff ... bundle.setAddress("/*print") bundle.append( ("no,", 3, "actually.") ) c.send(bundle) # send it! # lets try sending a different random number every frame in a loop try : seed = random.Random() # need to seed first while 1: # endless loop rNum= OSC.OSCMessage() rNum.setAddress("/print") n = seed.randint(1, 1000) # get a random num every loop rNum.append(n) c.send(rNum) time.sleep(5) # wait here some secs except KeyboardInterrupt: print "Closing OSCClient" c.close() print "Done"
lgpl-3.0
hzhuang1/linux
scripts/tracing/draw_functrace.py
14676
3560
#!/usr/bin/python """ Copyright 2008 (c) Frederic Weisbecker <fweisbec@gmail.com> Licensed under the terms of the GNU GPL License version 2 This script parses a trace provided by the function tracer in kernel/trace/trace_functions.c The resulted trace is processed into a tree to produce a more human view of the call stack by drawing textual but hierarchical tree of calls. Only the functions's names and the the call time are provided. Usage: Be sure that you have CONFIG_FUNCTION_TRACER # mount -t debugfs nodev /sys/kernel/debug # echo function > /sys/kernel/debug/tracing/current_tracer $ cat /sys/kernel/debug/tracing/trace_pipe > ~/raw_trace_func Wait some times but not too much, the script is a bit slow. Break the pipe (Ctrl + Z) $ scripts/draw_functrace.py < raw_trace_func > draw_functrace Then you have your drawn trace in draw_functrace """ import sys, re class CallTree: """ This class provides a tree representation of the functions call stack. If a function has no parent in the kernel (interrupt, syscall, kernel thread...) then it is attached to a virtual parent called ROOT. """ ROOT = None def __init__(self, func, time = None, parent = None): self._func = func self._time = time if parent is None: self._parent = CallTree.ROOT else: self._parent = parent self._children = [] def calls(self, func, calltime): """ If a function calls another one, call this method to insert it into the tree at the appropriate place. @return: A reference to the newly created child node. """ child = CallTree(func, calltime, self) self._children.append(child) return child def getParent(self, func): """ Retrieve the last parent of the current node that has the name given by func. If this function is not on a parent, then create it as new child of root @return: A reference to the parent. """ tree = self while tree != CallTree.ROOT and tree._func != func: tree = tree._parent if tree == CallTree.ROOT: child = CallTree.ROOT.calls(func, None) return child return tree def __repr__(self): return self.__toString("", True) def __toString(self, branch, lastChild): if self._time is not None: s = "%s----%s (%s)\n" % (branch, self._func, self._time) else: s = "%s----%s\n" % (branch, self._func) i = 0 if lastChild: branch = branch[:-1] + " " while i < len(self._children): if i != len(self._children) - 1: s += "%s" % self._children[i].__toString(branch +\ " |", False) else: s += "%s" % self._children[i].__toString(branch +\ " |", True) i += 1 return s class BrokenLineException(Exception): """If the last line is not complete because of the pipe breakage, we want to stop the processing and ignore this line. """ pass class CommentLineException(Exception): """ If the line is a comment (as in the beginning of the trace file), just ignore it. """ pass def parseLine(line): line = line.strip() if line.startswith("#"): raise CommentLineException m = re.match("[^]]+?\\] +([0-9.]+): (\\w+) <-(\\w+)", line) if m is None: raise BrokenLineException return (m.group(1), m.group(2), m.group(3)) def main(): CallTree.ROOT = CallTree("Root (Nowhere)", None, None) tree = CallTree.ROOT for line in sys.stdin: try: calltime, callee, caller = parseLine(line) except BrokenLineException: break except CommentLineException: continue tree = tree.getParent(caller) tree = tree.calls(callee, calltime) print CallTree.ROOT if __name__ == "__main__": main()
gpl-2.0
topojoy/deepdive
examples/spouse_example/postgres/incremental/udf/ext_has_spouse_features.f1.py
15
2715
#! /usr/bin/env python import sys import ddlib # DeepDive python utility ARR_DELIM = '~^~' # For each input tuple for row in sys.stdin: parts = row.strip().split('\t') if len(parts) != 6: print >>sys.stderr, 'Failed to parse row:', row continue # Get all fields from a row words = parts[0].split(ARR_DELIM) relation_id = parts[1] p1_start, p1_length, p2_start, p2_length = [int(x) for x in parts[2:]] # Unpack input into tuples. span1 = ddlib.Span(begin_word_id=p1_start, length=p1_length) span2 = ddlib.Span(begin_word_id=p2_start, length=p2_length) # Features for this pair come in here features = set() # Feature 1: Bag of words between the two phrases words_between = ddlib.tokens_between_spans(words, span1, span2) for word in words_between.elements: features.add("word_between=" + word) # Feature 2: Number of words between the two phrases # features.add("num_words_between=%s" % len(words_between.elements)) # Feature 3: Does the last word (last name) match? # last_word_left = ddlib.materialize_span(words, span1)[-1] # last_word_right = ddlib.materialize_span(words, span2)[-1] # if (last_word_left == last_word_right): # features.add("potential_last_name_match") ######################## # Improved Feature Set # ######################## # # Feature 1: Find out if a lemma of marry occurs. # # A better feature would ensure this is on the dependency path between the two. # words_between = ddlib.tokens_between_spans(words, span1, span2) # lemma_between = ddlib.tokens_between_spans(obj["lemma"], span1, span2) # married_words = ['marry', 'widow', 'wife', 'fiancee', 'spouse'] # non_married_words = ['father', 'mother', 'brother', 'sister', 'son'] # # Make sure the distance between mention pairs is not too long # if len(words_between.elements) <= 10: # for mw in married_words + non_married_words: # if mw in lemma_between.elements: # features.add("important_word=%s" % mw) # # Feature 2: Number of words between the two phrases # # Intuition: if they are close by, the link may be stronger. # l = len(words_between.elements) # if l < 5: features.add("few_words_between") # else: features.add("many_words_between") # # Feature 3: Does the last word (last name) match? # last_word_left = ddlib.materialize_span(words, span1)[-1] # last_word_right = ddlib.materialize_span(words, span2)[-1] # if (last_word_left == last_word_right): # features.add("potential_last_name_match") ####################### # # Use this line if you want to print out all features extracted: # ddlib.log(features) for feature in features: print str(relation_id) + '\t' + feature
apache-2.0
vipulroxx/kivy
examples/canvas/fbo_canvas.py
59
2544
''' FBO Canvas ========== This demonstrates a layout using an FBO (Frame Buffer Off-screen) instead of a plain canvas. You should see a black canvas with a button labelled 'FBO' in the bottom left corner. Clicking it animates the button moving right to left. ''' __all__ = ('FboFloatLayout', ) from kivy.graphics import Color, Rectangle, Canvas, ClearBuffers, ClearColor from kivy.graphics.fbo import Fbo from kivy.uix.floatlayout import FloatLayout from kivy.properties import ObjectProperty, NumericProperty from kivy.app import App from kivy.core.window import Window from kivy.animation import Animation from kivy.factory import Factory class FboFloatLayout(FloatLayout): texture = ObjectProperty(None, allownone=True) alpha = NumericProperty(1) def __init__(self, **kwargs): self.canvas = Canvas() with self.canvas: self.fbo = Fbo(size=self.size) self.fbo_color = Color(1, 1, 1, 1) self.fbo_rect = Rectangle() with self.fbo: ClearColor(0, 0, 0, 0) ClearBuffers() # wait that all the instructions are in the canvas to set texture self.texture = self.fbo.texture super(FboFloatLayout, self).__init__(**kwargs) def add_widget(self, *largs): # trick to attach graphics instruction to fbo instead of canvas canvas = self.canvas self.canvas = self.fbo ret = super(FboFloatLayout, self).add_widget(*largs) self.canvas = canvas return ret def remove_widget(self, *largs): canvas = self.canvas self.canvas = self.fbo super(FboFloatLayout, self).remove_widget(*largs) self.canvas = canvas def on_size(self, instance, value): self.fbo.size = value self.texture = self.fbo.texture self.fbo_rect.size = value def on_pos(self, instance, value): self.fbo_rect.pos = value def on_texture(self, instance, value): self.fbo_rect.texture = value def on_alpha(self, instance, value): self.fbo_color.rgba = (1, 1, 1, value) class ScreenLayerApp(App): def build(self): f = FboFloatLayout() b = Factory.Button(text="FBO", size_hint=(None, None)) f.add_widget(b) def anim_btn(*args): if b.pos[0] == 0: Animation(x=f.width - b.width).start(b) else: Animation(x=0).start(b) b.bind(on_press=anim_btn) return f if __name__ == "__main__": ScreenLayerApp().run()
mit
mjgrav2001/scikit-learn
examples/cluster/plot_feature_agglomeration_vs_univariate_selection.py
218
3893
""" ============================================== Feature agglomeration vs. univariate selection ============================================== This example compares 2 dimensionality reduction strategies: - univariate feature selection with Anova - feature agglomeration with Ward hierarchical clustering Both methods are compared in a regression problem using a BayesianRidge as supervised estimator. """ # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # License: BSD 3 clause print(__doc__) import shutil import tempfile import numpy as np import matplotlib.pyplot as plt from scipy import linalg, ndimage from sklearn.feature_extraction.image import grid_to_graph from sklearn import feature_selection from sklearn.cluster import FeatureAgglomeration from sklearn.linear_model import BayesianRidge from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.externals.joblib import Memory from sklearn.cross_validation import KFold ############################################################################### # Generate data n_samples = 200 size = 40 # image size roi_size = 15 snr = 5. np.random.seed(0) mask = np.ones([size, size], dtype=np.bool) coef = np.zeros((size, size)) coef[0:roi_size, 0:roi_size] = -1. coef[-roi_size:, -roi_size:] = 1. X = np.random.randn(n_samples, size ** 2) for x in X: # smooth data x[:] = ndimage.gaussian_filter(x.reshape(size, size), sigma=1.0).ravel() X -= X.mean(axis=0) X /= X.std(axis=0) y = np.dot(X, coef.ravel()) noise = np.random.randn(y.shape[0]) noise_coef = (linalg.norm(y, 2) / np.exp(snr / 20.)) / linalg.norm(noise, 2) y += noise_coef * noise # add noise ############################################################################### # Compute the coefs of a Bayesian Ridge with GridSearch cv = KFold(len(y), 2) # cross-validation generator for model selection ridge = BayesianRidge() cachedir = tempfile.mkdtemp() mem = Memory(cachedir=cachedir, verbose=1) # Ward agglomeration followed by BayesianRidge connectivity = grid_to_graph(n_x=size, n_y=size) ward = FeatureAgglomeration(n_clusters=10, connectivity=connectivity, memory=mem) clf = Pipeline([('ward', ward), ('ridge', ridge)]) # Select the optimal number of parcels with grid search clf = GridSearchCV(clf, {'ward__n_clusters': [10, 20, 30]}, n_jobs=1, cv=cv) clf.fit(X, y) # set the best parameters coef_ = clf.best_estimator_.steps[-1][1].coef_ coef_ = clf.best_estimator_.steps[0][1].inverse_transform(coef_) coef_agglomeration_ = coef_.reshape(size, size) # Anova univariate feature selection followed by BayesianRidge f_regression = mem.cache(feature_selection.f_regression) # caching function anova = feature_selection.SelectPercentile(f_regression) clf = Pipeline([('anova', anova), ('ridge', ridge)]) # Select the optimal percentage of features with grid search clf = GridSearchCV(clf, {'anova__percentile': [5, 10, 20]}, cv=cv) clf.fit(X, y) # set the best parameters coef_ = clf.best_estimator_.steps[-1][1].coef_ coef_ = clf.best_estimator_.steps[0][1].inverse_transform(coef_) coef_selection_ = coef_.reshape(size, size) ############################################################################### # Inverse the transformation to plot the results on an image plt.close('all') plt.figure(figsize=(7.3, 2.7)) plt.subplot(1, 3, 1) plt.imshow(coef, interpolation="nearest", cmap=plt.cm.RdBu_r) plt.title("True weights") plt.subplot(1, 3, 2) plt.imshow(coef_selection_, interpolation="nearest", cmap=plt.cm.RdBu_r) plt.title("Feature Selection") plt.subplot(1, 3, 3) plt.imshow(coef_agglomeration_, interpolation="nearest", cmap=plt.cm.RdBu_r) plt.title("Feature Agglomeration") plt.subplots_adjust(0.04, 0.0, 0.98, 0.94, 0.16, 0.26) plt.show() # Attempt to remove the temporary cachedir, but don't worry if it fails shutil.rmtree(cachedir, ignore_errors=True)
bsd-3-clause
blaggacao/odoo
addons/crm_partner_assign/wizard/crm_forward_to_partner.py
377
10606
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class crm_lead_forward_to_partner(osv.TransientModel): """ Forward info history to partners. """ _name = 'crm.lead.forward.to.partner' def _convert_to_assignation_line(self, cr, uid, lead, partner, context=None): lead_location = [] partner_location = [] if lead.country_id: lead_location.append(lead.country_id.name) if lead.city: lead_location.append(lead.city) if partner: if partner.country_id: partner_location.append(partner.country_id.name) if partner.city: partner_location.append(partner.city) return {'lead_id': lead.id, 'lead_location': ", ".join(lead_location), 'partner_assigned_id': partner and partner.id or False, 'partner_location': ", ".join(partner_location), 'lead_link': self.get_lead_portal_url(cr, uid, lead.id, lead.type, context=context), } def default_get(self, cr, uid, fields, context=None): if context is None: context = {} lead_obj = self.pool.get('crm.lead') email_template_obj = self.pool.get('email.template') try: template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', 'email_template_lead_forward_mail')[1] except ValueError: template_id = False res = super(crm_lead_forward_to_partner, self).default_get(cr, uid, fields, context=context) active_ids = context.get('active_ids') default_composition_mode = context.get('default_composition_mode') res['assignation_lines'] = [] if template_id: res['body'] = email_template_obj.get_email_template(cr, uid, template_id).body_html if active_ids: lead_ids = lead_obj.browse(cr, uid, active_ids, context=context) if default_composition_mode == 'mass_mail': partner_assigned_ids = lead_obj.search_geo_partner(cr, uid, active_ids, context=context) else: partner_assigned_ids = dict((lead.id, lead.partner_assigned_id and lead.partner_assigned_id.id or False) for lead in lead_ids) res['partner_id'] = lead_ids[0].partner_assigned_id.id for lead in lead_ids: partner_id = partner_assigned_ids.get(lead.id) or False partner = False if partner_id: partner = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context) res['assignation_lines'].append(self._convert_to_assignation_line(cr, uid, lead, partner)) return res def action_forward(self, cr, uid, ids, context=None): lead_obj = self.pool.get('crm.lead') record = self.browse(cr, uid, ids[0], context=context) email_template_obj = self.pool.get('email.template') try: template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', 'email_template_lead_forward_mail')[1] except ValueError: raise osv.except_osv(_('Email Template Error'), _('The Forward Email Template is not in the database')) try: portal_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_portal')[1] except ValueError: raise osv.except_osv(_('Portal Group Error'), _('The Portal group cannot be found')) local_context = context.copy() if not (record.forward_type == 'single'): no_email = set() for lead in record.assignation_lines: if lead.partner_assigned_id and not lead.partner_assigned_id.email: no_email.add(lead.partner_assigned_id.name) if no_email: raise osv.except_osv(_('Email Error'), ('Set an email address for the partner(s): %s' % ", ".join(no_email))) if record.forward_type == 'single' and not record.partner_id.email: raise osv.except_osv(_('Email Error'), ('Set an email address for the partner %s' % record.partner_id.name)) partners_leads = {} for lead in record.assignation_lines: partner = record.forward_type == 'single' and record.partner_id or lead.partner_assigned_id lead_details = { 'lead_link': lead.lead_link, 'lead_id': lead.lead_id, } if partner: partner_leads = partners_leads.get(partner.id) if partner_leads: partner_leads['leads'].append(lead_details) else: partners_leads[partner.id] = {'partner': partner, 'leads': [lead_details]} stage_id = False if record.assignation_lines and record.assignation_lines[0].lead_id.type == 'lead': try: stage_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', 'stage_portal_lead_assigned')[1] except ValueError: pass for partner_id, partner_leads in partners_leads.items(): in_portal = False for contact in (partner.child_ids or [partner]): if contact.user_ids: in_portal = portal_id in [g.id for g in contact.user_ids[0].groups_id] local_context['partner_id'] = partner_leads['partner'] local_context['partner_leads'] = partner_leads['leads'] local_context['partner_in_portal'] = in_portal email_template_obj.send_mail(cr, uid, template_id, ids[0], context=local_context) lead_ids = [lead['lead_id'].id for lead in partner_leads['leads']] values = {'partner_assigned_id': partner_id, 'user_id': partner_leads['partner'].user_id.id} if stage_id: values['stage_id'] = stage_id if partner_leads['partner'].user_id: values['section_id'] = partner_leads['partner'].user_id.default_section_id.id lead_obj.write(cr, uid, lead_ids, values) self.pool.get('crm.lead').message_subscribe(cr, uid, lead_ids, [partner_id], context=context) return True def get_lead_portal_url(self, cr, uid, lead_id, type, context=None): action = type == 'opportunity' and 'action_portal_opportunities' or 'action_portal_leads' try: action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', action)[1] except ValueError: action_id = False portal_link = "%s/?db=%s#id=%s&action=%s&view_type=form" % (self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url'), cr.dbname, lead_id, action_id) return portal_link def get_portal_url(self, cr, uid, ids, context=None): portal_link = "%s/?db=%s" % (self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url'), cr.dbname) return portal_link _columns = { 'forward_type': fields.selection([('single', 'a single partner: manual selection of partner'), ('assigned', "several partners: automatic assignation, using GPS coordinates and partner's grades"), ], 'Forward selected leads to'), 'partner_id': fields.many2one('res.partner', 'Forward Leads To'), 'assignation_lines': fields.one2many('crm.lead.assignation', 'forward_id', 'Partner Assignation'), 'body': fields.html('Contents', help='Automatically sanitized HTML contents'), } _defaults = { 'forward_type': lambda self, cr, uid, c: c.get('forward_type') or 'single', } class crm_lead_assignation (osv.TransientModel): _name = 'crm.lead.assignation' _columns = { 'forward_id': fields.many2one('crm.lead.forward.to.partner', 'Partner Assignation'), 'lead_id': fields.many2one('crm.lead', 'Lead'), 'lead_location': fields.char('Lead Location', size=128), 'partner_assigned_id': fields.many2one('res.partner', 'Assigned Partner'), 'partner_location': fields.char('Partner Location', size=128), 'lead_link': fields.char('Lead Single Links', size=128), } def on_change_lead_id(self, cr, uid, ids, lead_id, context=None): if not context: context = {} if not lead_id: return {'value': {'lead_location': False}} lead = self.pool.get('crm.lead').browse(cr, uid, lead_id, context=context) lead_location = [] if lead.country_id: lead_location.append(lead.country_id.name) if lead.city: lead_location.append(lead.city) return {'value': {'lead_location': ", ".join(lead_location)}} def on_change_partner_assigned_id(self, cr, uid, ids, partner_assigned_id, context=None): if not context: context = {} if not partner_assigned_id: return {'value': {'lead_location': False}} partner = self.pool.get('res.partner').browse(cr, uid, partner_assigned_id, context=context) partner_location = [] if partner.country_id: partner_location.append(partner.country_id.name) if partner.city: partner_location.append(partner.city) return {'value': {'partner_location': ", ".join(partner_location)}} # # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
huguesv/PTVS
Python/Product/Miniconda/Miniconda3-x64/Lib/ctypes/test/test_stringptr.py
114
2536
import unittest from test import support from ctypes import * import _ctypes_test lib = CDLL(_ctypes_test.__file__) class StringPtrTestCase(unittest.TestCase): @support.refcount_test def test__POINTER_c_char(self): class X(Structure): _fields_ = [("str", POINTER(c_char))] x = X() # NULL pointer access self.assertRaises(ValueError, getattr, x.str, "contents") b = c_buffer(b"Hello, World") from sys import getrefcount as grc self.assertEqual(grc(b), 2) x.str = b self.assertEqual(grc(b), 3) # POINTER(c_char) and Python string is NOT compatible # POINTER(c_char) and c_buffer() is compatible for i in range(len(b)): self.assertEqual(b[i], x.str[i]) self.assertRaises(TypeError, setattr, x, "str", "Hello, World") def test__c_char_p(self): class X(Structure): _fields_ = [("str", c_char_p)] x = X() # c_char_p and Python string is compatible # c_char_p and c_buffer is NOT compatible self.assertEqual(x.str, None) x.str = b"Hello, World" self.assertEqual(x.str, b"Hello, World") b = c_buffer(b"Hello, World") self.assertRaises(TypeError, setattr, x, b"str", b) def test_functions(self): strchr = lib.my_strchr strchr.restype = c_char_p # c_char_p and Python string is compatible # c_char_p and c_buffer are now compatible strchr.argtypes = c_char_p, c_char self.assertEqual(strchr(b"abcdef", b"c"), b"cdef") self.assertEqual(strchr(c_buffer(b"abcdef"), b"c"), b"cdef") # POINTER(c_char) and Python string is NOT compatible # POINTER(c_char) and c_buffer() is compatible strchr.argtypes = POINTER(c_char), c_char buf = c_buffer(b"abcdef") self.assertEqual(strchr(buf, b"c"), b"cdef") self.assertEqual(strchr(b"abcdef", b"c"), b"cdef") # XXX These calls are dangerous, because the first argument # to strchr is no longer valid after the function returns! # So we must keep a reference to buf separately strchr.restype = POINTER(c_char) buf = c_buffer(b"abcdef") r = strchr(buf, b"c") x = r[0], r[1], r[2], r[3], r[4] self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\000")) del buf # x1 will NOT be the same as x, usually: x1 = r[0], r[1], r[2], r[3], r[4] if __name__ == '__main__': unittest.main()
apache-2.0
kdaily/altanalyze
SubGeneViewerExport.py
1
10521
###SubGeneViewerExport #Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California #Author Nathan Salomonis - nsalomonis@gmail.com #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is furnished #to do so, subject to the following conditions: #THE 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. import sys, string import os.path import unique import export dirfile = unique ############ File Import Functions ############# def filepath(filename): fn = unique.filepath(filename) return fn def read_directory(sub_dir): dir_list = unique.read_directory(sub_dir) #add in code to prevent folder names from being included dir_list2 = [] for entry in dir_list: if entry[-4:] == ".txt" or entry[-4:] == ".all" or entry[-5:] == ".data" or entry[-3:] == ".fa": dir_list2.append(entry) return dir_list2 def returnDirectories(sub_dir): dir=os.path.dirname(dirfile.__file__) dir_list = os.listdir(dir + sub_dir) ###Below code used to prevent FILE names from being included dir_list2 = [] for entry in dir_list: if "." not in entry: dir_list2.append(entry) return dir_list2 class GrabFiles: def setdirectory(self,value): self.data = value def display(self): print self.data def searchdirectory(self,search_term): #self is an instance while self.data is the value of the instance files = getDirectoryFiles(self.data,search_term) if len(files)<1: print 'files not found' return files def returndirectory(self): dir_list = getAllDirectoryFiles(self.data) return dir_list def getAllDirectoryFiles(import_dir): all_files = [] dir_list = read_directory(import_dir) #send a sub_directory to a function to identify all files in a directory for data in dir_list: #loop through each file in the directory to output results data_dir = import_dir[1:]+'/'+data all_files.append(data_dir) return all_files def getDirectoryFiles(import_dir,search_term): dir_list = read_directory(import_dir) #send a sub_directory to a function to identify all files in a directory matches=[] for data in dir_list: #loop through each file in the directory to output results data_dir = import_dir[1:]+'/'+data if search_term in data_dir: matches.append(data_dir) return matches def cleanUpLine(line): line = string.replace(line,'\n','') line = string.replace(line,'\c','') data = string.replace(line,'\r','') data = string.replace(data,'"','') return data ############### Main Program ############### def importAnnotationData(filename): fn=filepath(filename); x=1 global gene_symbol_db; gene_symbol_db={} for line in open(fn,'rU').xreadlines(): data = cleanUpLine(line) t = string.split(data,'\t') if x==0: x=1 else: gene = t[0] try: symbol = t[1] except IndexError: symbol = '' if len(symbol)>0: gene_symbol_db[gene] = symbol def importGeneData(filename,data_type): fn=filepath(filename); x=0; gene_db={} for line in open(fn,'rU').xreadlines(): data = cleanUpLine(line) t = string.split(data,'\t') if x==0:x=1 else: proceed = 'yes' if data_type == 'junction': gene, region5, region3 = t; value_str = region5+':'+region3 if data_type == 'feature': probeset, gene, feature, region = t; value_str = region,feature+':'+region+':'+probeset ###access region data later #if (gene,region) not in region_db: region_db[gene,region] = feature,probeset ### Needed for processed structure table (see two lines down) try: region_db[gene,region].append((feature,probeset)) ### Needed for processed structure table (see two lines down) except KeyError: region_db[gene,region] = [(feature,probeset)] try: region_count_db[(gene,region)]+=1 except KeyError: region_count_db[(gene,region)]=1 ###have to add in when parsing structure probeset values for nulls (equal to 0) if data_type == 'structure': gene, exon, type, block, region, const, start, annot = t; region_id = exon if len(annot)<1: annot = '---' if (gene,exon) in region_db: probeset_data = region_db[(gene,exon)] for (feature,probeset) in probeset_data: count = str(region_count_db[(gene,exon)]) ###here, feature is the label (reversed below) value_str = feature+':'+exon+':'+probeset+':'+type+':'+count+':'+const+':'+start+':'+annot if gene in gene_symbol_db: ###Only incorporate gene data with a gene symbol, since Cytoscape currently requires this try: gene_db[gene].append(value_str) except KeyError: gene_db[gene] = [value_str] proceed = 'no' else: ### Occurs when no probeset is present: E.g. the imaginary first and last UTR region if doesn't exit feature = exon ###feature contains the region information, exon is the label used in Cytoscape exon,null = string.split(exon,'.') probeset = '0' count = '1' null_value_str = exon,exon+':'+feature+':'+probeset ###This is how Alex has it... to display the label without the '.1' first try: feature_db[gene].append(null_value_str) except KeyError: feature_db[gene] = [null_value_str] value_str = exon+':'+feature+':'+probeset+':'+type+':'+count+':'+const+':'+start+':'+annot if gene in structure_region_db: order_db = structure_region_db[gene] order_db[exon] = block else: order_db = {} order_db[exon] = block structure_region_db[gene] = order_db if gene in gene_symbol_db and proceed == 'yes': ###Only incorporate gene data with a gene symbol, since Cytoscape currently requires this try: gene_db[gene].append(value_str) except KeyError: gene_db[gene] = [value_str] return gene_db def exportData(gene_db,data_type,species): export_file = 'AltDatabase/ensembl/SubGeneViewer/'+species+'/Xport_sgv_'+data_type+'.csv' if data_type == 'feature': title = 'gene'+'\t'+'symbol'+'\t'+'sgv_feature'+'\n' if data_type == 'structure': title = 'gene'+'\t'+'symbol'+'\t'+'sgv_structure'+'\n' if data_type == 'splice': title = 'gene'+'\t'+'symbol'+'\t'+'sgv_splice'+'\n' data = export.createExportFile(export_file,'AltDatabase/ensembl/SubGeneViewer/'+species) #fn=filepath(export_file); data = open(fn,'w') data.write(title) for gene in gene_db: try: symbol = gene_symbol_db[gene] value_str_list = gene_db[gene] value_str = string.join(value_str_list,',') values = string.join([gene,symbol,value_str],'\t')+'\n'; data.write(values) except KeyError: null = [] data.close() print "exported to",export_file def customLSDeepCopy(ls): ls2=[] for i in ls: ls2.append(i) return ls2 def reorganizeData(species): global region_db; global region_count_db; global structure_region_db; global feature_db region_db={}; region_count_db={}; structure_region_db={} import_dir = '/AltDatabase/ensembl/'+species g = GrabFiles(); g.setdirectory(import_dir) exon_struct_file = g.searchdirectory('exon-structure') feature_file = g.searchdirectory('feature-data') junction_file = g.searchdirectory('junction-data') annot_file = g.searchdirectory('Ensembl-annotations.') importAnnotationData(annot_file[0]) ### Run the files through the same function which has options for different pieces of data. Feature data is processed a bit differently ### since fake probeset data is supplied for intron and UTR features not probed for splice_db = importGeneData(junction_file[0],'junction') feature_db = importGeneData(feature_file[0],'feature') structure_db = importGeneData(exon_struct_file[0],'structure') for gene in feature_db: order_db = structure_region_db[gene] temp_list0 = []; temp_list = []; rank = 1 for (region,value_str) in feature_db[gene]: ###First, we have to get the existing order... this is important because when we sort, it screw up ranking within an intron with many probesets temp_list0.append((rank,region,value_str)); rank+=1 for (rank,region,value_str) in temp_list0: try: block_number = order_db[region] except KeyError: print gene, region, order_db;kill temp_list.append((int(block_number),rank,value_str)) ###Combine the original ranking plus the ranking included from taking into account regions not covered by probesets temp_list.sort() temp_list2 = [] for (block,rank,value_str) in temp_list: temp_list2.append(value_str) feature_db[gene] = temp_list2 exportData(splice_db,'splice',species) exportData(structure_db,'structure',species) exportData(feature_db,'feature',species) if __name__ == '__main__': dirfile = unique species = 'Hs' reorganizeData(species)
apache-2.0
rhertzog/django
tests/serializers/test_yaml.py
50
5754
# -*- coding: utf-8 -*- from __future__ import unicode_literals import importlib import unittest from django.core import management, serializers from django.core.serializers.base import DeserializationError from django.test import SimpleTestCase, TestCase, TransactionTestCase from django.utils import six from django.utils.six import StringIO from .models import Author from .tests import SerializersTestBase, SerializersTransactionTestBase try: import yaml HAS_YAML = True except ImportError: HAS_YAML = False YAML_IMPORT_ERROR_MESSAGE = r'No module named yaml' class YamlImportModuleMock(object): """Provides a wrapped import_module function to simulate yaml ImportError In order to run tests that verify the behavior of the YAML serializer when run on a system that has yaml installed (like the django CI server), mock import_module, so that it raises an ImportError when the yaml serializer is being imported. The importlib.import_module() call is being made in the serializers.register_serializer(). Refs: #12756 """ def __init__(self): self._import_module = importlib.import_module def import_module(self, module_path): if module_path == serializers.BUILTIN_SERIALIZERS['yaml']: raise ImportError(YAML_IMPORT_ERROR_MESSAGE) return self._import_module(module_path) class NoYamlSerializerTestCase(SimpleTestCase): """Not having pyyaml installed provides a misleading error Refs: #12756 """ @classmethod def setUpClass(cls): """Removes imported yaml and stubs importlib.import_module""" super(NoYamlSerializerTestCase, cls).setUpClass() cls._import_module_mock = YamlImportModuleMock() importlib.import_module = cls._import_module_mock.import_module # clear out cached serializers to emulate yaml missing serializers._serializers = {} @classmethod def tearDownClass(cls): """Puts yaml back if necessary""" super(NoYamlSerializerTestCase, cls).tearDownClass() importlib.import_module = cls._import_module_mock._import_module # clear out cached serializers to clean out BadSerializer instances serializers._serializers = {} def test_serializer_pyyaml_error_message(self): """Using yaml serializer without pyyaml raises ImportError""" jane = Author(name="Jane") with self.assertRaises(ImportError): serializers.serialize("yaml", [jane]) def test_deserializer_pyyaml_error_message(self): """Using yaml deserializer without pyyaml raises ImportError""" with self.assertRaises(ImportError): serializers.deserialize("yaml", "") def test_dumpdata_pyyaml_error_message(self): """Calling dumpdata produces an error when yaml package missing""" with self.assertRaisesMessage(management.CommandError, YAML_IMPORT_ERROR_MESSAGE): management.call_command('dumpdata', format='yaml') @unittest.skipUnless(HAS_YAML, "No yaml library detected") class YamlSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "yaml" fwd_ref_str = """- fields: headline: Forward references pose no problem pub_date: 2006-06-16 15:00:00 categories: [1] author: 1 pk: 1 model: serializers.article - fields: name: Reference pk: 1 model: serializers.category - fields: name: Agnes pk: 1 model: serializers.author""" pkless_str = """- fields: name: Reference pk: null model: serializers.category - fields: name: Non-fiction model: serializers.category""" mapping_ordering_str = """- model: serializers.article pk: %(article_pk)s fields: author: %(author_pk)s headline: Poker has no place on ESPN pub_date: 2006-06-16 11:00:00 categories: [%(first_category_pk)s, %(second_category_pk)s] meta_data: [] """ @staticmethod def _validate_output(serial_str): try: yaml.safe_load(StringIO(serial_str)) except Exception: return False else: return True @staticmethod def _get_pk_values(serial_str): ret_list = [] stream = StringIO(serial_str) for obj_dict in yaml.safe_load(stream): ret_list.append(obj_dict["pk"]) return ret_list @staticmethod def _get_field_values(serial_str, field_name): ret_list = [] stream = StringIO(serial_str) for obj_dict in yaml.safe_load(stream): if "fields" in obj_dict and field_name in obj_dict["fields"]: field_value = obj_dict["fields"][field_name] # yaml.safe_load will return non-string objects for some # of the fields we are interested in, this ensures that # everything comes back as a string if isinstance(field_value, six.string_types): ret_list.append(field_value) else: ret_list.append(str(field_value)) return ret_list def test_yaml_deserializer_exception(self): with self.assertRaises(DeserializationError): for obj in serializers.deserialize("yaml", "{"): pass @unittest.skipUnless(HAS_YAML, "No yaml library detected") class YamlSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "yaml" fwd_ref_str = """- fields: headline: Forward references pose no problem pub_date: 2006-06-16 15:00:00 categories: [1] author: 1 pk: 1 model: serializers.article - fields: name: Reference pk: 1 model: serializers.category - fields: name: Agnes pk: 1 model: serializers.author"""
bsd-3-clause
catapult-project/catapult-csm
third_party/html5lib-python/html5lib/sanitizer.py
30
17677
from __future__ import absolute_import, division, unicode_literals import re from xml.sax.saxutils import escape, unescape from six.moves import urllib_parse as urlparse from .tokenizer import HTMLTokenizer from .constants import tokenTypes content_type_rgx = re.compile(r''' ^ # Match a content type <application>/<type> (?P<content_type>[-a-zA-Z0-9.]+/[-a-zA-Z0-9.]+) # Match any character set and encoding (?:(?:;charset=(?:[-a-zA-Z0-9]+)(?:;(?:base64))?) |(?:;(?:base64))?(?:;charset=(?:[-a-zA-Z0-9]+))?) # Assume the rest is data ,.* $ ''', re.VERBOSE) class HTMLSanitizerMixin(object): """ sanitization of XHTML+MathML+SVG and of inline style attributes.""" acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset', 'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins', 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter', 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option', 'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select', 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video'] mathml_elements = ['maction', 'math', 'merror', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'none'] svg_elements = ['a', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'clipPath', 'circle', 'defs', 'desc', 'ellipse', 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern', 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', 'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use'] acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis', 'background', 'balance', 'bgcolor', 'bgproperties', 'border', 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding', 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff', 'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'compact', 'contenteditable', 'controls', 'coords', 'data', 'datafld', 'datapagesize', 'datasrc', 'datetime', 'default', 'delay', 'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end', 'face', 'for', 'form', 'frame', 'galleryimg', 'gutter', 'headers', 'height', 'hidefocus', 'hidden', 'high', 'href', 'hreflang', 'hspace', 'icon', 'id', 'inputmode', 'ismap', 'keytype', 'label', 'leftspacing', 'lang', 'list', 'longdesc', 'loop', 'loopcount', 'loopend', 'loopstart', 'low', 'lowsrc', 'max', 'maxlength', 'media', 'method', 'min', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'open', 'optimum', 'pattern', 'ping', 'point-size', 'poster', 'pqg', 'preload', 'prompt', 'radiogroup', 'readonly', 'rel', 'repeat-max', 'repeat-min', 'replace', 'required', 'rev', 'rightspacing', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'start', 'step', 'style', 'summary', 'suppress', 'tabindex', 'target', 'template', 'title', 'toppadding', 'type', 'unselectable', 'usemap', 'urn', 'valign', 'value', 'variable', 'volume', 'vspace', 'vrml', 'width', 'wrap', 'xml:lang'] mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'depth', 'display', 'displaystyle', 'equalcolumns', 'equalrows', 'fence', 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness', 'lspace', 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant', 'maxsize', 'minsize', 'other', 'rowalign', 'rowalign', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection', 'separator', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show', 'xlink:type', 'xmlns', 'xmlns:xlink'] svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic', 'arabic-form', 'ascent', 'attributeName', 'attributeType', 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height', 'class', 'clip-path', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx', 'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-opacity', 'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x', 'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', 'keySplines', 'keyTimes', 'lang', 'marker-end', 'marker-mid', 'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'mathematical', 'max', 'min', 'name', 'offset', 'opacity', 'orient', 'origin', 'overline-position', 'overline-thickness', 'panose-1', 'path', 'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'systemLanguage', 'target', 'text-anchor', 'to', 'transform', 'type', 'u1', 'u2', 'underline-position', 'underline-thickness', 'unicode', 'unicode-range', 'units-per-em', 'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x', 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', 'y1', 'y2', 'zoomAndPan'] attr_val_is_uri = ['href', 'src', 'cite', 'action', 'longdesc', 'poster', 'background', 'datasrc', 'dynsrc', 'lowsrc', 'ping', 'poster', 'xlink:href', 'xml:base'] svg_attr_val_allows_ref = ['clip-path', 'color-profile', 'cursor', 'fill', 'filter', 'marker', 'marker-start', 'marker-mid', 'marker-end', 'mask', 'stroke'] svg_allow_local_href = ['altGlyph', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'cursor', 'feImage', 'filter', 'linearGradient', 'pattern', 'radialGradient', 'textpath', 'tref', 'set', 'use'] acceptable_css_properties = ['azimuth', 'background-color', 'border-bottom-color', 'border-collapse', 'border-color', 'border-left-color', 'border-right-color', 'border-top-color', 'clear', 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font', 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'overflow', 'pause', 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness', 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation', 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent', 'unicode-bidi', 'vertical-align', 'voice-family', 'volume', 'white-space', 'width'] acceptable_css_keywords = ['auto', 'aqua', 'black', 'block', 'blue', 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed', 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left', 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive', 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top', 'transparent', 'underline', 'white', 'yellow'] acceptable_svg_properties = ['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-opacity'] acceptable_protocols = ['ed2k', 'ftp', 'http', 'https', 'irc', 'mailto', 'news', 'gopher', 'nntp', 'telnet', 'webcal', 'xmpp', 'callto', 'feed', 'urn', 'aim', 'rsync', 'tag', 'ssh', 'sftp', 'rtsp', 'afs', 'data'] acceptable_content_types = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'text/plain'] # subclasses may define their own versions of these constants allowed_elements = acceptable_elements + mathml_elements + svg_elements allowed_attributes = acceptable_attributes + mathml_attributes + svg_attributes allowed_css_properties = acceptable_css_properties allowed_css_keywords = acceptable_css_keywords allowed_svg_properties = acceptable_svg_properties allowed_protocols = acceptable_protocols allowed_content_types = acceptable_content_types # Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and # stripping out all # attributes not in ALLOWED_ATTRIBUTES. Style # attributes are parsed, and a restricted set, # specified by # ALLOWED_CSS_PROPERTIES and ALLOWED_CSS_KEYWORDS, are allowed through. # attributes in ATTR_VAL_IS_URI are scanned, and only URI schemes specified # in ALLOWED_PROTOCOLS are allowed. # # sanitize_html('<script> do_nasty_stuff() </script>') # => &lt;script> do_nasty_stuff() &lt;/script> # sanitize_html('<a href="javascript: sucker();">Click here for $100</a>') # => <a>Click here for $100</a> def sanitize_token(self, token): # accommodate filters which use token_type differently token_type = token["type"] if token_type in list(tokenTypes.keys()): token_type = tokenTypes[token_type] if token_type in (tokenTypes["StartTag"], tokenTypes["EndTag"], tokenTypes["EmptyTag"]): if token["name"] in self.allowed_elements: return self.allowed_token(token, token_type) else: return self.disallowed_token(token, token_type) elif token_type == tokenTypes["Comment"]: pass else: return token def allowed_token(self, token, token_type): if "data" in token: attrs = dict([(name, val) for name, val in token["data"][::-1] if name in self.allowed_attributes]) for attr in self.attr_val_is_uri: if attr not in attrs: continue val_unescaped = re.sub("[`\000-\040\177-\240\s]+", '', unescape(attrs[attr])).lower() # remove replacement characters from unescaped characters val_unescaped = val_unescaped.replace("\ufffd", "") uri = urlparse.urlparse(val_unescaped) if uri and uri.scheme: if uri.scheme not in self.allowed_protocols: del attrs[attr] if uri.scheme == 'data': m = content_type_rgx.match(uri.path) if not m: del attrs[attr] elif m.group('content_type') not in self.allowed_content_types: del attrs[attr] for attr in self.svg_attr_val_allows_ref: if attr in attrs: attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', ' ', unescape(attrs[attr])) if (token["name"] in self.svg_allow_local_href and 'xlink:href' in attrs and re.search('^\s*[^#\s].*', attrs['xlink:href'])): del attrs['xlink:href'] if 'style' in attrs: attrs['style'] = self.sanitize_css(attrs['style']) token["data"] = [[name, val] for name, val in list(attrs.items())] return token def disallowed_token(self, token, token_type): if token_type == tokenTypes["EndTag"]: token["data"] = "</%s>" % token["name"] elif token["data"]: attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token["data"]]) token["data"] = "<%s%s>" % (token["name"], attrs) else: token["data"] = "<%s>" % token["name"] if token.get("selfClosing"): token["data"] = token["data"][:-1] + "/>" if token["type"] in list(tokenTypes.keys()): token["type"] = "Characters" else: token["type"] = tokenTypes["Characters"] del token["name"] return token def sanitize_css(self, style): # disallow urls style = re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) # gauntlet if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): return '' if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): return '' clean = [] for prop, value in re.findall("([-\w]+)\s*:\s*([^:;]*)", style): if not value: continue if prop.lower() in self.allowed_css_properties: clean.append(prop + ': ' + value + ';') elif prop.split('-')[0].lower() in ['background', 'border', 'margin', 'padding']: for keyword in value.split(): if keyword not in self.acceptable_css_keywords and \ not re.match("^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$", keyword): break else: clean.append(prop + ': ' + value + ';') elif prop.lower() in self.allowed_svg_properties: clean.append(prop + ': ' + value + ';') return ' '.join(clean) class HTMLSanitizer(HTMLTokenizer, HTMLSanitizerMixin): def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True, lowercaseElementName=False, lowercaseAttrName=False, parser=None): # Change case matching defaults as we only output lowercase html anyway # This solution doesn't seem ideal... HTMLTokenizer.__init__(self, stream, encoding, parseMeta, useChardet, lowercaseElementName, lowercaseAttrName, parser=parser) def __iter__(self): for token in HTMLTokenizer.__iter__(self): token = self.sanitize_token(token) if token: yield token
bsd-3-clause
brenton/cobbler
cobbler/modules/authz_ownership.py
1
5953
""" Authorization module that allow users listed in /etc/cobbler/users.conf to be permitted to access resources, with the further restriction that cobbler objects can be edited to only allow certain users/groups to access those specific objects. Copyright 2008, Red Hat, Inc Michael DeHaan <mdehaan@redhat.com> This software may be freely redistributed under the terms of the GNU general public license. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. """ import distutils.sysconfig import ConfigParser import sys import os from cobbler.utils import _ plib = distutils.sysconfig.get_python_lib() mod_path="%s/cobbler" % plib sys.path.insert(0, mod_path) import cexceptions import utils def register(): """ The mandatory cobbler module registration hook. """ return "authz" def __parse_config(): etcfile='/etc/cobbler/users.conf' if not os.path.exists(etcfile): raise CX(_("/etc/cobbler/users.conf does not exist")) config = ConfigParser.ConfigParser() config.read(etcfile) alldata = {} sections = config.sections() for g in sections: alldata[str(g)] = {} opts = config.options(g) for o in opts: alldata[g][o] = 1 return alldata def __authorize_kickstart(api_handle, user, user_groups, kickstart): # the authorization rules for kickstart editing are a bit # of a special case. Non-admin users can edit a kickstart # only if all objects that depend on that kickstart are # editable by the user in question. # # Example: # if Pinky owns ProfileA # and the Brain owns ProfileB # and both profiles use the same kickstart template # and neither Pinky nor the Brain is an admin # neither is allowed to edit the kickstart template # because they would make unwanted changes to each other # # In the above scenario the UI will explain the problem # and ask that the user asks the admin to resolve it if required. # NOTE: this function is only called by authorize so admin users are # cleared before this function is called. lst = api_handle.find_profile(kickstart=kickstart, return_list=True) lst.extend(api_handle.find_system(kickstart=kickstart, return_list=True)) for obj in lst: if not __is_user_allowed(obj, user, user_groups): return 0 return 1 def __is_user_allowed(obj, user, user_groups): if obj.owners == []: # no ownership restrictions, cleared return 1 for allowed in obj.owners: if user == allowed: # user match return 1 # else look for a group match for group in user_groups: if group == allowed and user in user_groups[group]: return 1 return 0 def authorize(api_handle,user,resource,arg1=None,arg2=None): """ Validate a user against a resource. All users in the file are permitted by this module. """ # everybody can get read-only access to everything # if they pass authorization, they don't have to be in users.conf if resource is not None: for x in [ "get", "read", "/cobbler/web" ]: if resource.startswith(x): return 1 user_groups = __parse_config() # classify the type of operation modify_operation = False for criteria in ["save","remove","modify","write","edit"]: if resource.find(criteria) != -1: modify_operation = True # FIXME: is everyone allowed to copy? I think so. # FIXME: deal with the problem of deleted parents and promotion found_user = False for g in user_groups: for x in user_groups[g]: if x == user: found_user = True # if user is in the admin group, always authorize # regardless of the ownership of the object. if g == "admins" or g == "admin": return 1 break if not found_user: # if the user isn't anywhere in the file, reject regardless # they can still use read-only XMLRPC return 0 if not modify_operation: # sufficient to allow access for non save/remove ops to all # users for now, may want to refine later. return 1 # now we have a modify_operation op, so we must check ownership # of the object. remove ops pass in arg1 as a string name, # saves pass in actual objects, so we must treat them differently. # kickstarts are even more special so we call those out to another # function, rather than going through the rest of the code here. if resource.find("kickstart") != -1: return __authorize_kickstart(api_handle,user,user_groups,arg1) obj = None if resource.find("remove") != -1: if resource == "remove_distro": obj = api_handle.find_distro(arg1) elif resource == "remove_profile": obj = api_handle.find_profile(arg1) elif resource == "remove_system": obj = api_handle.find_system(arg1) elif resource == "remove_repo": obj = api_handle.find_system(arg1) elif resource.find("save") != -1 or resource.find("modify") != -1: obj = arg1 # if the object has no ownership data, allow access regardless if obj.owners is None or obj.owners == []: return 1 return __is_user_allowed(obj,user,user_groups) if __name__ == "__main__": # real tests are contained in tests/tests.py import api as cobbler_api api = cobbler_api.BootAPI() print __parse_config() print authorize(api, "admin1", "sync") d = api.find_distro("F9B-i386") d.set_owners(["allowed"]) api.add_distro(d) print authorize(api, "admin1", "save_distro", d) print authorize(api, "basement2", "save_distro", d)
gpl-2.0
zhjunlang/kbengine
kbe/res/scripts/common/Lib/test/test_strtod.py
84
20594
# Tests for the correctly-rounded string -> float conversions # introduced in Python 2.7 and 3.1. import random import unittest import re import sys import test.support if getattr(sys, 'float_repr_style', '') != 'short': raise unittest.SkipTest('correctly-rounded string->float conversions ' 'not available on this system') # Correctly rounded str -> float in pure Python, for comparison. strtod_parser = re.compile(r""" # A numeric string consists of: (?P<sign>[-+])? # an optional sign, followed by (?=\d|\.\d) # a number with at least one digit (?P<int>\d*) # having a (possibly empty) integer part (?:\.(?P<frac>\d*))? # followed by an optional fractional part (?:E(?P<exp>[-+]?\d+))? # and an optional exponent \Z """, re.VERBOSE | re.IGNORECASE).match # Pure Python version of correctly rounded string->float conversion. # Avoids any use of floating-point by returning the result as a hex string. def strtod(s, mant_dig=53, min_exp = -1021, max_exp = 1024): """Convert a finite decimal string to a hex string representing an IEEE 754 binary64 float. Return 'inf' or '-inf' on overflow. This function makes no use of floating-point arithmetic at any stage.""" # parse string into a pair of integers 'a' and 'b' such that # abs(decimal value) = a/b, along with a boolean 'negative'. m = strtod_parser(s) if m is None: raise ValueError('invalid numeric string') fraction = m.group('frac') or '' intpart = int(m.group('int') + fraction) exp = int(m.group('exp') or '0') - len(fraction) negative = m.group('sign') == '-' a, b = intpart*10**max(exp, 0), 10**max(0, -exp) # quick return for zeros if not a: return '-0x0.0p+0' if negative else '0x0.0p+0' # compute exponent e for result; may be one too small in the case # that the rounded value of a/b lies in a different binade from a/b d = a.bit_length() - b.bit_length() d += (a >> d if d >= 0 else a << -d) >= b e = max(d, min_exp) - mant_dig # approximate a/b by number of the form q * 2**e; adjust e if necessary a, b = a << max(-e, 0), b << max(e, 0) q, r = divmod(a, b) if 2*r > b or 2*r == b and q & 1: q += 1 if q.bit_length() == mant_dig+1: q //= 2 e += 1 # double check that (q, e) has the right form assert q.bit_length() <= mant_dig and e >= min_exp - mant_dig assert q.bit_length() == mant_dig or e == min_exp - mant_dig # check for overflow and underflow if e + q.bit_length() > max_exp: return '-inf' if negative else 'inf' if not q: return '-0x0.0p+0' if negative else '0x0.0p+0' # for hex representation, shift so # bits after point is a multiple of 4 hexdigs = 1 + (mant_dig-2)//4 shift = 3 - (mant_dig-2)%4 q, e = q << shift, e - shift return '{}0x{:x}.{:0{}x}p{:+d}'.format( '-' if negative else '', q // 16**hexdigs, q % 16**hexdigs, hexdigs, e + 4*hexdigs) TEST_SIZE = 10 class StrtodTests(unittest.TestCase): def check_strtod(self, s): """Compare the result of Python's builtin correctly rounded string->float conversion (using float) to a pure Python correctly rounded string->float implementation. Fail if the two methods give different results.""" try: fs = float(s) except OverflowError: got = '-inf' if s[0] == '-' else 'inf' except MemoryError: got = 'memory error' else: got = fs.hex() expected = strtod(s) self.assertEqual(expected, got, "Incorrectly rounded str->float conversion for {}: " "expected {}, got {}".format(s, expected, got)) def test_short_halfway_cases(self): # exact halfway cases with a small number of significant digits for k in 0, 5, 10, 15, 20: # upper = smallest integer >= 2**54/5**k upper = -(-2**54//5**k) # lower = smallest odd number >= 2**53/5**k lower = -(-2**53//5**k) if lower % 2 == 0: lower += 1 for i in range(TEST_SIZE): # Select a random odd n in [2**53/5**k, # 2**54/5**k). Then n * 10**k gives a halfway case # with small number of significant digits. n, e = random.randrange(lower, upper, 2), k # Remove any additional powers of 5. while n % 5 == 0: n, e = n // 5, e + 1 assert n % 10 in (1, 3, 7, 9) # Try numbers of the form n * 2**p2 * 10**e, p2 >= 0, # until n * 2**p2 has more than 20 significant digits. digits, exponent = n, e while digits < 10**20: s = '{}e{}'.format(digits, exponent) self.check_strtod(s) # Same again, but with extra trailing zeros. s = '{}e{}'.format(digits * 10**40, exponent - 40) self.check_strtod(s) digits *= 2 # Try numbers of the form n * 5**p2 * 10**(e - p5), p5 # >= 0, with n * 5**p5 < 10**20. digits, exponent = n, e while digits < 10**20: s = '{}e{}'.format(digits, exponent) self.check_strtod(s) # Same again, but with extra trailing zeros. s = '{}e{}'.format(digits * 10**40, exponent - 40) self.check_strtod(s) digits *= 5 exponent -= 1 def test_halfway_cases(self): # test halfway cases for the round-half-to-even rule for i in range(100 * TEST_SIZE): # bit pattern for a random finite positive (or +0.0) float bits = random.randrange(2047*2**52) # convert bit pattern to a number of the form m * 2**e e, m = divmod(bits, 2**52) if e: m, e = m + 2**52, e - 1 e -= 1074 # add 0.5 ulps m, e = 2*m + 1, e - 1 # convert to a decimal string if e >= 0: digits = m << e exponent = 0 else: # m * 2**e = (m * 5**-e) * 10**e digits = m * 5**-e exponent = e s = '{}e{}'.format(digits, exponent) self.check_strtod(s) def test_boundaries(self): # boundaries expressed as triples (n, e, u), where # n*10**e is an approximation to the boundary value and # u*10**e is 1ulp boundaries = [ (10000000000000000000, -19, 1110), # a power of 2 boundary (1.0) (17976931348623159077, 289, 1995), # overflow boundary (2.**1024) (22250738585072013831, -327, 4941), # normal/subnormal (2.**-1022) (0, -327, 4941), # zero ] for n, e, u in boundaries: for j in range(1000): digits = n + random.randrange(-3*u, 3*u) exponent = e s = '{}e{}'.format(digits, exponent) self.check_strtod(s) n *= 10 u *= 10 e -= 1 def test_underflow_boundary(self): # test values close to 2**-1075, the underflow boundary; similar # to boundary_tests, except that the random error doesn't scale # with n for exponent in range(-400, -320): base = 10**-exponent // 2**1075 for j in range(TEST_SIZE): digits = base + random.randrange(-1000, 1000) s = '{}e{}'.format(digits, exponent) self.check_strtod(s) def test_bigcomp(self): for ndigs in 5, 10, 14, 15, 16, 17, 18, 19, 20, 40, 41, 50: dig10 = 10**ndigs for i in range(10 * TEST_SIZE): digits = random.randrange(dig10) exponent = random.randrange(-400, 400) s = '{}e{}'.format(digits, exponent) self.check_strtod(s) def test_parsing(self): # make '0' more likely to be chosen than other digits digits = '000000123456789' signs = ('+', '-', '') # put together random short valid strings # \d*[.\d*]?e for i in range(1000): for j in range(TEST_SIZE): s = random.choice(signs) intpart_len = random.randrange(5) s += ''.join(random.choice(digits) for _ in range(intpart_len)) if random.choice([True, False]): s += '.' fracpart_len = random.randrange(5) s += ''.join(random.choice(digits) for _ in range(fracpart_len)) else: fracpart_len = 0 if random.choice([True, False]): s += random.choice(['e', 'E']) s += random.choice(signs) exponent_len = random.randrange(1, 4) s += ''.join(random.choice(digits) for _ in range(exponent_len)) if intpart_len + fracpart_len: self.check_strtod(s) else: try: float(s) except ValueError: pass else: assert False, "expected ValueError" @test.support.bigmemtest(size=test.support._2G+10, memuse=3, dry_run=False) def test_oversized_digit_strings(self, maxsize): # Input string whose length doesn't fit in an INT. s = "1." + "1" * maxsize with self.assertRaises(ValueError): float(s) del s s = "0." + "0" * maxsize + "1" with self.assertRaises(ValueError): float(s) del s def test_large_exponents(self): # Verify that the clipping of the exponent in strtod doesn't affect the # output values. def positive_exp(n): """ Long string with value 1.0 and exponent n""" return '0.{}1e+{}'.format('0'*(n-1), n) def negative_exp(n): """ Long string with value 1.0 and exponent -n""" return '1{}e-{}'.format('0'*n, n) self.assertEqual(float(positive_exp(10000)), 1.0) self.assertEqual(float(positive_exp(20000)), 1.0) self.assertEqual(float(positive_exp(30000)), 1.0) self.assertEqual(float(negative_exp(10000)), 1.0) self.assertEqual(float(negative_exp(20000)), 1.0) self.assertEqual(float(negative_exp(30000)), 1.0) def test_particular(self): # inputs that produced crashes or incorrectly rounded results with # previous versions of dtoa.c, for various reasons test_strings = [ # issue 7632 bug 1, originally reported failing case '2183167012312112312312.23538020374420446192e-370', # 5 instances of issue 7632 bug 2 '12579816049008305546974391768996369464963024663104e-357', '17489628565202117263145367596028389348922981857013e-357', '18487398785991994634182916638542680759613590482273e-357', '32002864200581033134358724675198044527469366773928e-358', '94393431193180696942841837085033647913224148539854e-358', '73608278998966969345824653500136787876436005957953e-358', '64774478836417299491718435234611299336288082136054e-358', '13704940134126574534878641876947980878824688451169e-357', '46697445774047060960624497964425416610480524760471e-358', # failing case for bug introduced by METD in r77451 (attempted # fix for issue 7632, bug 2), and fixed in r77482. '28639097178261763178489759107321392745108491825303e-311', # two numbers demonstrating a flaw in the bigcomp 'dig == 0' # correction block (issue 7632, bug 3) '1.00000000000000001e44', '1.0000000000000000100000000000000000000001e44', # dtoa.c bug for numbers just smaller than a power of 2 (issue # 7632, bug 4) '99999999999999994487665465554760717039532578546e-47', # failing case for off-by-one error introduced by METD in # r77483 (dtoa.c cleanup), fixed in r77490 '965437176333654931799035513671997118345570045914469' #... '6213413350821416312194420007991306908470147322020121018368e0', # incorrect lsb detection for round-half-to-even when # bc->scale != 0 (issue 7632, bug 6). '104308485241983990666713401708072175773165034278685' #... '682646111762292409330928739751702404658197872319129' #... '036519947435319418387839758990478549477777586673075' #... '945844895981012024387992135617064532141489278815239' #... '849108105951619997829153633535314849999674266169258' #... '928940692239684771590065027025835804863585454872499' #... '320500023126142553932654370362024104462255244034053' #... '203998964360882487378334860197725139151265590832887' #... '433736189468858614521708567646743455601905935595381' #... '852723723645799866672558576993978025033590728687206' #... '296379801363024094048327273913079612469982585674824' #... '156000783167963081616214710691759864332339239688734' #... '656548790656486646106983450809073750535624894296242' #... '072010195710276073042036425579852459556183541199012' #... '652571123898996574563824424330960027873516082763671875e-1075', # demonstration that original fix for issue 7632 bug 1 was # buggy; the exit condition was too strong '247032822920623295e-341', # demonstrate similar problem to issue 7632 bug1: crash # with 'oversized quotient in quorem' message. '99037485700245683102805043437346965248029601286431e-373', '99617639833743863161109961162881027406769510558457e-373', '98852915025769345295749278351563179840130565591462e-372', '99059944827693569659153042769690930905148015876788e-373', '98914979205069368270421829889078356254059760327101e-372', # issue 7632 bug 5: the following 2 strings convert differently '1000000000000000000000000000000000000000e-16', '10000000000000000000000000000000000000000e-17', # issue 7632 bug 7 '991633793189150720000000000000000000000000000000000000000e-33', # And another, similar, failing halfway case '4106250198039490000000000000000000000000000000000000000e-38', # issue 7632 bug 8: the following produced 10.0 '10.900000000000000012345678912345678912345', # two humongous values from issue 7743 '116512874940594195638617907092569881519034793229385' #... '228569165191541890846564669771714896916084883987920' #... '473321268100296857636200926065340769682863349205363' #... '349247637660671783209907949273683040397979984107806' #... '461822693332712828397617946036239581632976585100633' #... '520260770761060725403904123144384571612073732754774' #... '588211944406465572591022081973828448927338602556287' #... '851831745419397433012491884869454462440536895047499' #... '436551974649731917170099387762871020403582994193439' #... '761933412166821484015883631622539314203799034497982' #... '130038741741727907429575673302461380386596501187482' #... '006257527709842179336488381672818798450229339123527' #... '858844448336815912020452294624916993546388956561522' #... '161875352572590420823607478788399460162228308693742' #... '05287663441403533948204085390898399055004119873046875e-1075', '525440653352955266109661060358202819561258984964913' #... '892256527849758956045218257059713765874251436193619' #... '443248205998870001633865657517447355992225852945912' #... '016668660000210283807209850662224417504752264995360' #... '631512007753855801075373057632157738752800840302596' #... '237050247910530538250008682272783660778181628040733' #... '653121492436408812668023478001208529190359254322340' #... '397575185248844788515410722958784640926528544043090' #... '115352513640884988017342469275006999104519620946430' #... '818767147966495485406577703972687838176778993472989' #... '561959000047036638938396333146685137903018376496408' #... '319705333868476925297317136513970189073693314710318' #... '991252811050501448326875232850600451776091303043715' #... '157191292827614046876950225714743118291034780466325' #... '085141343734564915193426994587206432697337118211527' #... '278968731294639353354774788602467795167875117481660' #... '4738791256853675690543663283782215866825e-1180', # exercise exit conditions in bigcomp comparison loop '2602129298404963083833853479113577253105939995688e2', '260212929840496308383385347911357725310593999568896e0', '26021292984049630838338534791135772531059399956889601e-2', '260212929840496308383385347911357725310593999568895e0', '260212929840496308383385347911357725310593999568897e0', '260212929840496308383385347911357725310593999568996e0', '260212929840496308383385347911357725310593999568866e0', # 2**53 '9007199254740992.00', # 2**1024 - 2**970: exact overflow boundary. All values # smaller than this should round to something finite; any value # greater than or equal to this one overflows. '179769313486231580793728971405303415079934132710037' #... '826936173778980444968292764750946649017977587207096' #... '330286416692887910946555547851940402630657488671505' #... '820681908902000708383676273854845817711531764475730' #... '270069855571366959622842914819860834936475292719074' #... '168444365510704342711559699508093042880177904174497792', # 2**1024 - 2**970 - tiny '179769313486231580793728971405303415079934132710037' #... '826936173778980444968292764750946649017977587207096' #... '330286416692887910946555547851940402630657488671505' #... '820681908902000708383676273854845817711531764475730' #... '270069855571366959622842914819860834936475292719074' #... '168444365510704342711559699508093042880177904174497791.999', # 2**1024 - 2**970 + tiny '179769313486231580793728971405303415079934132710037' #... '826936173778980444968292764750946649017977587207096' #... '330286416692887910946555547851940402630657488671505' #... '820681908902000708383676273854845817711531764475730' #... '270069855571366959622842914819860834936475292719074' #... '168444365510704342711559699508093042880177904174497792.001', # 1 - 2**-54, +-tiny '999999999999999944488848768742172978818416595458984375e-54', '9999999999999999444888487687421729788184165954589843749999999e-54', '9999999999999999444888487687421729788184165954589843750000001e-54', # Value found by Rick Regan that gives a result of 2**-968 # under Gay's dtoa.c (as of Nov 04, 2010); since fixed. # (Fixed some time ago in Python's dtoa.c.) '0.0000000000000000000000000000000000000000100000000' #... '000000000576129113423785429971690421191214034235435' #... '087147763178149762956868991692289869941246658073194' #... '51982237978882039897143840789794921875', ] for s in test_strings: self.check_strtod(s) def test_main(): test.support.run_unittest(StrtodTests) if __name__ == "__main__": test_main()
lgpl-3.0
lmprice/ansible
lib/ansible/modules/network/nxos/nxos_vtp_version.py
70
5734
#!/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/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = ''' --- module: nxos_vtp_version extends_documentation_fragment: nxos version_added: "2.2" short_description: Manages VTP version configuration. description: - Manages VTP version configuration. author: - Gabriele Gerbino (@GGabriele) notes: - Tested against NXOSv 7.3.(0)D1(1) on VIRL - VTP feature must be active on the device to use this module. - This module is used to manage only VTP version. - Use this in combination with M(nxos_vtp_password) and M(nxos_vtp_version) to fully manage VTP operations. options: version: description: - VTP version number. required: true choices: ['1', '2'] ''' EXAMPLES = ''' # ENSURE VTP VERSION IS 2 - nxos_vtp_version: version: 2 host: "{{ inventory_hostname }}" username: "{{ un }}" password: "{{ pwd }}" ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: always type: dict sample: {"version": "2"} existing: description: - k/v pairs of existing vtp returned: always type: dict sample: {"domain": "testing", "version": "1", "vtp_password": "\"} end_state: description: k/v pairs of vtp after module execution returned: always type: dict sample: {"domain": "testing", "version": "2", "vtp_password": "\"} updates: description: command sent to the device returned: always type: list sample: ["vtp version 2"] changed: description: check to see if a change was made on the device returned: always type: boolean sample: true ''' from ansible.module_utils.network.nxos.nxos import load_config, run_commands from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleModule import re import re def execute_show_command(command, module, command_type='cli_show'): if 'status' not in command: output = 'json' else: output = 'text' cmds = [{ 'command': command, 'output': output, }] body = run_commands(module, cmds) return body def flatten_list(command_lists): flat_command_list = [] for command in command_lists: if isinstance(command, list): flat_command_list.extend(command) else: flat_command_list.append(command) return flat_command_list def get_vtp_config(module): command = 'show vtp status' body = execute_show_command( command, module)[0] vtp_parsed = {} if body: version_regex = r'.*VTP version running\s+:\s+(?P<version>\d).*' domain_regex = r'.*VTP Domain Name\s+:\s+(?P<domain>\S+).*' try: match_version = re.match(version_regex, body, re.DOTALL) version = match_version.groupdict()['version'] except AttributeError: version = '' try: match_domain = re.match(domain_regex, body, re.DOTALL) domain = match_domain.groupdict()['domain'] except AttributeError: domain = '' if domain and version: vtp_parsed['domain'] = domain vtp_parsed['version'] = version vtp_parsed['vtp_password'] = get_vtp_password(module) return vtp_parsed def get_vtp_password(module): command = 'show vtp password' body = execute_show_command(command, module)[0] try: password = body['passwd'] if password: return str(password) else: return "" except TypeError: return "" def main(): argument_spec = dict( version=dict(type='str', choices=['1', '2'], required=True), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) version = module.params['version'] existing = get_vtp_config(module) end_state = existing args = dict(version=version) changed = False proposed = dict((k, v) for k, v in args.items() if v is not None) delta = dict(set(proposed.items()).difference(existing.items())) commands = [] if delta: commands.append(['vtp version {0}'.format(version)]) cmds = flatten_list(commands) if cmds: if module.check_mode: module.exit_json(changed=True, commands=cmds) else: changed = True load_config(module, cmds) end_state = get_vtp_config(module) if 'configure' in cmds: cmds.pop(0) results = {} results['proposed'] = proposed results['existing'] = existing results['end_state'] = end_state results['updates'] = cmds results['changed'] = changed results['warnings'] = warnings module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
geoff-reid/RackHD
test/tests/api-cit/v2_0/nodes_tests.py
9
18541
''' Copyright (c) 2016-2017 Dell Inc. or its subsidiaries. All Rights Reserved. Author(s): ''' import fit_path # NOQA: unused import import json import fit_common import flogging from on_http_api2_0 import ApiApi as Api from on_http_api2_0.rest import ApiException from config.api2_0_config import config from datetime import datetime from json import loads from time import sleep from nosedep import depends from nose.plugins.attrib import attr logs = flogging.get_loggers() @attr(regression=False, smoke=True, nodes_api2_tests=True) class NodesTests(fit_common.unittest.TestCase): @classmethod def setUpClass(cls): cls._cls_client = config.api_client cls.clear_nodes() @classmethod def tearDownClass(cls): cls.clear_nodes() def setUp(self): self.__client = config.api_client self.__worker = None self.__discovery_duration = None self.__discovered = 0 self.__test_nodes = [ { 'identifiers': ["FF:FF:FF:01"], 'autoDiscover': False, 'name': 'test_switch_node', 'type': 'switch' }, { 'identifiers': ["FF:FF:FF:02"], 'autoDiscover': False, 'name': 'test_mgmt_node', 'type': 'mgmt' }, { 'identifiers': ["FF:FF:FF:03"], 'autoDiscover': False, 'name': 'test_pdu_node', 'type': 'pdu' }, { 'identifiers': ["FF:FF:FF:04"], 'autoDiscover': False, 'name': 'test_enclosure_node', 'type': 'enclosure' }, { 'identifiers': ["FF:FF:FF:05"], 'autoDiscover': False, 'name': 'test_compute_node', 'type': 'compute' } ] self.__test_tags = { 'tags': ['tag1', 'tag2'] } def __get_data(self): return loads(self.__client.last_response.data) def __get_workflow_status(self, id, query): Api().nodes_get_workflow_by_id(identifier=id, active=query) data = self.__get_data() if len(data) > 0: status = data[0].get('_status') return status return 'not running' def __post_workflow(self, id, graph_name): status = self.__get_workflow_status(id, 'true') if status != 'pending' and status != 'running': Api().nodes_post_workflow_by_id(identifier=id, name=graph_name, body={'name': graph_name}) timeout = 20 while status != 'pending' and status != 'running' and timeout != 0: logs.warning('Workflow status for Node %s (status=%s,timeout=%s)', id, str(status), str(timeout)) status = self.__get_workflow_status(id, 'true') sleep(1) timeout -= 1 return timeout def create_temp_nodes(self): # utility to create a set of test nodes for n in self.__test_nodes: logs.info(' Creating test node (name=%s)', n.get('name')) Api().nodes_post(identifiers=n) rsp = self.__client.last_response if rsp.status != 201: logs.info(' Failed to create test node') # self.assertEqual(201, rsp.status, msg=rsp.reason) def delete_temp_nodes(self): # utility to delete the set of test nodes codes = [] Api().nodes_get_all() nodes = self.__get_data() test_names = [t.get('name') for t in self.__test_nodes] for n in nodes: name = n.get('name') if name in test_names: uuid = n.get('id') logs.info(' Deleting node %s (name=%s)', uuid, name) Api().nodes_del_by_id(identifier=uuid) rsp = self.__client.last_response if rsp.status != 204: codes.append(rsp) logs.info(' Failed to delete node %s - %s', uuid, name) return len(codes) def test_nodes(self): # Testing GET:/api/2.0/nodes found = False Api().nodes_get_all() nodes = self.__get_data() self.assertNotEqual(0, len(nodes), msg='Node list was empty!') logs.debug(json.dumps(nodes, indent=4)) for node in nodes: if node.get('type') == 'compute': logs.info(" Node: %s %s %s", node.get('id'), node.get('type'), node.get('name')) if node.get('sku') and node.get('obms'): found = True self.assertTrue(found, msg='No node with both sku and OBM settingd found!') @depends(after='test_nodes') def test_node_id(self): # Testing GET:/api/2.0/nodes/:id Api().nodes_get_all() nodes = self.__get_data() logs.debug(json.dumps(nodes, indent=4)) codes = [] for n in nodes: logs.info(" Node: %s %s %s", n.get('id'), n.get('type'), n.get('name')) logs.debug(json.dumps(n, indent=4)) if n.get('type') == 'compute': uuid = n.get('id') Api().nodes_get_by_id(identifier=uuid) rsp = self.__client.last_response codes.append(rsp) self.assertNotEqual(0, len(codes), msg='Failed to find compute node Ids') for c in codes: self.assertEqual(200, c.status, msg=c.reason) self.assertRaises(ApiException, Api().nodes_get_by_id, 'fooey') @depends(after='test_node_id') def test_node_create(self): # Testing POST:/api/2.0/nodes/ # This test uses the fake set of nodes __test_nodes for n in self.__test_nodes: logs.info(' Creating node (name=%s)', n.get('name')) Api().nodes_post(identifiers=n) rsp = self.__client.last_response self.assertEqual(201, rsp.status, msg=rsp.reason) @depends(after='test_node_create') def test_node_patch(self): # Testing PATCH:/api/2.0/nodes/:id data = {"name": 'fake_name_test'} Api().nodes_get_all() nodes = self.__get_data() codes = [] for n in nodes: if n.get('name') == 'test_compute_node': uuid = n.get('id') Api().nodes_patch_by_id(identifier=uuid, body=data) rsp = self.__client.last_response test_nodes = self.__get_data() self.assertEqual(test_nodes.get('name'), 'fake_name_test', 'Oops patch failed') codes.append(rsp) logs.info(' Restoring name to "test_compute_node"') correct_data = {"name": 'test_compute_node'} Api().nodes_patch_by_id(identifier=uuid, body=correct_data) rsp = self.__client.last_response restored_nodes = self.__get_data() self.assertEqual(restored_nodes.get('name'), 'test_compute_node', 'Oops restoring failed') codes.append(rsp) self.assertNotEqual(0, len(codes), msg='Failed to find compute node Ids') for c in codes: self.assertEqual(200, c.status, msg=c.reason) self.assertRaises(ApiException, Api().nodes_patch_by_id, 'fooey', data) @depends(after='test_node_patch') def test_node_delete(self): # Testing DELETE:/api/2.0/nodes/:id codes = [] Api().nodes_get_all() nodes = self.__get_data() test_names = [t.get('name') for t in self.__test_nodes] for n in nodes: name = n.get('name') if name in test_names: uuid = n.get('id') logs.info(' Deleting node %s (name=%s)', uuid, name) Api().nodes_del_by_id(identifier=uuid) codes.append(self.__client.last_response) self.assertNotEqual(0, len(codes), msg='Delete node list empty, should contain test nodes!') for c in codes: self.assertEqual(204, c.status, msg=c.reason) self.assertRaises(ApiException, Api().nodes_del_by_id, 'fooey') @depends(after='test_node_delete') def test_node_catalogs(self): # Testing GET:/api/2.0/nodes/:id/catalogs resps = [] Api().nodes_get_all() nodes = self.__get_data() for n in nodes: if n.get('type') == 'compute': Api().nodes_get_catalog_by_id(identifier=n.get('id')) resps.append(self.__get_data()) for resp in resps: self.assertNotEqual(0, len(resp), msg='Node catalog is empty!') self.assertRaises(ApiException, Api().nodes_get_catalog_by_id, 'fooey') @depends(after='test_node_catalogs') def test_node_catalogs_bysource(self): # Testing GET:/api/2.0/nodes/:id/catalogs/source resps = [] Api().nodes_get_all() nodes = self.__get_data() for n in nodes: if n.get('type') == 'compute': Api().nodes_get_catalog_source_by_id(identifier=n.get('id'), source='bmc') resps.append(self.__client.last_response) for resp in resps: self.assertEqual(200, resp.status, msg=resp.reason) self.assertRaises(ApiException, Api().nodes_get_catalog_source_by_id, 'fooey', 'bmc') @depends(after='test_node_catalogs_bysource') def test_node_workflows_get(self): # Testing GET:/api/2.0/nodes/:id/workflows resps = [] Api().nodes_get_all() nodes = self.__get_data() for n in nodes: if n.get('type') == 'compute': Api().nodes_get_workflow_by_id(identifier=n.get('id')) resps.append(self.__get_data()) for resp in resps: self.assertNotEqual(0, len(resp), msg='No Workflows found for Node') @depends(after='test_node_workflows_get') def test_node_tags_patch(self): # Testing PATCH:/api/2.0/nodes/:id/tags codes = [] Api().nodes_get_all() rsp = self.__client.last_response nodes = loads(rsp.data) codes.append(rsp) for n in nodes: logs.info(' node to tag %s', n.get('id')) logs.debug(json.dumps(n, indent=4)) Api().nodes_patch_tag_by_id(identifier=n.get('id'), body=self.__test_tags) logs.info(' Creating tag (name=%s)', self.__test_tags) rsp = self.__client.last_response codes.append(rsp) for c in codes: self.assertEqual(200, c.status, msg=c.reason) self.assertRaises(ApiException, Api().nodes_patch_tag_by_id, 'fooey', body=self.__test_tags) @depends(after='test_node_tags_patch') def test_node_tags_get(self): # Testing GET:api/2.0/nodes/:id/tags codes = [] Api().nodes_get_all() rsp = self.__client.last_response nodes = loads(rsp.data) codes.append(rsp) for n in nodes: Api().nodes_get_tags_by_id(n.get('id')) rsp = self.__client.last_response tags = loads(rsp.data) codes.append(rsp) for t in self.__test_tags.get('tags'): self.assertTrue(t in tags, msg="cannot find new tag") for c in codes: self.assertEqual(200, c.status, msg=c.reason) self.assertRaises(ApiException, Api().nodes_patch_tag_by_id, 'fooey', body=self.__test_tags) @depends(after='test_node_tags_get') def test_node_tags_del(self): # Testing DELETE:api/2.0/nodes/:id/tags/:tagName # This workflow deletes the the tags off the nodes created by # the test above test_node_tags_patch get_codes = [] del_codes = [] Api().nodes_get_all() rsp = self.__client.last_response nodes = loads(rsp.data) get_codes.append(rsp) for n in nodes: for t in self.__test_tags.get('tags'): Api().nodes_del_tag_by_id(identifier=n.get('id'), tag_name=t) rsp = self.__client.last_response del_codes.append(rsp) Api().nodes_get_by_id(identifier=n.get('id')) rsp = self.__client.last_response get_codes.append(rsp) updated_node = loads(rsp.data) for t in self.__test_tags.get('tags'): self.assertTrue(t not in updated_node.get('tags'), msg="Tag " + t + " was not deleted") for c in get_codes: self.assertEqual(200, c.status, msg=c.reason) for c in del_codes: self.assertEqual(204, c.status, msg=c.reason) self.assertRaises(ApiException, Api().nodes_del_tag_by_id, 'fooey', tag_name=['tag']) @depends(after='test_node_tags_del') def test_node_tags_masterDel(self): # Testing DELETE:api/2.0/nodes/tags/:tagName # negative test: This workflow calls the test_node_tags_patch test above to # get tags put back on the nodes, then verifies trying to delete an non-existing # tag id doesn't cause a failure, then it deletes all the tags that were created codes = [] self.test_node_tags_patch() t = 'tag3' logs.info(" Check to make sure invalid tag is not deleted") Api().nodes_master_del_tag_by_id(tag_name=t) rsp = self.__client.last_response codes.append(rsp) logs.info(" Test to check valid tags are deleted") for t in self.__test_tags.get('tags'): Api().nodes_master_del_tag_by_id(tag_name=t) rsp = self.__client.last_response codes.append(rsp) for c in codes: self.assertEqual(204, c.status, msg=c.reason) @depends(after='test_node_tags_masterDel') def test_node_put_obm_by_node_id(self): # Testing PUT:/api/2.0/nodes/:id/obm self.create_temp_nodes() Api().nodes_get_all() rsp = self.__client.last_response nodes = loads(rsp.data) self.assertEqual(200, rsp.status, msg=rsp.status) test_obm = { 'config': { 'host': '1.2.3.4', 'user': 'username', 'password': 'password' }, 'service': 'noop-obm-service' } for n in nodes: if n.get('name') == 'test_compute_node': logs.info(" Node to put obm: %s %s ", n.get('id'), n.get('name')) test_obm["nodeId"] = str(n.get('id')) logs.debug(json.dumps(n, indent=4)) Api().nodes_put_obms_by_node_id(identifier=n.get('id'), body=test_obm) logs.info(' Creating obm: %s ', str(test_obm)) rsp = self.__client.last_response self.assertEqual(201, rsp.status, msg=rsp.status) @depends(after='test_node_put_obm_by_node_id') def test_node_get_obm_by_node_id(self): # Testing GET:/api/2.0/:id/obm Api().nodes_get_all() rsp = self.__client.last_response nodes = loads(rsp.data) self.assertEqual(200, rsp.status, msg=rsp.status) for n in nodes: if n.get('name') == 'test_compute_node': logs.debug(json.dumps(n, indent=4)) Api().nodes_get_obms_by_node_id(identifier=n.get('id')) logs.info(' getting OBMs for node: %s', n.get('id')) rsp = self.__client.last_response self.assertEqual(200, rsp.status, msg=rsp.status) obms = loads(rsp.data) self.assertNotEqual(0, len(obms), msg='OBMs list was empty!') for obm in obms: id = obm.get('id') Api().obms_delete_by_id(identifier=id) rsp = self.__client.last_response self.assertEqual(204, rsp.status, msg=rsp.status) @depends(after='test_node_get_obm_by_node_id') def test_node_put_obm_invalid_node_id(self): # Testing that PUT:/api/2.0/:id/obm returns 404 with invalid node ID found_node = False Api().nodes_get_all() rsp = self.__client.last_response nodes = loads(rsp.data) self.assertEqual(200, rsp.status, msg=rsp.status) test_obm = { 'config': { 'host': '1.2.3.4', 'user': 'username', 'password': 'password' }, 'service': 'noop-obm-service' } # get the first test compute node id, to get a 404, we need the payload data set up # with a valid node id. Otherwise, a 400 will be returned if bad payload. for n in nodes: if n.get('name') == 'test_compute_node': test_obm["nodeId"] = str(n.get('id')) found_node = True break if found_node: try: Api().nodes_put_obms_by_node_id(identifier='invalid_ID', body=test_obm) self.fail(msg='did not raise exception') except ApiException as e: self.assertEqual(404, e.status, msg='unexpected response {0}, expected 404'.format(e.status)) else: self.fail(msg='No test compute node available for try invalid_ID') @depends(after='test_node_put_obm_invalid_node_id') def test_node_get_obm_invalid_node_id(self): # Testing that PUT:/api/2.0/:id/obm returns 404 with invalid node ID try: Api().nodes_get_obms_by_node_id(identifier='invalid_ID') self.fail(msg='did not raise exception') except ApiException as e: self.assertEqual(404, e.status, msg='unexpected response {0}, expected 404'.format(e.status)) @depends(after='test_node_get_obm_invalid_node_id') def test_clean_up_test_nodes(self): # Clean up the added test nodes self.assertEqual(0, self.delete_temp_nodes(), msg="Failed to clean up test nodes from script") @classmethod def clear_nodes(self): # """ Clear the temp created nodes if any exist """ Api().nodes_get_all() nodes = loads(self._cls_client.last_response.data) for n in nodes: name = n.get('name') if "test_" in name: uuid = n.get('id') logs.info(' Deleting node %s (name=%s)', uuid, name) Api().nodes_del_by_id(identifier=uuid) rsp = self._cls_client.last_response if rsp.status != 204: logs.info(' Failed to delete test node %s - %s', uuid, name)
apache-2.0
openstack/sahara
sahara/service/validations/node_group_templates.py
2
3936
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from sahara import exceptions as ex from sahara.i18n import _ from sahara.service.api import v10 as api import sahara.service.validations.base as b from sahara.service.validations import shares def check_node_group_template_create(data, **kwargs): plugin_version = 'hadoop_version' if data.get('plugin_version'): plugin_version = 'plugin_version' b.check_node_group_template_unique_name(data['name']) b.check_plugin_name_exists(data['plugin_name']) b.check_plugin_supports_version(data['plugin_name'], data[plugin_version]) b.check_node_group_basic_fields(data['plugin_name'], data[plugin_version], data) if data.get('image_id'): b.check_image_registered(data['image_id']) b.check_required_image_tags(data['plugin_name'], data[plugin_version], data['image_id']) if data.get('shares'): shares.check_shares(data['shares']) def check_node_group_template_usage(node_group_template_id, **kwargs): cluster_users = [] template_users = [] for cluster in api.get_clusters(): if (node_group_template_id in [node_group.node_group_template_id for node_group in cluster.node_groups]): cluster_users += [cluster.name] for cluster_template in api.get_cluster_templates(): if (node_group_template_id in [node_group.node_group_template_id for node_group in cluster_template.node_groups]): template_users += [cluster_template.name] if cluster_users or template_users: raise ex.InvalidReferenceException( _("Node group template %(template)s is in use by " "cluster templates: %(users)s; and clusters: %(clusters)s") % {'template': node_group_template_id, 'users': template_users and ', '.join(template_users) or 'N/A', 'clusters': cluster_users and ', '.join(cluster_users) or 'N/A'}) def check_node_group_template_update(node_group_template_id, data, **kwargs): plugin_version = 'hadoop_version' if data.get('plugin_version'): plugin_version = 'plugin_version' if data.get('plugin_name') and not data.get(plugin_version): raise ex.InvalidReferenceException( _("You must specify a %s value " "for your plugin_name") % plugin_version) if data.get('plugin_name'): plugin = data.get('plugin_name') version = data.get(plugin_version) b.check_plugin_name_exists(plugin) b.check_plugin_supports_version(plugin, version) else: ngt = api.get_node_group_template(node_group_template_id) plugin = ngt.plugin_name if data.get(plugin_version): version = data.get(plugin_version) b.check_plugin_supports_version(plugin, version) else: version = ngt.hadoop_version if data.get('image_id'): b.check_image_registered(data['image_id']) b.check_required_image_tags(plugin, version, data['image_id']) b.check_node_group_basic_fields(plugin, version, data) if data.get('shares'): shares.check_shares(data['shares'])
apache-2.0
gaocegege/Processing.R
hack/migrate-from-ppy.py
1
5211
import click import os from defusedxml import ElementTree as etree import jinja2 property_file_name = '.property.yml' property_template_dir = 'hack/templates' property_template_file_name = 'property_template.jinja' class Migrator(object): def __init__(self, input_dir, output_dir): self.input_dir = input_dir self.output_dir = output_dir def migrate(self): for filename in os.listdir(self.input_dir): self.migrateItem(filename) def migrateItem(self, filename): prefix = filename[:-4] item_dir = os.path.join(self.output_dir, prefix) xml_file = os.path.join(self.input_dir, filename) if os.path.exists(item_dir) is False: os.makedirs(item_dir) # Write config to file tree = etree.parse(xml_file) with open(os.path.join(item_dir, property_file_name), 'w+') as f: f.write(self.render(tree)) def render(self, tree): property_template = jinja2.Environment( autoescape=True, loader=jinja2.FileSystemLoader( property_template_dir), trim_blocks='true')\ .get_template(property_template_file_name) subcategory = '' if tree.find('subcategory') is not None: subcategory = self.get_element_text(tree.find('subcategory')) description = '' if tree.find('description') is not None: description = self.get_element_text(tree.find('description')).replace('"', '\\"') syntax = '' if tree.find('syntax') is not None: syntax = etree.tostring(tree.find('syntax'))[9:-12].decode("utf-8")\ .replace('"', '\\"').replace('\n', '\\n') print(str(syntax)) parameters = [] for parameter in tree.iterfind('parameter'): label = self.get_element_text(parameter.find('label')) param_description = '' if parameter.find('description') is not None: param_description = self.get_element_text(parameter.find('description'))\ .replace('"', '\\"').replace('\n', ' ') parameters.append({'label':label, 'description':param_description}) # TODO: Support method methods = [] for method in tree.iterfind('method'): label = self.get_element_text(method.find('label')) param_description = method.find('description') # ref = create_ref_link(self.get_element_text(method.find('ref'))) # self.methods.append({'label':label, 'description':param_description, 'ref':ref}) constructors = [] for constructor in tree.iterfind('constructor'): constructors.append(self.get_element_text(constructor)) relateds = [] for related in tree.iterfind('related'): relateds.append(self.get_element_text(related)) item = { 'category': self.get_element_text(tree.find('category')), 'subcategory': subcategory, 'description': description, 'syntax': syntax, 'parameters': parameters, 'methods': methods, 'constructors': constructors, 'related': relateds # 'category': self.get_element_text(tree.find('category')), # 'category': self.get_element_text(tree.find('category')), # 'category': self.get_element_text(tree.find('category')), # 'category': self.get_element_text(tree.find('category')), # 'category': self.get_element_text(tree.find('category')) } return property_template.render(item=item) def get_element_text(self, element): '''Get element.text, supplying the empty string if element.text is None. Take filename so we can point to errors.''' text = element.text if text is None: print("Warning: Element '{}' has no text".format(element.tag)) text = '' return text @click.command() @click.option('--core', default='', help='The location of Processing.R source code.') @click.option('--py-docs-dir', default='', help='The location of Processing.py reference') def migrate(core, py_docs_dir): '''Migrate From Processing.py to Processing.R web reference.''' # BUG: Fail to exit. if core is None or py_docs_dir is None: click.echo('There is no core or py_docs_dir.') exit(1) click.echo('The location of Processing.R source code: %s' % core) click.echo('The location of Processing.py reference: %s' % py_docs_dir) output_dir_short = 'examples/reference' output_dir = os.path.join(core, output_dir_short) input_dir_short = 'Reference/api_en' input_dir = os.path.join(py_docs_dir, input_dir_short) migrator = Migrator(input_dir, output_dir) migrator.migrate() def convert_hypertext(element): text = element.text if hasattr(element, 'text') and element.text else '' for child in element: convert_hypertext(child) # We don't just do this at the top level because we need to skip the top-level tags s = child if s: text += s return text if __name__ == '__main__': migrate()
gpl-3.0
sunze/py_flask
venv/lib/python3.4/site-packages/alembic/testing/plugin/plugin_base.py
8
17365
# plugin/plugin_base.py # Copyright (C) 2005-2014 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 """Testing extensions. this module is designed to work as a testing-framework-agnostic library, so that we can continue to support nose and also begin adding new functionality via py.test. NOTE: copied/adapted from SQLAlchemy master for backwards compatibility; this should be removable when Alembic targets SQLAlchemy 1.0.0 """ from __future__ import absolute_import try: # unitttest has a SkipTest also but pytest doesn't # honor it unless nose is imported too... from nose import SkipTest except ImportError: from _pytest.runner import Skipped as SkipTest import sys import re py3k = sys.version_info >= (3, 0) if py3k: import configparser else: import ConfigParser as configparser # late imports fixtures = None engines = None provision = None exclusions = None warnings = None assertions = None requirements = None config = None util = None file_config = None logging = None db_opts = {} include_tags = set() exclude_tags = set() options = None def setup_options(make_option): make_option("--log-info", action="callback", type="string", callback=_log, help="turn on info logging for <LOG> (multiple OK)") make_option("--log-debug", action="callback", type="string", callback=_log, help="turn on debug logging for <LOG> (multiple OK)") make_option("--db", action="append", type="string", dest="db", help="Use prefab database uri. Multiple OK, " "first one is run by default.") make_option('--dbs', action='callback', callback=_list_dbs, help="List available prefab dbs") make_option("--dburi", action="append", type="string", dest="dburi", help="Database uri. Multiple OK, " "first one is run by default.") make_option("--dropfirst", action="store_true", dest="dropfirst", help="Drop all tables in the target database first") make_option("--backend-only", action="store_true", dest="backend_only", help="Run only tests marked with __backend__") make_option("--mockpool", action="store_true", dest="mockpool", help="Use mock pool (asserts only one connection used)") make_option("--low-connections", action="store_true", dest="low_connections", help="Use a low number of distinct connections - " "i.e. for Oracle TNS") make_option("--reversetop", action="store_true", dest="reversetop", default=False, help="Use a random-ordering set implementation in the ORM " "(helps reveal dependency issues)") make_option("--requirements", action="callback", type="string", callback=_requirements_opt, help="requirements class for testing, overrides setup.cfg") make_option("--with-cdecimal", action="store_true", dest="cdecimal", default=False, help="Monkeypatch the cdecimal library into Python 'decimal' " "for all tests") make_option("--include-tag", action="callback", callback=_include_tag, type="string", help="Include tests with tag <tag>") make_option("--exclude-tag", action="callback", callback=_exclude_tag, type="string", help="Exclude tests with tag <tag>") make_option("--serverside", action="store_true", help="Turn on server side cursors for PG") make_option("--mysql-engine", action="store", dest="mysql_engine", default=None, help="Use the specified MySQL storage engine for all tables, " "default is a db-default/InnoDB combo.") def configure_follower(follower_ident): """Configure required state for a follower. This invokes in the parent process and typically includes database creation. """ from alembic.testing import provision provision.FOLLOWER_IDENT = follower_ident def memoize_important_follower_config(dict_): """Store important configuration we will need to send to a follower. This invokes in the parent process after normal config is set up. This is necessary as py.test seems to not be using forking, so we start with nothing in memory, *but* it isn't running our argparse callables, so we have to just copy all of that over. """ dict_['memoized_config'] = { 'db_opts': db_opts, 'include_tags': include_tags, 'exclude_tags': exclude_tags } def restore_important_follower_config(dict_): """Restore important configuration needed by a follower. This invokes in the follower process. """ global db_opts, include_tags, exclude_tags db_opts.update(dict_['memoized_config']['db_opts']) include_tags.update(dict_['memoized_config']['include_tags']) exclude_tags.update(dict_['memoized_config']['exclude_tags']) def read_config(): global file_config file_config = configparser.ConfigParser() file_config.read(['setup.cfg', 'test.cfg']) def pre_begin(opt): """things to set up early, before coverage might be setup.""" global options options = opt for fn in pre_configure: fn(options, file_config) def set_coverage_flag(value): options.has_coverage = value def post_begin(): """things to set up later, once we know coverage is running.""" # Lazy setup of other options (post coverage) for fn in post_configure: fn(options, file_config) # late imports, has to happen after config as well # as nose plugins like coverage global util, fixtures, engines, exclusions, \ assertions, warnings, profiling,\ config, testing from alembic.testing import config, warnings, exclusions # noqa from alembic.testing import engines, fixtures # noqa from sqlalchemy import util # noqa warnings.setup_filters() def _log(opt_str, value, parser): global logging if not logging: import logging logging.basicConfig() if opt_str.endswith('-info'): logging.getLogger(value).setLevel(logging.INFO) elif opt_str.endswith('-debug'): logging.getLogger(value).setLevel(logging.DEBUG) def _list_dbs(*args): print("Available --db options (use --dburi to override)") for macro in sorted(file_config.options('db')): print("%20s\t%s" % (macro, file_config.get('db', macro))) sys.exit(0) def _requirements_opt(opt_str, value, parser): _setup_requirements(value) def _exclude_tag(opt_str, value, parser): exclude_tags.add(value.replace('-', '_')) def _include_tag(opt_str, value, parser): include_tags.add(value.replace('-', '_')) pre_configure = [] post_configure = [] def pre(fn): pre_configure.append(fn) return fn def post(fn): post_configure.append(fn) return fn @pre def _setup_options(opt, file_config): global options options = opt @pre def _server_side_cursors(options, file_config): if options.serverside: db_opts['server_side_cursors'] = True @pre def _monkeypatch_cdecimal(options, file_config): if options.cdecimal: import cdecimal sys.modules['decimal'] = cdecimal @post def _engine_uri(options, file_config): from alembic.testing import config from alembic.testing import provision if options.dburi: db_urls = list(options.dburi) else: db_urls = [] if options.db: for db_token in options.db: for db in re.split(r'[,\s]+', db_token): if db not in file_config.options('db'): raise RuntimeError( "Unknown URI specifier '%s'. " "Specify --dbs for known uris." % db) else: db_urls.append(file_config.get('db', db)) if not db_urls: db_urls.append(file_config.get('db', 'default')) for db_url in db_urls: cfg = provision.setup_config( db_url, db_opts, options, file_config, provision.FOLLOWER_IDENT) if not config._current: cfg.set_as_current(cfg) @post def _engine_pool(options, file_config): if options.mockpool: from sqlalchemy import pool db_opts['poolclass'] = pool.AssertionPool @post def _requirements(options, file_config): requirement_cls = file_config.get('sqla_testing', "requirement_cls") _setup_requirements(requirement_cls) def _setup_requirements(argument): from alembic.testing import config if config.requirements is not None: return modname, clsname = argument.split(":") # importlib.import_module() only introduced in 2.7, a little # late mod = __import__(modname) for component in modname.split(".")[1:]: mod = getattr(mod, component) req_cls = getattr(mod, clsname) config.requirements = req_cls() @post def _prep_testing_database(options, file_config): from alembic.testing import config from alembic.testing.exclusions import against from sqlalchemy import schema from alembic import util if util.sqla_08: from sqlalchemy import inspect else: from sqlalchemy.engine.reflection import Inspector inspect = Inspector.from_engine if options.dropfirst: for cfg in config.Config.all_configs(): e = cfg.db inspector = inspect(e) try: view_names = inspector.get_view_names() except NotImplementedError: pass else: for vname in view_names: e.execute(schema._DropView( schema.Table(vname, schema.MetaData()) )) if config.requirements.schemas.enabled_for_config(cfg): try: view_names = inspector.get_view_names( schema="test_schema") except NotImplementedError: pass else: for vname in view_names: e.execute(schema._DropView( schema.Table(vname, schema.MetaData(), schema="test_schema") )) for tname in reversed(inspector.get_table_names( order_by="foreign_key")): e.execute(schema.DropTable( schema.Table(tname, schema.MetaData()) )) if config.requirements.schemas.enabled_for_config(cfg): for tname in reversed(inspector.get_table_names( order_by="foreign_key", schema="test_schema")): e.execute(schema.DropTable( schema.Table(tname, schema.MetaData(), schema="test_schema") )) if against(cfg, "postgresql") and util.sqla_100: from sqlalchemy.dialects import postgresql for enum in inspector.get_enums("*"): e.execute(postgresql.DropEnumType( postgresql.ENUM( name=enum['name'], schema=enum['schema']))) @post def _reverse_topological(options, file_config): if options.reversetop: from sqlalchemy.orm.util import randomize_unitofwork randomize_unitofwork() @post def _post_setup_options(opt, file_config): from alembic.testing import config config.options = options config.file_config = file_config def want_class(cls): if not issubclass(cls, fixtures.TestBase): return False elif cls.__name__.startswith('_'): return False elif config.options.backend_only and not getattr(cls, '__backend__', False): return False else: return True def want_method(cls, fn): if not fn.__name__.startswith("test_"): return False elif fn.__module__ is None: return False elif include_tags: return ( hasattr(cls, '__tags__') and exclusions.tags(cls.__tags__).include_test( include_tags, exclude_tags) ) or ( hasattr(fn, '_sa_exclusion_extend') and fn._sa_exclusion_extend.include_test( include_tags, exclude_tags) ) elif exclude_tags and hasattr(cls, '__tags__'): return exclusions.tags(cls.__tags__).include_test( include_tags, exclude_tags) elif exclude_tags and hasattr(fn, '_sa_exclusion_extend'): return fn._sa_exclusion_extend.include_test(include_tags, exclude_tags) else: return True def generate_sub_tests(cls, module): if getattr(cls, '__backend__', False): for cfg in _possible_configs_for_cls(cls): name = "%s_%s_%s" % (cls.__name__, cfg.db.name, cfg.db.driver) subcls = type( name, (cls, ), { "__only_on__": ("%s+%s" % (cfg.db.name, cfg.db.driver)), } ) setattr(module, name, subcls) yield subcls else: yield cls def start_test_class(cls): _do_skips(cls) _setup_engine(cls) def stop_test_class(cls): #from sqlalchemy import inspect #assert not inspect(testing.db).get_table_names() _restore_engine() def _restore_engine(): config._current.reset() def _setup_engine(cls): if getattr(cls, '__engine_options__', None): eng = engines.testing_engine(options=cls.__engine_options__) config._current.push_engine(eng) def before_test(test, test_module_name, test_class, test_name): pass def after_test(test): pass def _possible_configs_for_cls(cls, reasons=None): all_configs = set(config.Config.all_configs()) if cls.__unsupported_on__: spec = exclusions.db_spec(*cls.__unsupported_on__) for config_obj in list(all_configs): if spec(config_obj): all_configs.remove(config_obj) if getattr(cls, '__only_on__', None): spec = exclusions.db_spec(*util.to_list(cls.__only_on__)) for config_obj in list(all_configs): if not spec(config_obj): all_configs.remove(config_obj) if hasattr(cls, '__requires__'): requirements = config.requirements for config_obj in list(all_configs): for requirement in cls.__requires__: check = getattr(requirements, requirement) skip_reasons = check.matching_config_reasons(config_obj) if skip_reasons: all_configs.remove(config_obj) if reasons is not None: reasons.extend(skip_reasons) break if hasattr(cls, '__prefer_requires__'): non_preferred = set() requirements = config.requirements for config_obj in list(all_configs): for requirement in cls.__prefer_requires__: check = getattr(requirements, requirement) if not check.enabled_for_config(config_obj): non_preferred.add(config_obj) if all_configs.difference(non_preferred): all_configs.difference_update(non_preferred) return all_configs def _do_skips(cls): reasons = [] all_configs = _possible_configs_for_cls(cls, reasons) if getattr(cls, '__skip_if__', False): for c in getattr(cls, '__skip_if__'): if c(): raise SkipTest("'%s' skipped by %s" % ( cls.__name__, c.__name__) ) if not all_configs: if getattr(cls, '__backend__', False): msg = "'%s' unsupported for implementation '%s'" % ( cls.__name__, cls.__only_on__) else: msg = "'%s' unsupported on any DB implementation %s%s" % ( cls.__name__, ", ".join( "'%s(%s)+%s'" % ( config_obj.db.name, ".".join( str(dig) for dig in config_obj.db.dialect.server_version_info), config_obj.db.driver ) for config_obj in config.Config.all_configs() ), ", ".join(reasons) ) raise SkipTest(msg) elif hasattr(cls, '__prefer_backends__'): non_preferred = set() spec = exclusions.db_spec(*util.to_list(cls.__prefer_backends__)) for config_obj in all_configs: if not spec(config_obj): non_preferred.add(config_obj) if all_configs.difference(non_preferred): all_configs.difference_update(non_preferred) if config._current not in all_configs: _setup_config(all_configs.pop(), cls) def _setup_config(config_obj, ctx): config._current.push(config_obj)
mit
SimtterCom/gyp
test/rules/gyptest-default.py
25
1660
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies simple rules when using an explicit build target of 'all'. """ import TestGyp test = TestGyp.TestGyp() test.run_gyp('actions.gyp', chdir='src') test.relocate('src', 'relocate/src') test.build('actions.gyp', chdir='relocate/src') expect = """\ Hello from program.c Hello from function1.in Hello from function2.in """ if test.format == 'xcode': chdir = 'relocate/src/subdir1' else: chdir = 'relocate/src' test.run_built_executable('program', chdir=chdir, stdout=expect) expect = """\ Hello from program.c Hello from function3.in """ if test.format == 'xcode': chdir = 'relocate/src/subdir3' else: chdir = 'relocate/src' test.run_built_executable('program2', chdir=chdir, stdout=expect) test.must_match('relocate/src/subdir2/file1.out', 'Hello from file1.in\n') test.must_match('relocate/src/subdir2/file2.out', 'Hello from file2.in\n') test.must_match('relocate/src/subdir2/file1.out2', 'Hello from file1.in\n') test.must_match('relocate/src/subdir2/file2.out2', 'Hello from file2.in\n') test.must_match('relocate/src/subdir2/file1.out4', 'Hello from file1.in\n') test.must_match('relocate/src/subdir2/file2.out4', 'Hello from file2.in\n') test.must_match('relocate/src/subdir2/file1.copy', 'Hello from file1.in\n') test.must_match('relocate/src/external/file1.external_rules.out', 'Hello from file1.in\n') test.must_match('relocate/src/external/file2.external_rules.out', 'Hello from file2.in\n') test.pass_test()
bsd-3-clause
XiaosongWei/chromium-crosswalk
tools/telemetry/telemetry/internal/story_runner_unittest.py
9
24824
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import StringIO import sys import unittest from catapult_base import cloud_storage from telemetry import benchmark from telemetry.core import exceptions from telemetry.core import util from telemetry import decorators from telemetry.internal.results import results_options from telemetry.internal import story_runner from telemetry.internal.util import exception_formatter as ex_formatter_module from telemetry.page import page as page_module from telemetry.page import page_test from telemetry import story as story_module from telemetry.testing import options_for_unittests from telemetry.testing import system_stub import mock from telemetry.value import improvement_direction from telemetry.value import list_of_scalar_values from telemetry.value import scalar from telemetry.value import summary as summary_module from telemetry.web_perf import story_test from telemetry.web_perf import timeline_based_measurement from telemetry.wpr import archive_info # This linter complains if we define classes nested inside functions. # pylint: disable=bad-super-call class FakePlatform(object): def CanMonitorThermalThrottling(self): return False class TestSharedState(story_module.SharedState): _platform = FakePlatform() @classmethod def SetTestPlatform(cls, platform): cls._platform = platform def __init__(self, test, options, story_set): super(TestSharedState, self).__init__( test, options, story_set) self._test = test self._current_story = None @property def platform(self): return self._platform def WillRunStory(self, story): self._current_story = story def CanRunStory(self, story): return True def RunStory(self, results): raise NotImplementedError def DidRunStory(self, results): pass def TearDownState(self): pass class TestSharedPageState(TestSharedState): def RunStory(self, results): self._test.RunPage(self._current_story, None, results) class FooStoryState(TestSharedPageState): pass class BarStoryState(TestSharedPageState): pass class DummyTest(page_test.PageTest): def RunPage(self, *_): pass def ValidateAndMeasurePage(self, page, tab, results): pass class EmptyMetadataForTest(benchmark.BenchmarkMetadata): def __init__(self): super(EmptyMetadataForTest, self).__init__('') class DummyLocalStory(story_module.Story): def __init__(self, shared_state_class, name=''): super(DummyLocalStory, self).__init__( shared_state_class, name=name) def Run(self, shared_state): pass @property def is_local(self): return True class MixedStateStorySet(story_module.StorySet): @property def allow_mixed_story_states(self): return True def SetupStorySet(allow_multiple_story_states, story_state_list): if allow_multiple_story_states: story_set = MixedStateStorySet() else: story_set = story_module.StorySet() for story_state in story_state_list: story_set.AddStory(DummyLocalStory(story_state)) return story_set def _GetOptionForUnittest(): options = options_for_unittests.GetCopy() options.output_formats = ['none'] options.suppress_gtest_report = False parser = options.CreateParser() story_runner.AddCommandLineArgs(parser) options.MergeDefaultValues(parser.get_default_values()) story_runner.ProcessCommandLineArgs(parser, options) return options class FakeExceptionFormatterModule(object): @staticmethod def PrintFormattedException( exception_class=None, exception=None, tb=None, msg=None): pass def GetNumberOfSuccessfulPageRuns(results): return len([run for run in results.all_page_runs if run.ok or run.skipped]) class TestOnlyException(Exception): pass class StoryRunnerTest(unittest.TestCase): def setUp(self): self.fake_stdout = StringIO.StringIO() self.actual_stdout = sys.stdout sys.stdout = self.fake_stdout self.options = _GetOptionForUnittest() self.results = results_options.CreateResults( EmptyMetadataForTest(), self.options) self._story_runner_logging_stub = None def SuppressExceptionFormatting(self): """Fake out exception formatter to avoid spamming the unittest stdout.""" story_runner.exception_formatter = FakeExceptionFormatterModule self._story_runner_logging_stub = system_stub.Override( story_runner, ['logging']) def RestoreExceptionFormatter(self): story_runner.exception_formatter = ex_formatter_module if self._story_runner_logging_stub: self._story_runner_logging_stub.Restore() self._story_runner_logging_stub = None def tearDown(self): sys.stdout = self.actual_stdout self.RestoreExceptionFormatter() def testStoriesGroupedByStateClass(self): foo_states = [FooStoryState, FooStoryState, FooStoryState, FooStoryState, FooStoryState] mixed_states = [FooStoryState, FooStoryState, FooStoryState, BarStoryState, FooStoryState] # StorySet's are only allowed to have one SharedState. story_set = SetupStorySet(False, foo_states) story_groups = ( story_runner.StoriesGroupedByStateClass( story_set, False)) self.assertEqual(len(story_groups), 1) story_set = SetupStorySet(False, mixed_states) self.assertRaises( ValueError, story_runner.StoriesGroupedByStateClass, story_set, False) # BaseStorySets are allowed to have multiple SharedStates. mixed_story_set = SetupStorySet(True, mixed_states) story_groups = ( story_runner.StoriesGroupedByStateClass( mixed_story_set, True)) self.assertEqual(len(story_groups), 3) self.assertEqual(story_groups[0].shared_state_class, FooStoryState) self.assertEqual(story_groups[1].shared_state_class, BarStoryState) self.assertEqual(story_groups[2].shared_state_class, FooStoryState) def RunStoryTest(self, s, expected_successes): test = DummyTest() story_runner.Run( test, s, self.options, self.results) self.assertEquals(0, len(self.results.failures)) self.assertEquals(expected_successes, GetNumberOfSuccessfulPageRuns(self.results)) def testStoryTest(self): all_foo = [FooStoryState, FooStoryState, FooStoryState] one_bar = [FooStoryState, FooStoryState, BarStoryState] story_set = SetupStorySet(True, one_bar) self.RunStoryTest(story_set, 3) story_set = SetupStorySet(True, all_foo) self.RunStoryTest(story_set, 6) story_set = SetupStorySet(False, all_foo) self.RunStoryTest(story_set, 9) story_set = SetupStorySet(False, one_bar) test = DummyTest() self.assertRaises(ValueError, story_runner.Run, test, story_set, self.options, self.results) def testSuccessfulTimelineBasedMeasurementTest(self): """Check that PageTest is not required for story_runner.Run. Any PageTest related calls or attributes need to only be called for PageTest tests. """ class TestSharedTbmState(TestSharedState): def RunStory(self, results): pass TEST_WILL_RUN_STORY = 'test.WillRunStory' TEST_MEASURE = 'test.Measure' TEST_DID_RUN_STORY = 'test.DidRunStory' EXPECTED_CALLS_IN_ORDER = [TEST_WILL_RUN_STORY, TEST_MEASURE, TEST_DID_RUN_STORY] test = timeline_based_measurement.TimelineBasedMeasurement( timeline_based_measurement.Options()) manager = mock.MagicMock() test.WillRunStory = mock.MagicMock() test.Measure = mock.MagicMock() test.DidRunStory = mock.MagicMock() manager.attach_mock(test.WillRunStory, TEST_WILL_RUN_STORY) manager.attach_mock(test.Measure, TEST_MEASURE) manager.attach_mock(test.DidRunStory, TEST_DID_RUN_STORY) story_set = story_module.StorySet() story_set.AddStory(DummyLocalStory(TestSharedTbmState)) story_set.AddStory(DummyLocalStory(TestSharedTbmState)) story_set.AddStory(DummyLocalStory(TestSharedTbmState)) story_runner.Run( test, story_set, self.options, self.results) self.assertEquals(0, len(self.results.failures)) self.assertEquals(3, GetNumberOfSuccessfulPageRuns(self.results)) self.assertEquals(3*EXPECTED_CALLS_IN_ORDER, [call[0] for call in manager.mock_calls]) def testCallOrderBetweenStoryTestAndSharedState(self): """Check that the call order between StoryTest and SharedState is correct. """ TEST_WILL_RUN_STORY = 'test.WillRunStory' TEST_MEASURE = 'test.Measure' TEST_DID_RUN_STORY = 'test.DidRunStory' STATE_WILL_RUN_STORY = 'state.WillRunStory' STATE_RUN_STORY = 'state.RunStory' STATE_DID_RUN_STORY = 'state.DidRunStory' EXPECTED_CALLS_IN_ORDER = [TEST_WILL_RUN_STORY, STATE_WILL_RUN_STORY, STATE_RUN_STORY, TEST_MEASURE, STATE_DID_RUN_STORY, TEST_DID_RUN_STORY] class TestStoryTest(story_test.StoryTest): def WillRunStory(self, platform): pass def Measure(self, platform, results): pass def DidRunStory(self, platform): pass class TestSharedStateForStoryTest(TestSharedState): def RunStory(self, results): pass @mock.patch.object(TestStoryTest, 'WillRunStory') @mock.patch.object(TestStoryTest, 'Measure') @mock.patch.object(TestStoryTest, 'DidRunStory') @mock.patch.object(TestSharedStateForStoryTest, 'WillRunStory') @mock.patch.object(TestSharedStateForStoryTest, 'RunStory') @mock.patch.object(TestSharedStateForStoryTest, 'DidRunStory') def GetCallsInOrder(state_DidRunStory, state_RunStory, state_WillRunStory, test_DidRunStory, test_Measure, test_WillRunStory): manager = mock.MagicMock() manager.attach_mock(test_WillRunStory, TEST_WILL_RUN_STORY) manager.attach_mock(test_Measure, TEST_MEASURE) manager.attach_mock(test_DidRunStory, TEST_DID_RUN_STORY) manager.attach_mock(state_WillRunStory, STATE_WILL_RUN_STORY) manager.attach_mock(state_RunStory, STATE_RUN_STORY) manager.attach_mock(state_DidRunStory, STATE_DID_RUN_STORY) test = TestStoryTest() story_set = story_module.StorySet() story_set.AddStory(DummyLocalStory(TestSharedStateForStoryTest)) story_runner.Run(test, story_set, self.options, self.results) return [call[0] for call in manager.mock_calls] calls_in_order = GetCallsInOrder() # pylint: disable=no-value-for-parameter self.assertEquals(EXPECTED_CALLS_IN_ORDER, calls_in_order) def testTearDownIsCalledOnceForEachStoryGroupWithPageSetRepeat(self): self.options.pageset_repeat = 3 fooz_init_call_counter = [0] fooz_tear_down_call_counter = [0] barz_init_call_counter = [0] barz_tear_down_call_counter = [0] class FoozStoryState(FooStoryState): def __init__(self, test, options, storyz): super(FoozStoryState, self).__init__( test, options, storyz) fooz_init_call_counter[0] += 1 def TearDownState(self): fooz_tear_down_call_counter[0] += 1 class BarzStoryState(BarStoryState): def __init__(self, test, options, storyz): super(BarzStoryState, self).__init__( test, options, storyz) barz_init_call_counter[0] += 1 def TearDownState(self): barz_tear_down_call_counter[0] += 1 def AssertAndCleanUpFoo(): self.assertEquals(1, fooz_init_call_counter[0]) self.assertEquals(1, fooz_tear_down_call_counter[0]) fooz_init_call_counter[0] = 0 fooz_tear_down_call_counter[0] = 0 story_set1_list = [FoozStoryState, FoozStoryState, FoozStoryState, BarzStoryState, BarzStoryState] story_set1 = SetupStorySet(True, story_set1_list) self.RunStoryTest(story_set1, 15) AssertAndCleanUpFoo() self.assertEquals(1, barz_init_call_counter[0]) self.assertEquals(1, barz_tear_down_call_counter[0]) barz_init_call_counter[0] = 0 barz_tear_down_call_counter[0] = 0 story_set2_list = [FoozStoryState, FoozStoryState, FoozStoryState, FoozStoryState] story_set2 = SetupStorySet(False, story_set2_list) self.RunStoryTest(story_set2, 27) AssertAndCleanUpFoo() self.assertEquals(0, barz_init_call_counter[0]) self.assertEquals(0, barz_tear_down_call_counter[0]) def testAppCrashExceptionCausesFailureValue(self): self.SuppressExceptionFormatting() story_set = story_module.StorySet() class SharedStoryThatCausesAppCrash(TestSharedPageState): def WillRunStory(self, story): raise exceptions.AppCrashException(msg='App Foo crashes') story_set.AddStory(DummyLocalStory( SharedStoryThatCausesAppCrash)) story_runner.Run( DummyTest(), story_set, self.options, self.results) self.assertEquals(1, len(self.results.failures)) self.assertEquals(0, GetNumberOfSuccessfulPageRuns(self.results)) self.assertIn('App Foo crashes', self.fake_stdout.getvalue()) def testExceptionRaisedInSharedStateTearDown(self): self.SuppressExceptionFormatting() story_set = story_module.StorySet() class SharedStoryThatCausesAppCrash(TestSharedPageState): def TearDownState(self): raise TestOnlyException() story_set.AddStory(DummyLocalStory( SharedStoryThatCausesAppCrash)) with self.assertRaises(TestOnlyException): story_runner.Run( DummyTest(), story_set, self.options, self.results) def testUnknownExceptionIsFatal(self): self.SuppressExceptionFormatting() story_set = story_module.StorySet() class UnknownException(Exception): pass # This erroneous test is set up to raise exception for the 2nd story # run. class Test(page_test.PageTest): def __init__(self, *args): super(Test, self).__init__(*args) self.run_count = 0 def RunPage(self, *_): old_run_count = self.run_count self.run_count += 1 if old_run_count == 1: raise UnknownException('FooBarzException') def ValidateAndMeasurePage(self, page, tab, results): pass s1 = DummyLocalStory(TestSharedPageState) s2 = DummyLocalStory(TestSharedPageState) story_set.AddStory(s1) story_set.AddStory(s2) test = Test() with self.assertRaises(UnknownException): story_runner.Run( test, story_set, self.options, self.results) self.assertEqual(set([s2]), self.results.pages_that_failed) self.assertEqual(set([s1]), self.results.pages_that_succeeded) self.assertIn('FooBarzException', self.fake_stdout.getvalue()) def testRaiseBrowserGoneExceptionFromRunPage(self): self.SuppressExceptionFormatting() story_set = story_module.StorySet() class Test(page_test.PageTest): def __init__(self, *args): super(Test, self).__init__(*args) self.run_count = 0 def RunPage(self, *_): old_run_count = self.run_count self.run_count += 1 if old_run_count == 0: raise exceptions.BrowserGoneException( None, 'i am a browser crash message') def ValidateAndMeasurePage(self, page, tab, results): pass story_set.AddStory(DummyLocalStory(TestSharedPageState)) story_set.AddStory(DummyLocalStory(TestSharedPageState)) test = Test() story_runner.Run( test, story_set, self.options, self.results) self.assertEquals(2, test.run_count) self.assertEquals(1, len(self.results.failures)) self.assertEquals(1, GetNumberOfSuccessfulPageRuns(self.results)) def testAppCrashThenRaiseInTearDownFatal(self): self.SuppressExceptionFormatting() story_set = story_module.StorySet() unit_test_events = [] # track what was called when class DidRunTestError(Exception): pass class TestTearDownSharedState(TestSharedPageState): def TearDownState(self): unit_test_events.append('tear-down-state') raise DidRunTestError class Test(page_test.PageTest): def __init__(self, *args): super(Test, self).__init__(*args) self.run_count = 0 def RunPage(self, *_): old_run_count = self.run_count self.run_count += 1 if old_run_count == 0: unit_test_events.append('app-crash') raise exceptions.AppCrashException def ValidateAndMeasurePage(self, page, tab, results): pass story_set.AddStory(DummyLocalStory(TestTearDownSharedState)) story_set.AddStory(DummyLocalStory(TestTearDownSharedState)) test = Test() with self.assertRaises(DidRunTestError): story_runner.Run( test, story_set, self.options, self.results) self.assertEqual(['app-crash', 'tear-down-state'], unit_test_events) # The AppCrashException gets added as a failure. self.assertEquals(1, len(self.results.failures)) def testPagesetRepeat(self): story_set = story_module.StorySet() # TODO(eakuefner): Factor this out after flattening page ref in Value blank_story = DummyLocalStory(TestSharedPageState, name='blank') green_story = DummyLocalStory(TestSharedPageState, name='green') story_set.AddStory(blank_story) story_set.AddStory(green_story) class Measurement(page_test.PageTest): i = 0 def RunPage(self, page, _, results): self.i += 1 results.AddValue(scalar.ScalarValue( page, 'metric', 'unit', self.i, improvement_direction=improvement_direction.UP)) def ValidateAndMeasurePage(self, page, tab, results): pass self.options.page_repeat = 1 self.options.pageset_repeat = 2 self.options.output_formats = [] results = results_options.CreateResults( EmptyMetadataForTest(), self.options) story_runner.Run( Measurement(), story_set, self.options, results) summary = summary_module.Summary(results.all_page_specific_values) values = summary.interleaved_computed_per_page_values_and_summaries blank_value = list_of_scalar_values.ListOfScalarValues( blank_story, 'metric', 'unit', [1, 3], improvement_direction=improvement_direction.UP) green_value = list_of_scalar_values.ListOfScalarValues( green_story, 'metric', 'unit', [2, 4], improvement_direction=improvement_direction.UP) merged_value = list_of_scalar_values.ListOfScalarValues( None, 'metric', 'unit', [1, 2, 3, 4], improvement_direction=improvement_direction.UP) self.assertEquals(4, GetNumberOfSuccessfulPageRuns(results)) self.assertEquals(0, len(results.failures)) self.assertEquals(3, len(values)) self.assertIn(blank_value, values) self.assertIn(green_value, values) self.assertIn(merged_value, values) @decorators.Disabled('chromeos') # crbug.com/483212 def testUpdateAndCheckArchives(self): usr_stub = system_stub.Override(story_runner, ['cloud_storage']) wpr_stub = system_stub.Override(archive_info, ['cloud_storage']) archive_data_dir = os.path.join( util.GetTelemetryDir(), 'telemetry', 'internal', 'testing', 'archive_files') try: story_set = story_module.StorySet() story_set.AddStory(page_module.Page( 'http://www.testurl.com', story_set, story_set.base_dir)) # Page set missing archive_data_file. self.assertRaises( story_runner.ArchiveError, story_runner._UpdateAndCheckArchives, story_set.archive_data_file, story_set.wpr_archive_info, story_set.stories) story_set = story_module.StorySet( archive_data_file='missing_archive_data_file.json') story_set.AddStory(page_module.Page( 'http://www.testurl.com', story_set, story_set.base_dir)) # Page set missing json file specified in archive_data_file. self.assertRaises( story_runner.ArchiveError, story_runner._UpdateAndCheckArchives, story_set.archive_data_file, story_set.wpr_archive_info, story_set.stories) story_set = story_module.StorySet( archive_data_file=os.path.join(archive_data_dir, 'test.json'), cloud_storage_bucket=cloud_storage.PUBLIC_BUCKET) story_set.AddStory(page_module.Page( 'http://www.testurl.com', story_set, story_set.base_dir)) # Page set with valid archive_data_file. self.assertTrue(story_runner._UpdateAndCheckArchives( story_set.archive_data_file, story_set.wpr_archive_info, story_set.stories)) story_set.AddStory(page_module.Page( 'http://www.google.com', story_set, story_set.base_dir)) # Page set with an archive_data_file which exists but is missing a page. self.assertRaises( story_runner.ArchiveError, story_runner._UpdateAndCheckArchives, story_set.archive_data_file, story_set.wpr_archive_info, story_set.stories) story_set = story_module.StorySet( archive_data_file= os.path.join(archive_data_dir, 'test_missing_wpr_file.json'), cloud_storage_bucket=cloud_storage.PUBLIC_BUCKET) story_set.AddStory(page_module.Page( 'http://www.testurl.com', story_set, story_set.base_dir)) story_set.AddStory(page_module.Page( 'http://www.google.com', story_set, story_set.base_dir)) # Page set with an archive_data_file which exists and contains all pages # but fails to find a wpr file. self.assertRaises( story_runner.ArchiveError, story_runner._UpdateAndCheckArchives, story_set.archive_data_file, story_set.wpr_archive_info, story_set.stories) finally: usr_stub.Restore() wpr_stub.Restore() def _testMaxFailuresOptionIsRespectedAndOverridable( self, num_failing_stories, runner_max_failures, options_max_failures, expected_num_failures): class SimpleSharedState(story_module.SharedState): _fake_platform = FakePlatform() _current_story = None @property def platform(self): return self._fake_platform def WillRunStory(self, story): self._current_story = story def RunStory(self, results): self._current_story.Run(self) def DidRunStory(self, results): pass def CanRunStory(self, story): return True def TearDownState(self): pass class FailingStory(story_module.Story): def __init__(self): super(FailingStory, self).__init__( shared_state_class=SimpleSharedState, is_local=True) self.was_run = False def Run(self, shared_state): self.was_run = True raise page_test.Failure self.SuppressExceptionFormatting() story_set = story_module.StorySet() for _ in range(num_failing_stories): story_set.AddStory(FailingStory()) options = _GetOptionForUnittest() options.output_formats = ['none'] options.suppress_gtest_report = True if options_max_failures: options.max_failures = options_max_failures results = results_options.CreateResults(EmptyMetadataForTest(), options) story_runner.Run( DummyTest(), story_set, options, results, max_failures=runner_max_failures) self.assertEquals(0, GetNumberOfSuccessfulPageRuns(results)) self.assertEquals(expected_num_failures, len(results.failures)) for ii, story in enumerate(story_set.stories): self.assertEqual(story.was_run, ii < expected_num_failures) def testMaxFailuresNotSpecified(self): self._testMaxFailuresOptionIsRespectedAndOverridable( num_failing_stories=5, runner_max_failures=None, options_max_failures=None, expected_num_failures=5) def testMaxFailuresSpecifiedToRun(self): # Runs up to max_failures+1 failing tests before stopping, since # every tests after max_failures failures have been encountered # may all be passing. self._testMaxFailuresOptionIsRespectedAndOverridable( num_failing_stories=5, runner_max_failures=3, options_max_failures=None, expected_num_failures=4) def testMaxFailuresOption(self): # Runs up to max_failures+1 failing tests before stopping, since # every tests after max_failures failures have been encountered # may all be passing. self._testMaxFailuresOptionIsRespectedAndOverridable( num_failing_stories=5, runner_max_failures=3, options_max_failures=1, expected_num_failures=2)
bsd-3-clause
Tiotao/morpherpy
env/Lib/site-packages/requests/packages/charade/big5freq.py
3133
82594
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # Big5 frequency table # by Taiwan's Mandarin Promotion Council # <http://www.edu.tw:81/mandr/> # # 128 --> 0.42261 # 256 --> 0.57851 # 512 --> 0.74851 # 1024 --> 0.89384 # 2048 --> 0.97583 # # Ideal Distribution Ratio = 0.74851/(1-0.74851) =2.98 # Random Distribution Ration = 512/(5401-512)=0.105 # # Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR BIG5_TYPICAL_DISTRIBUTION_RATIO = 0.75 #Char to FreqOrder table BIG5_TABLE_SIZE = 5376 Big5CharToFreqOrder = ( 1,1801,1506, 255,1431, 198, 9, 82, 6,5008, 177, 202,3681,1256,2821, 110, # 16 3814, 33,3274, 261, 76, 44,2114, 16,2946,2187,1176, 659,3971, 26,3451,2653, # 32 1198,3972,3350,4202, 410,2215, 302, 590, 361,1964, 8, 204, 58,4510,5009,1932, # 48 63,5010,5011, 317,1614, 75, 222, 159,4203,2417,1480,5012,3555,3091, 224,2822, # 64 3682, 3, 10,3973,1471, 29,2787,1135,2866,1940, 873, 130,3275,1123, 312,5013, # 80 4511,2052, 507, 252, 682,5014, 142,1915, 124, 206,2947, 34,3556,3204, 64, 604, # 96 5015,2501,1977,1978, 155,1991, 645, 641,1606,5016,3452, 337, 72, 406,5017, 80, # 112 630, 238,3205,1509, 263, 939,1092,2654, 756,1440,1094,3453, 449, 69,2987, 591, # 128 179,2096, 471, 115,2035,1844, 60, 50,2988, 134, 806,1869, 734,2036,3454, 180, # 144 995,1607, 156, 537,2907, 688,5018, 319,1305, 779,2145, 514,2379, 298,4512, 359, # 160 2502, 90,2716,1338, 663, 11, 906,1099,2553, 20,2441, 182, 532,1716,5019, 732, # 176 1376,4204,1311,1420,3206, 25,2317,1056, 113, 399, 382,1950, 242,3455,2474, 529, # 192 3276, 475,1447,3683,5020, 117, 21, 656, 810,1297,2300,2334,3557,5021, 126,4205, # 208 706, 456, 150, 613,4513, 71,1118,2037,4206, 145,3092, 85, 835, 486,2115,1246, # 224 1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,5022,2128,2359, 347,3815, 221, # 240 3558,3135,5023,1956,1153,4207, 83, 296,1199,3093, 192, 624, 93,5024, 822,1898, # 256 2823,3136, 795,2065, 991,1554,1542,1592, 27, 43,2867, 859, 139,1456, 860,4514, # 272 437, 712,3974, 164,2397,3137, 695, 211,3037,2097, 195,3975,1608,3559,3560,3684, # 288 3976, 234, 811,2989,2098,3977,2233,1441,3561,1615,2380, 668,2077,1638, 305, 228, # 304 1664,4515, 467, 415,5025, 262,2099,1593, 239, 108, 300, 200,1033, 512,1247,2078, # 320 5026,5027,2176,3207,3685,2682, 593, 845,1062,3277, 88,1723,2038,3978,1951, 212, # 336 266, 152, 149, 468,1899,4208,4516, 77, 187,5028,3038, 37, 5,2990,5029,3979, # 352 5030,5031, 39,2524,4517,2908,3208,2079, 55, 148, 74,4518, 545, 483,1474,1029, # 368 1665, 217,1870,1531,3138,1104,2655,4209, 24, 172,3562, 900,3980,3563,3564,4519, # 384 32,1408,2824,1312, 329, 487,2360,2251,2717, 784,2683, 4,3039,3351,1427,1789, # 400 188, 109, 499,5032,3686,1717,1790, 888,1217,3040,4520,5033,3565,5034,3352,1520, # 416 3687,3981, 196,1034, 775,5035,5036, 929,1816, 249, 439, 38,5037,1063,5038, 794, # 432 3982,1435,2301, 46, 178,3278,2066,5039,2381,5040, 214,1709,4521, 804, 35, 707, # 448 324,3688,1601,2554, 140, 459,4210,5041,5042,1365, 839, 272, 978,2262,2580,3456, # 464 2129,1363,3689,1423, 697, 100,3094, 48, 70,1231, 495,3139,2196,5043,1294,5044, # 480 2080, 462, 586,1042,3279, 853, 256, 988, 185,2382,3457,1698, 434,1084,5045,3458, # 496 314,2625,2788,4522,2335,2336, 569,2285, 637,1817,2525, 757,1162,1879,1616,3459, # 512 287,1577,2116, 768,4523,1671,2868,3566,2526,1321,3816, 909,2418,5046,4211, 933, # 528 3817,4212,2053,2361,1222,4524, 765,2419,1322, 786,4525,5047,1920,1462,1677,2909, # 544 1699,5048,4526,1424,2442,3140,3690,2600,3353,1775,1941,3460,3983,4213, 309,1369, # 560 1130,2825, 364,2234,1653,1299,3984,3567,3985,3986,2656, 525,1085,3041, 902,2001, # 576 1475, 964,4527, 421,1845,1415,1057,2286, 940,1364,3141, 376,4528,4529,1381, 7, # 592 2527, 983,2383, 336,1710,2684,1846, 321,3461, 559,1131,3042,2752,1809,1132,1313, # 608 265,1481,1858,5049, 352,1203,2826,3280, 167,1089, 420,2827, 776, 792,1724,3568, # 624 4214,2443,3281,5050,4215,5051, 446, 229, 333,2753, 901,3818,1200,1557,4530,2657, # 640 1921, 395,2754,2685,3819,4216,1836, 125, 916,3209,2626,4531,5052,5053,3820,5054, # 656 5055,5056,4532,3142,3691,1133,2555,1757,3462,1510,2318,1409,3569,5057,2146, 438, # 672 2601,2910,2384,3354,1068, 958,3043, 461, 311,2869,2686,4217,1916,3210,4218,1979, # 688 383, 750,2755,2627,4219, 274, 539, 385,1278,1442,5058,1154,1965, 384, 561, 210, # 704 98,1295,2556,3570,5059,1711,2420,1482,3463,3987,2911,1257, 129,5060,3821, 642, # 720 523,2789,2790,2658,5061, 141,2235,1333, 68, 176, 441, 876, 907,4220, 603,2602, # 736 710, 171,3464, 404, 549, 18,3143,2398,1410,3692,1666,5062,3571,4533,2912,4534, # 752 5063,2991, 368,5064, 146, 366, 99, 871,3693,1543, 748, 807,1586,1185, 22,2263, # 768 379,3822,3211,5065,3212, 505,1942,2628,1992,1382,2319,5066, 380,2362, 218, 702, # 784 1818,1248,3465,3044,3572,3355,3282,5067,2992,3694, 930,3283,3823,5068, 59,5069, # 800 585, 601,4221, 497,3466,1112,1314,4535,1802,5070,1223,1472,2177,5071, 749,1837, # 816 690,1900,3824,1773,3988,1476, 429,1043,1791,2236,2117, 917,4222, 447,1086,1629, # 832 5072, 556,5073,5074,2021,1654, 844,1090, 105, 550, 966,1758,2828,1008,1783, 686, # 848 1095,5075,2287, 793,1602,5076,3573,2603,4536,4223,2948,2302,4537,3825, 980,2503, # 864 544, 353, 527,4538, 908,2687,2913,5077, 381,2629,1943,1348,5078,1341,1252, 560, # 880 3095,5079,3467,2870,5080,2054, 973, 886,2081, 143,4539,5081,5082, 157,3989, 496, # 896 4224, 57, 840, 540,2039,4540,4541,3468,2118,1445, 970,2264,1748,1966,2082,4225, # 912 3144,1234,1776,3284,2829,3695, 773,1206,2130,1066,2040,1326,3990,1738,1725,4226, # 928 279,3145, 51,1544,2604, 423,1578,2131,2067, 173,4542,1880,5083,5084,1583, 264, # 944 610,3696,4543,2444, 280, 154,5085,5086,5087,1739, 338,1282,3096, 693,2871,1411, # 960 1074,3826,2445,5088,4544,5089,5090,1240, 952,2399,5091,2914,1538,2688, 685,1483, # 976 4227,2475,1436, 953,4228,2055,4545, 671,2400, 79,4229,2446,3285, 608, 567,2689, # 992 3469,4230,4231,1691, 393,1261,1792,2401,5092,4546,5093,5094,5095,5096,1383,1672, # 1008 3827,3213,1464, 522,1119, 661,1150, 216, 675,4547,3991,1432,3574, 609,4548,2690, # 1024 2402,5097,5098,5099,4232,3045, 0,5100,2476, 315, 231,2447, 301,3356,4549,2385, # 1040 5101, 233,4233,3697,1819,4550,4551,5102, 96,1777,1315,2083,5103, 257,5104,1810, # 1056 3698,2718,1139,1820,4234,2022,1124,2164,2791,1778,2659,5105,3097, 363,1655,3214, # 1072 5106,2993,5107,5108,5109,3992,1567,3993, 718, 103,3215, 849,1443, 341,3357,2949, # 1088 1484,5110,1712, 127, 67, 339,4235,2403, 679,1412, 821,5111,5112, 834, 738, 351, # 1104 2994,2147, 846, 235,1497,1881, 418,1993,3828,2719, 186,1100,2148,2756,3575,1545, # 1120 1355,2950,2872,1377, 583,3994,4236,2581,2995,5113,1298,3699,1078,2557,3700,2363, # 1136 78,3829,3830, 267,1289,2100,2002,1594,4237, 348, 369,1274,2197,2178,1838,4552, # 1152 1821,2830,3701,2757,2288,2003,4553,2951,2758, 144,3358, 882,4554,3995,2759,3470, # 1168 4555,2915,5114,4238,1726, 320,5115,3996,3046, 788,2996,5116,2831,1774,1327,2873, # 1184 3997,2832,5117,1306,4556,2004,1700,3831,3576,2364,2660, 787,2023, 506, 824,3702, # 1200 534, 323,4557,1044,3359,2024,1901, 946,3471,5118,1779,1500,1678,5119,1882,4558, # 1216 165, 243,4559,3703,2528, 123, 683,4239, 764,4560, 36,3998,1793, 589,2916, 816, # 1232 626,1667,3047,2237,1639,1555,1622,3832,3999,5120,4000,2874,1370,1228,1933, 891, # 1248 2084,2917, 304,4240,5121, 292,2997,2720,3577, 691,2101,4241,1115,4561, 118, 662, # 1264 5122, 611,1156, 854,2386,1316,2875, 2, 386, 515,2918,5123,5124,3286, 868,2238, # 1280 1486, 855,2661, 785,2216,3048,5125,1040,3216,3578,5126,3146, 448,5127,1525,5128, # 1296 2165,4562,5129,3833,5130,4242,2833,3579,3147, 503, 818,4001,3148,1568, 814, 676, # 1312 1444, 306,1749,5131,3834,1416,1030, 197,1428, 805,2834,1501,4563,5132,5133,5134, # 1328 1994,5135,4564,5136,5137,2198, 13,2792,3704,2998,3149,1229,1917,5138,3835,2132, # 1344 5139,4243,4565,2404,3580,5140,2217,1511,1727,1120,5141,5142, 646,3836,2448, 307, # 1360 5143,5144,1595,3217,5145,5146,5147,3705,1113,1356,4002,1465,2529,2530,5148, 519, # 1376 5149, 128,2133, 92,2289,1980,5150,4003,1512, 342,3150,2199,5151,2793,2218,1981, # 1392 3360,4244, 290,1656,1317, 789, 827,2365,5152,3837,4566, 562, 581,4004,5153, 401, # 1408 4567,2252, 94,4568,5154,1399,2794,5155,1463,2025,4569,3218,1944,5156, 828,1105, # 1424 4245,1262,1394,5157,4246, 605,4570,5158,1784,2876,5159,2835, 819,2102, 578,2200, # 1440 2952,5160,1502, 436,3287,4247,3288,2836,4005,2919,3472,3473,5161,2721,2320,5162, # 1456 5163,2337,2068, 23,4571, 193, 826,3838,2103, 699,1630,4248,3098, 390,1794,1064, # 1472 3581,5164,1579,3099,3100,1400,5165,4249,1839,1640,2877,5166,4572,4573, 137,4250, # 1488 598,3101,1967, 780, 104, 974,2953,5167, 278, 899, 253, 402, 572, 504, 493,1339, # 1504 5168,4006,1275,4574,2582,2558,5169,3706,3049,3102,2253, 565,1334,2722, 863, 41, # 1520 5170,5171,4575,5172,1657,2338, 19, 463,2760,4251, 606,5173,2999,3289,1087,2085, # 1536 1323,2662,3000,5174,1631,1623,1750,4252,2691,5175,2878, 791,2723,2663,2339, 232, # 1552 2421,5176,3001,1498,5177,2664,2630, 755,1366,3707,3290,3151,2026,1609, 119,1918, # 1568 3474, 862,1026,4253,5178,4007,3839,4576,4008,4577,2265,1952,2477,5179,1125, 817, # 1584 4254,4255,4009,1513,1766,2041,1487,4256,3050,3291,2837,3840,3152,5180,5181,1507, # 1600 5182,2692, 733, 40,1632,1106,2879, 345,4257, 841,2531, 230,4578,3002,1847,3292, # 1616 3475,5183,1263, 986,3476,5184, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562, # 1632 4010,4011,2954, 967,2761,2665,1349, 592,2134,1692,3361,3003,1995,4258,1679,4012, # 1648 1902,2188,5185, 739,3708,2724,1296,1290,5186,4259,2201,2202,1922,1563,2605,2559, # 1664 1871,2762,3004,5187, 435,5188, 343,1108, 596, 17,1751,4579,2239,3477,3709,5189, # 1680 4580, 294,3582,2955,1693, 477, 979, 281,2042,3583, 643,2043,3710,2631,2795,2266, # 1696 1031,2340,2135,2303,3584,4581, 367,1249,2560,5190,3585,5191,4582,1283,3362,2005, # 1712 240,1762,3363,4583,4584, 836,1069,3153, 474,5192,2149,2532, 268,3586,5193,3219, # 1728 1521,1284,5194,1658,1546,4260,5195,3587,3588,5196,4261,3364,2693,1685,4262, 961, # 1744 1673,2632, 190,2006,2203,3841,4585,4586,5197, 570,2504,3711,1490,5198,4587,2633, # 1760 3293,1957,4588, 584,1514, 396,1045,1945,5199,4589,1968,2449,5200,5201,4590,4013, # 1776 619,5202,3154,3294, 215,2007,2796,2561,3220,4591,3221,4592, 763,4263,3842,4593, # 1792 5203,5204,1958,1767,2956,3365,3712,1174, 452,1477,4594,3366,3155,5205,2838,1253, # 1808 2387,2189,1091,2290,4264, 492,5206, 638,1169,1825,2136,1752,4014, 648, 926,1021, # 1824 1324,4595, 520,4596, 997, 847,1007, 892,4597,3843,2267,1872,3713,2405,1785,4598, # 1840 1953,2957,3103,3222,1728,4265,2044,3714,4599,2008,1701,3156,1551, 30,2268,4266, # 1856 5207,2027,4600,3589,5208, 501,5209,4267, 594,3478,2166,1822,3590,3479,3591,3223, # 1872 829,2839,4268,5210,1680,3157,1225,4269,5211,3295,4601,4270,3158,2341,5212,4602, # 1888 4271,5213,4015,4016,5214,1848,2388,2606,3367,5215,4603, 374,4017, 652,4272,4273, # 1904 375,1140, 798,5216,5217,5218,2366,4604,2269, 546,1659, 138,3051,2450,4605,5219, # 1920 2254, 612,1849, 910, 796,3844,1740,1371, 825,3845,3846,5220,2920,2562,5221, 692, # 1936 444,3052,2634, 801,4606,4274,5222,1491, 244,1053,3053,4275,4276, 340,5223,4018, # 1952 1041,3005, 293,1168, 87,1357,5224,1539, 959,5225,2240, 721, 694,4277,3847, 219, # 1968 1478, 644,1417,3368,2666,1413,1401,1335,1389,4019,5226,5227,3006,2367,3159,1826, # 1984 730,1515, 184,2840, 66,4607,5228,1660,2958, 246,3369, 378,1457, 226,3480, 975, # 2000 4020,2959,1264,3592, 674, 696,5229, 163,5230,1141,2422,2167, 713,3593,3370,4608, # 2016 4021,5231,5232,1186, 15,5233,1079,1070,5234,1522,3224,3594, 276,1050,2725, 758, # 2032 1126, 653,2960,3296,5235,2342, 889,3595,4022,3104,3007, 903,1250,4609,4023,3481, # 2048 3596,1342,1681,1718, 766,3297, 286, 89,2961,3715,5236,1713,5237,2607,3371,3008, # 2064 5238,2962,2219,3225,2880,5239,4610,2505,2533, 181, 387,1075,4024, 731,2190,3372, # 2080 5240,3298, 310, 313,3482,2304, 770,4278, 54,3054, 189,4611,3105,3848,4025,5241, # 2096 1230,1617,1850, 355,3597,4279,4612,3373, 111,4280,3716,1350,3160,3483,3055,4281, # 2112 2150,3299,3598,5242,2797,4026,4027,3009, 722,2009,5243,1071, 247,1207,2343,2478, # 2128 1378,4613,2010, 864,1437,1214,4614, 373,3849,1142,2220, 667,4615, 442,2763,2563, # 2144 3850,4028,1969,4282,3300,1840, 837, 170,1107, 934,1336,1883,5244,5245,2119,4283, # 2160 2841, 743,1569,5246,4616,4284, 582,2389,1418,3484,5247,1803,5248, 357,1395,1729, # 2176 3717,3301,2423,1564,2241,5249,3106,3851,1633,4617,1114,2086,4285,1532,5250, 482, # 2192 2451,4618,5251,5252,1492, 833,1466,5253,2726,3599,1641,2842,5254,1526,1272,3718, # 2208 4286,1686,1795, 416,2564,1903,1954,1804,5255,3852,2798,3853,1159,2321,5256,2881, # 2224 4619,1610,1584,3056,2424,2764, 443,3302,1163,3161,5257,5258,4029,5259,4287,2506, # 2240 3057,4620,4030,3162,2104,1647,3600,2011,1873,4288,5260,4289, 431,3485,5261, 250, # 2256 97, 81,4290,5262,1648,1851,1558, 160, 848,5263, 866, 740,1694,5264,2204,2843, # 2272 3226,4291,4621,3719,1687, 950,2479, 426, 469,3227,3720,3721,4031,5265,5266,1188, # 2288 424,1996, 861,3601,4292,3854,2205,2694, 168,1235,3602,4293,5267,2087,1674,4622, # 2304 3374,3303, 220,2565,1009,5268,3855, 670,3010, 332,1208, 717,5269,5270,3603,2452, # 2320 4032,3375,5271, 513,5272,1209,2882,3376,3163,4623,1080,5273,5274,5275,5276,2534, # 2336 3722,3604, 815,1587,4033,4034,5277,3605,3486,3856,1254,4624,1328,3058,1390,4035, # 2352 1741,4036,3857,4037,5278, 236,3858,2453,3304,5279,5280,3723,3859,1273,3860,4625, # 2368 5281, 308,5282,4626, 245,4627,1852,2480,1307,2583, 430, 715,2137,2454,5283, 270, # 2384 199,2883,4038,5284,3606,2727,1753, 761,1754, 725,1661,1841,4628,3487,3724,5285, # 2400 5286, 587, 14,3305, 227,2608, 326, 480,2270, 943,2765,3607, 291, 650,1884,5287, # 2416 1702,1226, 102,1547, 62,3488, 904,4629,3489,1164,4294,5288,5289,1224,1548,2766, # 2432 391, 498,1493,5290,1386,1419,5291,2056,1177,4630, 813, 880,1081,2368, 566,1145, # 2448 4631,2291,1001,1035,2566,2609,2242, 394,1286,5292,5293,2069,5294, 86,1494,1730, # 2464 4039, 491,1588, 745, 897,2963, 843,3377,4040,2767,2884,3306,1768, 998,2221,2070, # 2480 397,1827,1195,1970,3725,3011,3378, 284,5295,3861,2507,2138,2120,1904,5296,4041, # 2496 2151,4042,4295,1036,3490,1905, 114,2567,4296, 209,1527,5297,5298,2964,2844,2635, # 2512 2390,2728,3164, 812,2568,5299,3307,5300,1559, 737,1885,3726,1210, 885, 28,2695, # 2528 3608,3862,5301,4297,1004,1780,4632,5302, 346,1982,2222,2696,4633,3863,1742, 797, # 2544 1642,4043,1934,1072,1384,2152, 896,4044,3308,3727,3228,2885,3609,5303,2569,1959, # 2560 4634,2455,1786,5304,5305,5306,4045,4298,1005,1308,3728,4299,2729,4635,4636,1528, # 2576 2610, 161,1178,4300,1983, 987,4637,1101,4301, 631,4046,1157,3229,2425,1343,1241, # 2592 1016,2243,2570, 372, 877,2344,2508,1160, 555,1935, 911,4047,5307, 466,1170, 169, # 2608 1051,2921,2697,3729,2481,3012,1182,2012,2571,1251,2636,5308, 992,2345,3491,1540, # 2624 2730,1201,2071,2406,1997,2482,5309,4638, 528,1923,2191,1503,1874,1570,2369,3379, # 2640 3309,5310, 557,1073,5311,1828,3492,2088,2271,3165,3059,3107, 767,3108,2799,4639, # 2656 1006,4302,4640,2346,1267,2179,3730,3230, 778,4048,3231,2731,1597,2667,5312,4641, # 2672 5313,3493,5314,5315,5316,3310,2698,1433,3311, 131, 95,1504,4049, 723,4303,3166, # 2688 1842,3610,2768,2192,4050,2028,2105,3731,5317,3013,4051,1218,5318,3380,3232,4052, # 2704 4304,2584, 248,1634,3864, 912,5319,2845,3732,3060,3865, 654, 53,5320,3014,5321, # 2720 1688,4642, 777,3494,1032,4053,1425,5322, 191, 820,2121,2846, 971,4643, 931,3233, # 2736 135, 664, 783,3866,1998, 772,2922,1936,4054,3867,4644,2923,3234, 282,2732, 640, # 2752 1372,3495,1127, 922, 325,3381,5323,5324, 711,2045,5325,5326,4055,2223,2800,1937, # 2768 4056,3382,2224,2255,3868,2305,5327,4645,3869,1258,3312,4057,3235,2139,2965,4058, # 2784 4059,5328,2225, 258,3236,4646, 101,1227,5329,3313,1755,5330,1391,3314,5331,2924, # 2800 2057, 893,5332,5333,5334,1402,4305,2347,5335,5336,3237,3611,5337,5338, 878,1325, # 2816 1781,2801,4647, 259,1385,2585, 744,1183,2272,4648,5339,4060,2509,5340, 684,1024, # 2832 4306,5341, 472,3612,3496,1165,3315,4061,4062, 322,2153, 881, 455,1695,1152,1340, # 2848 660, 554,2154,4649,1058,4650,4307, 830,1065,3383,4063,4651,1924,5342,1703,1919, # 2864 5343, 932,2273, 122,5344,4652, 947, 677,5345,3870,2637, 297,1906,1925,2274,4653, # 2880 2322,3316,5346,5347,4308,5348,4309, 84,4310, 112, 989,5349, 547,1059,4064, 701, # 2896 3613,1019,5350,4311,5351,3497, 942, 639, 457,2306,2456, 993,2966, 407, 851, 494, # 2912 4654,3384, 927,5352,1237,5353,2426,3385, 573,4312, 680, 921,2925,1279,1875, 285, # 2928 790,1448,1984, 719,2168,5354,5355,4655,4065,4066,1649,5356,1541, 563,5357,1077, # 2944 5358,3386,3061,3498, 511,3015,4067,4068,3733,4069,1268,2572,3387,3238,4656,4657, # 2960 5359, 535,1048,1276,1189,2926,2029,3167,1438,1373,2847,2967,1134,2013,5360,4313, # 2976 1238,2586,3109,1259,5361, 700,5362,2968,3168,3734,4314,5363,4315,1146,1876,1907, # 2992 4658,2611,4070, 781,2427, 132,1589, 203, 147, 273,2802,2407, 898,1787,2155,4071, # 3008 4072,5364,3871,2803,5365,5366,4659,4660,5367,3239,5368,1635,3872, 965,5369,1805, # 3024 2699,1516,3614,1121,1082,1329,3317,4073,1449,3873, 65,1128,2848,2927,2769,1590, # 3040 3874,5370,5371, 12,2668, 45, 976,2587,3169,4661, 517,2535,1013,1037,3240,5372, # 3056 3875,2849,5373,3876,5374,3499,5375,2612, 614,1999,2323,3877,3110,2733,2638,5376, # 3072 2588,4316, 599,1269,5377,1811,3735,5378,2700,3111, 759,1060, 489,1806,3388,3318, # 3088 1358,5379,5380,2391,1387,1215,2639,2256, 490,5381,5382,4317,1759,2392,2348,5383, # 3104 4662,3878,1908,4074,2640,1807,3241,4663,3500,3319,2770,2349, 874,5384,5385,3501, # 3120 3736,1859, 91,2928,3737,3062,3879,4664,5386,3170,4075,2669,5387,3502,1202,1403, # 3136 3880,2969,2536,1517,2510,4665,3503,2511,5388,4666,5389,2701,1886,1495,1731,4076, # 3152 2370,4667,5390,2030,5391,5392,4077,2702,1216, 237,2589,4318,2324,4078,3881,4668, # 3168 4669,2703,3615,3504, 445,4670,5393,5394,5395,5396,2771, 61,4079,3738,1823,4080, # 3184 5397, 687,2046, 935, 925, 405,2670, 703,1096,1860,2734,4671,4081,1877,1367,2704, # 3200 3389, 918,2106,1782,2483, 334,3320,1611,1093,4672, 564,3171,3505,3739,3390, 945, # 3216 2641,2058,4673,5398,1926, 872,4319,5399,3506,2705,3112, 349,4320,3740,4082,4674, # 3232 3882,4321,3741,2156,4083,4675,4676,4322,4677,2408,2047, 782,4084, 400, 251,4323, # 3248 1624,5400,5401, 277,3742, 299,1265, 476,1191,3883,2122,4324,4325,1109, 205,5402, # 3264 2590,1000,2157,3616,1861,5403,5404,5405,4678,5406,4679,2573, 107,2484,2158,4085, # 3280 3507,3172,5407,1533, 541,1301, 158, 753,4326,2886,3617,5408,1696, 370,1088,4327, # 3296 4680,3618, 579, 327, 440, 162,2244, 269,1938,1374,3508, 968,3063, 56,1396,3113, # 3312 2107,3321,3391,5409,1927,2159,4681,3016,5410,3619,5411,5412,3743,4682,2485,5413, # 3328 2804,5414,1650,4683,5415,2613,5416,5417,4086,2671,3392,1149,3393,4087,3884,4088, # 3344 5418,1076, 49,5419, 951,3242,3322,3323, 450,2850, 920,5420,1812,2805,2371,4328, # 3360 1909,1138,2372,3885,3509,5421,3243,4684,1910,1147,1518,2428,4685,3886,5422,4686, # 3376 2393,2614, 260,1796,3244,5423,5424,3887,3324, 708,5425,3620,1704,5426,3621,1351, # 3392 1618,3394,3017,1887, 944,4329,3395,4330,3064,3396,4331,5427,3744, 422, 413,1714, # 3408 3325, 500,2059,2350,4332,2486,5428,1344,1911, 954,5429,1668,5430,5431,4089,2409, # 3424 4333,3622,3888,4334,5432,2307,1318,2512,3114, 133,3115,2887,4687, 629, 31,2851, # 3440 2706,3889,4688, 850, 949,4689,4090,2970,1732,2089,4335,1496,1853,5433,4091, 620, # 3456 3245, 981,1242,3745,3397,1619,3746,1643,3326,2140,2457,1971,1719,3510,2169,5434, # 3472 3246,5435,5436,3398,1829,5437,1277,4690,1565,2048,5438,1636,3623,3116,5439, 869, # 3488 2852, 655,3890,3891,3117,4092,3018,3892,1310,3624,4691,5440,5441,5442,1733, 558, # 3504 4692,3747, 335,1549,3065,1756,4336,3748,1946,3511,1830,1291,1192, 470,2735,2108, # 3520 2806, 913,1054,4093,5443,1027,5444,3066,4094,4693, 982,2672,3399,3173,3512,3247, # 3536 3248,1947,2807,5445, 571,4694,5446,1831,5447,3625,2591,1523,2429,5448,2090, 984, # 3552 4695,3749,1960,5449,3750, 852, 923,2808,3513,3751, 969,1519, 999,2049,2325,1705, # 3568 5450,3118, 615,1662, 151, 597,4095,2410,2326,1049, 275,4696,3752,4337, 568,3753, # 3584 3626,2487,4338,3754,5451,2430,2275, 409,3249,5452,1566,2888,3514,1002, 769,2853, # 3600 194,2091,3174,3755,2226,3327,4339, 628,1505,5453,5454,1763,2180,3019,4096, 521, # 3616 1161,2592,1788,2206,2411,4697,4097,1625,4340,4341, 412, 42,3119, 464,5455,2642, # 3632 4698,3400,1760,1571,2889,3515,2537,1219,2207,3893,2643,2141,2373,4699,4700,3328, # 3648 1651,3401,3627,5456,5457,3628,2488,3516,5458,3756,5459,5460,2276,2092, 460,5461, # 3664 4701,5462,3020, 962, 588,3629, 289,3250,2644,1116, 52,5463,3067,1797,5464,5465, # 3680 5466,1467,5467,1598,1143,3757,4342,1985,1734,1067,4702,1280,3402, 465,4703,1572, # 3696 510,5468,1928,2245,1813,1644,3630,5469,4704,3758,5470,5471,2673,1573,1534,5472, # 3712 5473, 536,1808,1761,3517,3894,3175,2645,5474,5475,5476,4705,3518,2929,1912,2809, # 3728 5477,3329,1122, 377,3251,5478, 360,5479,5480,4343,1529, 551,5481,2060,3759,1769, # 3744 2431,5482,2930,4344,3330,3120,2327,2109,2031,4706,1404, 136,1468,1479, 672,1171, # 3760 3252,2308, 271,3176,5483,2772,5484,2050, 678,2736, 865,1948,4707,5485,2014,4098, # 3776 2971,5486,2737,2227,1397,3068,3760,4708,4709,1735,2931,3403,3631,5487,3895, 509, # 3792 2854,2458,2890,3896,5488,5489,3177,3178,4710,4345,2538,4711,2309,1166,1010, 552, # 3808 681,1888,5490,5491,2972,2973,4099,1287,1596,1862,3179, 358, 453, 736, 175, 478, # 3824 1117, 905,1167,1097,5492,1854,1530,5493,1706,5494,2181,3519,2292,3761,3520,3632, # 3840 4346,2093,4347,5495,3404,1193,2489,4348,1458,2193,2208,1863,1889,1421,3331,2932, # 3856 3069,2182,3521, 595,2123,5496,4100,5497,5498,4349,1707,2646, 223,3762,1359, 751, # 3872 3121, 183,3522,5499,2810,3021, 419,2374, 633, 704,3897,2394, 241,5500,5501,5502, # 3888 838,3022,3763,2277,2773,2459,3898,1939,2051,4101,1309,3122,2246,1181,5503,1136, # 3904 2209,3899,2375,1446,4350,2310,4712,5504,5505,4351,1055,2615, 484,3764,5506,4102, # 3920 625,4352,2278,3405,1499,4353,4103,5507,4104,4354,3253,2279,2280,3523,5508,5509, # 3936 2774, 808,2616,3765,3406,4105,4355,3123,2539, 526,3407,3900,4356, 955,5510,1620, # 3952 4357,2647,2432,5511,1429,3766,1669,1832, 994, 928,5512,3633,1260,5513,5514,5515, # 3968 1949,2293, 741,2933,1626,4358,2738,2460, 867,1184, 362,3408,1392,5516,5517,4106, # 3984 4359,1770,1736,3254,2934,4713,4714,1929,2707,1459,1158,5518,3070,3409,2891,1292, # 4000 1930,2513,2855,3767,1986,1187,2072,2015,2617,4360,5519,2574,2514,2170,3768,2490, # 4016 3332,5520,3769,4715,5521,5522, 666,1003,3023,1022,3634,4361,5523,4716,1814,2257, # 4032 574,3901,1603, 295,1535, 705,3902,4362, 283, 858, 417,5524,5525,3255,4717,4718, # 4048 3071,1220,1890,1046,2281,2461,4107,1393,1599, 689,2575, 388,4363,5526,2491, 802, # 4064 5527,2811,3903,2061,1405,2258,5528,4719,3904,2110,1052,1345,3256,1585,5529, 809, # 4080 5530,5531,5532, 575,2739,3524, 956,1552,1469,1144,2328,5533,2329,1560,2462,3635, # 4096 3257,4108, 616,2210,4364,3180,2183,2294,5534,1833,5535,3525,4720,5536,1319,3770, # 4112 3771,1211,3636,1023,3258,1293,2812,5537,5538,5539,3905, 607,2311,3906, 762,2892, # 4128 1439,4365,1360,4721,1485,3072,5540,4722,1038,4366,1450,2062,2648,4367,1379,4723, # 4144 2593,5541,5542,4368,1352,1414,2330,2935,1172,5543,5544,3907,3908,4724,1798,1451, # 4160 5545,5546,5547,5548,2936,4109,4110,2492,2351, 411,4111,4112,3637,3333,3124,4725, # 4176 1561,2674,1452,4113,1375,5549,5550, 47,2974, 316,5551,1406,1591,2937,3181,5552, # 4192 1025,2142,3125,3182, 354,2740, 884,2228,4369,2412, 508,3772, 726,3638, 996,2433, # 4208 3639, 729,5553, 392,2194,1453,4114,4726,3773,5554,5555,2463,3640,2618,1675,2813, # 4224 919,2352,2975,2353,1270,4727,4115, 73,5556,5557, 647,5558,3259,2856,2259,1550, # 4240 1346,3024,5559,1332, 883,3526,5560,5561,5562,5563,3334,2775,5564,1212, 831,1347, # 4256 4370,4728,2331,3909,1864,3073, 720,3910,4729,4730,3911,5565,4371,5566,5567,4731, # 4272 5568,5569,1799,4732,3774,2619,4733,3641,1645,2376,4734,5570,2938, 669,2211,2675, # 4288 2434,5571,2893,5572,5573,1028,3260,5574,4372,2413,5575,2260,1353,5576,5577,4735, # 4304 3183, 518,5578,4116,5579,4373,1961,5580,2143,4374,5581,5582,3025,2354,2355,3912, # 4320 516,1834,1454,4117,2708,4375,4736,2229,2620,1972,1129,3642,5583,2776,5584,2976, # 4336 1422, 577,1470,3026,1524,3410,5585,5586, 432,4376,3074,3527,5587,2594,1455,2515, # 4352 2230,1973,1175,5588,1020,2741,4118,3528,4737,5589,2742,5590,1743,1361,3075,3529, # 4368 2649,4119,4377,4738,2295, 895, 924,4378,2171, 331,2247,3076, 166,1627,3077,1098, # 4384 5591,1232,2894,2231,3411,4739, 657, 403,1196,2377, 542,3775,3412,1600,4379,3530, # 4400 5592,4740,2777,3261, 576, 530,1362,4741,4742,2540,2676,3776,4120,5593, 842,3913, # 4416 5594,2814,2032,1014,4121, 213,2709,3413, 665, 621,4380,5595,3777,2939,2435,5596, # 4432 2436,3335,3643,3414,4743,4381,2541,4382,4744,3644,1682,4383,3531,1380,5597, 724, # 4448 2282, 600,1670,5598,1337,1233,4745,3126,2248,5599,1621,4746,5600, 651,4384,5601, # 4464 1612,4385,2621,5602,2857,5603,2743,2312,3078,5604, 716,2464,3079, 174,1255,2710, # 4480 4122,3645, 548,1320,1398, 728,4123,1574,5605,1891,1197,3080,4124,5606,3081,3082, # 4496 3778,3646,3779, 747,5607, 635,4386,4747,5608,5609,5610,4387,5611,5612,4748,5613, # 4512 3415,4749,2437, 451,5614,3780,2542,2073,4388,2744,4389,4125,5615,1764,4750,5616, # 4528 4390, 350,4751,2283,2395,2493,5617,4391,4126,2249,1434,4127, 488,4752, 458,4392, # 4544 4128,3781, 771,1330,2396,3914,2576,3184,2160,2414,1553,2677,3185,4393,5618,2494, # 4560 2895,2622,1720,2711,4394,3416,4753,5619,2543,4395,5620,3262,4396,2778,5621,2016, # 4576 2745,5622,1155,1017,3782,3915,5623,3336,2313, 201,1865,4397,1430,5624,4129,5625, # 4592 5626,5627,5628,5629,4398,1604,5630, 414,1866, 371,2595,4754,4755,3532,2017,3127, # 4608 4756,1708, 960,4399, 887, 389,2172,1536,1663,1721,5631,2232,4130,2356,2940,1580, # 4624 5632,5633,1744,4757,2544,4758,4759,5634,4760,5635,2074,5636,4761,3647,3417,2896, # 4640 4400,5637,4401,2650,3418,2815, 673,2712,2465, 709,3533,4131,3648,4402,5638,1148, # 4656 502, 634,5639,5640,1204,4762,3649,1575,4763,2623,3783,5641,3784,3128, 948,3263, # 4672 121,1745,3916,1110,5642,4403,3083,2516,3027,4132,3785,1151,1771,3917,1488,4133, # 4688 1987,5643,2438,3534,5644,5645,2094,5646,4404,3918,1213,1407,2816, 531,2746,2545, # 4704 3264,1011,1537,4764,2779,4405,3129,1061,5647,3786,3787,1867,2897,5648,2018, 120, # 4720 4406,4407,2063,3650,3265,2314,3919,2678,3419,1955,4765,4134,5649,3535,1047,2713, # 4736 1266,5650,1368,4766,2858, 649,3420,3920,2546,2747,1102,2859,2679,5651,5652,2000, # 4752 5653,1111,3651,2977,5654,2495,3921,3652,2817,1855,3421,3788,5655,5656,3422,2415, # 4768 2898,3337,3266,3653,5657,2577,5658,3654,2818,4135,1460, 856,5659,3655,5660,2899, # 4784 2978,5661,2900,3922,5662,4408, 632,2517, 875,3923,1697,3924,2296,5663,5664,4767, # 4800 3028,1239, 580,4768,4409,5665, 914, 936,2075,1190,4136,1039,2124,5666,5667,5668, # 4816 5669,3423,1473,5670,1354,4410,3925,4769,2173,3084,4137, 915,3338,4411,4412,3339, # 4832 1605,1835,5671,2748, 398,3656,4413,3926,4138, 328,1913,2860,4139,3927,1331,4414, # 4848 3029, 937,4415,5672,3657,4140,4141,3424,2161,4770,3425, 524, 742, 538,3085,1012, # 4864 5673,5674,3928,2466,5675, 658,1103, 225,3929,5676,5677,4771,5678,4772,5679,3267, # 4880 1243,5680,4142, 963,2250,4773,5681,2714,3658,3186,5682,5683,2596,2332,5684,4774, # 4896 5685,5686,5687,3536, 957,3426,2547,2033,1931,2941,2467, 870,2019,3659,1746,2780, # 4912 2781,2439,2468,5688,3930,5689,3789,3130,3790,3537,3427,3791,5690,1179,3086,5691, # 4928 3187,2378,4416,3792,2548,3188,3131,2749,4143,5692,3428,1556,2549,2297, 977,2901, # 4944 2034,4144,1205,3429,5693,1765,3430,3189,2125,1271, 714,1689,4775,3538,5694,2333, # 4960 3931, 533,4417,3660,2184, 617,5695,2469,3340,3539,2315,5696,5697,3190,5698,5699, # 4976 3932,1988, 618, 427,2651,3540,3431,5700,5701,1244,1690,5702,2819,4418,4776,5703, # 4992 3541,4777,5704,2284,1576, 473,3661,4419,3432, 972,5705,3662,5706,3087,5707,5708, # 5008 4778,4779,5709,3793,4145,4146,5710, 153,4780, 356,5711,1892,2902,4420,2144, 408, # 5024 803,2357,5712,3933,5713,4421,1646,2578,2518,4781,4782,3934,5714,3935,4422,5715, # 5040 2416,3433, 752,5716,5717,1962,3341,2979,5718, 746,3030,2470,4783,4423,3794, 698, # 5056 4784,1893,4424,3663,2550,4785,3664,3936,5719,3191,3434,5720,1824,1302,4147,2715, # 5072 3937,1974,4425,5721,4426,3192, 823,1303,1288,1236,2861,3542,4148,3435, 774,3938, # 5088 5722,1581,4786,1304,2862,3939,4787,5723,2440,2162,1083,3268,4427,4149,4428, 344, # 5104 1173, 288,2316, 454,1683,5724,5725,1461,4788,4150,2597,5726,5727,4789, 985, 894, # 5120 5728,3436,3193,5729,1914,2942,3795,1989,5730,2111,1975,5731,4151,5732,2579,1194, # 5136 425,5733,4790,3194,1245,3796,4429,5734,5735,2863,5736, 636,4791,1856,3940, 760, # 5152 1800,5737,4430,2212,1508,4792,4152,1894,1684,2298,5738,5739,4793,4431,4432,2213, # 5168 479,5740,5741, 832,5742,4153,2496,5743,2980,2497,3797, 990,3132, 627,1815,2652, # 5184 4433,1582,4434,2126,2112,3543,4794,5744, 799,4435,3195,5745,4795,2113,1737,3031, # 5200 1018, 543, 754,4436,3342,1676,4796,4797,4154,4798,1489,5746,3544,5747,2624,2903, # 5216 4155,5748,5749,2981,5750,5751,5752,5753,3196,4799,4800,2185,1722,5754,3269,3270, # 5232 1843,3665,1715, 481, 365,1976,1857,5755,5756,1963,2498,4801,5757,2127,3666,3271, # 5248 433,1895,2064,2076,5758, 602,2750,5759,5760,5761,5762,5763,3032,1628,3437,5764, # 5264 3197,4802,4156,2904,4803,2519,5765,2551,2782,5766,5767,5768,3343,4804,2905,5769, # 5280 4805,5770,2864,4806,4807,1221,2982,4157,2520,5771,5772,5773,1868,1990,5774,5775, # 5296 5776,1896,5777,5778,4808,1897,4158, 318,5779,2095,4159,4437,5780,5781, 485,5782, # 5312 938,3941, 553,2680, 116,5783,3942,3667,5784,3545,2681,2783,3438,3344,2820,5785, # 5328 3668,2943,4160,1747,2944,2983,5786,5787, 207,5788,4809,5789,4810,2521,5790,3033, # 5344 890,3669,3943,5791,1878,3798,3439,5792,2186,2358,3440,1652,5793,5794,5795, 941, # 5360 2299, 208,3546,4161,2020, 330,4438,3944,2906,2499,3799,4439,4811,5796,5797,5798, # 5376 #last 512 #Everything below is of no interest for detection purpose 2522,1613,4812,5799,3345,3945,2523,5800,4162,5801,1637,4163,2471,4813,3946,5802, # 5392 2500,3034,3800,5803,5804,2195,4814,5805,2163,5806,5807,5808,5809,5810,5811,5812, # 5408 5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828, # 5424 5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844, # 5440 5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856,5857,5858,5859,5860, # 5456 5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872,5873,5874,5875,5876, # 5472 5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888,5889,5890,5891,5892, # 5488 5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904,5905,5906,5907,5908, # 5504 5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920,5921,5922,5923,5924, # 5520 5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936,5937,5938,5939,5940, # 5536 5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952,5953,5954,5955,5956, # 5552 5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968,5969,5970,5971,5972, # 5568 5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984,5985,5986,5987,5988, # 5584 5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000,6001,6002,6003,6004, # 5600 6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016,6017,6018,6019,6020, # 5616 6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032,6033,6034,6035,6036, # 5632 6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052, # 5648 6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6068, # 5664 6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084, # 5680 6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6100, # 5696 6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112,6113,6114,6115,6116, # 5712 6117,6118,6119,6120,6121,6122,6123,6124,6125,6126,6127,6128,6129,6130,6131,6132, # 5728 6133,6134,6135,6136,6137,6138,6139,6140,6141,6142,6143,6144,6145,6146,6147,6148, # 5744 6149,6150,6151,6152,6153,6154,6155,6156,6157,6158,6159,6160,6161,6162,6163,6164, # 5760 6165,6166,6167,6168,6169,6170,6171,6172,6173,6174,6175,6176,6177,6178,6179,6180, # 5776 6181,6182,6183,6184,6185,6186,6187,6188,6189,6190,6191,6192,6193,6194,6195,6196, # 5792 6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210,6211,6212, # 5808 6213,6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,3670,6224,6225,6226,6227, # 5824 6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241,6242,6243, # 5840 6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,6254,6255,6256,6257,6258,6259, # 5856 6260,6261,6262,6263,6264,6265,6266,6267,6268,6269,6270,6271,6272,6273,6274,6275, # 5872 6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,4815,6286,6287,6288,6289,6290, # 5888 6291,6292,4816,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,6303,6304,6305, # 5904 6306,6307,6308,6309,6310,6311,4817,4818,6312,6313,6314,6315,6316,6317,6318,4819, # 5920 6319,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333,6334, # 5936 6335,6336,6337,4820,6338,6339,6340,6341,6342,6343,6344,6345,6346,6347,6348,6349, # 5952 6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363,6364,6365, # 5968 6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379,6380,6381, # 5984 6382,6383,6384,6385,6386,6387,6388,6389,6390,6391,6392,6393,6394,6395,6396,6397, # 6000 6398,6399,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,3441,6411,6412, # 6016 6413,6414,6415,6416,6417,6418,6419,6420,6421,6422,6423,6424,6425,4440,6426,6427, # 6032 6428,6429,6430,6431,6432,6433,6434,6435,6436,6437,6438,6439,6440,6441,6442,6443, # 6048 6444,6445,6446,6447,6448,6449,6450,6451,6452,6453,6454,4821,6455,6456,6457,6458, # 6064 6459,6460,6461,6462,6463,6464,6465,6466,6467,6468,6469,6470,6471,6472,6473,6474, # 6080 6475,6476,6477,3947,3948,6478,6479,6480,6481,3272,4441,6482,6483,6484,6485,4442, # 6096 6486,6487,6488,6489,6490,6491,6492,6493,6494,6495,6496,4822,6497,6498,6499,6500, # 6112 6501,6502,6503,6504,6505,6506,6507,6508,6509,6510,6511,6512,6513,6514,6515,6516, # 6128 6517,6518,6519,6520,6521,6522,6523,6524,6525,6526,6527,6528,6529,6530,6531,6532, # 6144 6533,6534,6535,6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548, # 6160 6549,6550,6551,6552,6553,6554,6555,6556,2784,6557,4823,6558,6559,6560,6561,6562, # 6176 6563,6564,6565,6566,6567,6568,6569,3949,6570,6571,6572,4824,6573,6574,6575,6576, # 6192 6577,6578,6579,6580,6581,6582,6583,4825,6584,6585,6586,3950,2785,6587,6588,6589, # 6208 6590,6591,6592,6593,6594,6595,6596,6597,6598,6599,6600,6601,6602,6603,6604,6605, # 6224 6606,6607,6608,6609,6610,6611,6612,4826,6613,6614,6615,4827,6616,6617,6618,6619, # 6240 6620,6621,6622,6623,6624,6625,4164,6626,6627,6628,6629,6630,6631,6632,6633,6634, # 6256 3547,6635,4828,6636,6637,6638,6639,6640,6641,6642,3951,2984,6643,6644,6645,6646, # 6272 6647,6648,6649,4165,6650,4829,6651,6652,4830,6653,6654,6655,6656,6657,6658,6659, # 6288 6660,6661,6662,4831,6663,6664,6665,6666,6667,6668,6669,6670,6671,4166,6672,4832, # 6304 3952,6673,6674,6675,6676,4833,6677,6678,6679,4167,6680,6681,6682,3198,6683,6684, # 6320 6685,6686,6687,6688,6689,6690,6691,6692,6693,6694,6695,6696,6697,4834,6698,6699, # 6336 6700,6701,6702,6703,6704,6705,6706,6707,6708,6709,6710,6711,6712,6713,6714,6715, # 6352 6716,6717,6718,6719,6720,6721,6722,6723,6724,6725,6726,6727,6728,6729,6730,6731, # 6368 6732,6733,6734,4443,6735,6736,6737,6738,6739,6740,6741,6742,6743,6744,6745,4444, # 6384 6746,6747,6748,6749,6750,6751,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761, # 6400 6762,6763,6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777, # 6416 6778,6779,6780,6781,4168,6782,6783,3442,6784,6785,6786,6787,6788,6789,6790,6791, # 6432 4169,6792,6793,6794,6795,6796,6797,6798,6799,6800,6801,6802,6803,6804,6805,6806, # 6448 6807,6808,6809,6810,6811,4835,6812,6813,6814,4445,6815,6816,4446,6817,6818,6819, # 6464 6820,6821,6822,6823,6824,6825,6826,6827,6828,6829,6830,6831,6832,6833,6834,6835, # 6480 3548,6836,6837,6838,6839,6840,6841,6842,6843,6844,6845,6846,4836,6847,6848,6849, # 6496 6850,6851,6852,6853,6854,3953,6855,6856,6857,6858,6859,6860,6861,6862,6863,6864, # 6512 6865,6866,6867,6868,6869,6870,6871,6872,6873,6874,6875,6876,6877,3199,6878,6879, # 6528 6880,6881,6882,4447,6883,6884,6885,6886,6887,6888,6889,6890,6891,6892,6893,6894, # 6544 6895,6896,6897,6898,6899,6900,6901,6902,6903,6904,4170,6905,6906,6907,6908,6909, # 6560 6910,6911,6912,6913,6914,6915,6916,6917,6918,6919,6920,6921,6922,6923,6924,6925, # 6576 6926,6927,4837,6928,6929,6930,6931,6932,6933,6934,6935,6936,3346,6937,6938,4838, # 6592 6939,6940,6941,4448,6942,6943,6944,6945,6946,4449,6947,6948,6949,6950,6951,6952, # 6608 6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6964,6965,6966,6967,6968, # 6624 6969,6970,6971,6972,6973,6974,6975,6976,6977,6978,6979,6980,6981,6982,6983,6984, # 6640 6985,6986,6987,6988,6989,6990,6991,6992,6993,6994,3671,6995,6996,6997,6998,4839, # 6656 6999,7000,7001,7002,3549,7003,7004,7005,7006,7007,7008,7009,7010,7011,7012,7013, # 6672 7014,7015,7016,7017,7018,7019,7020,7021,7022,7023,7024,7025,7026,7027,7028,7029, # 6688 7030,4840,7031,7032,7033,7034,7035,7036,7037,7038,4841,7039,7040,7041,7042,7043, # 6704 7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058,7059, # 6720 7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,2985,7071,7072,7073,7074, # 6736 7075,7076,7077,7078,7079,7080,4842,7081,7082,7083,7084,7085,7086,7087,7088,7089, # 6752 7090,7091,7092,7093,7094,7095,7096,7097,7098,7099,7100,7101,7102,7103,7104,7105, # 6768 7106,7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,4450,7119,7120, # 6784 7121,7122,7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136, # 6800 7137,7138,7139,7140,7141,7142,7143,4843,7144,7145,7146,7147,7148,7149,7150,7151, # 6816 7152,7153,7154,7155,7156,7157,7158,7159,7160,7161,7162,7163,7164,7165,7166,7167, # 6832 7168,7169,7170,7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183, # 6848 7184,7185,7186,7187,7188,4171,4172,7189,7190,7191,7192,7193,7194,7195,7196,7197, # 6864 7198,7199,7200,7201,7202,7203,7204,7205,7206,7207,7208,7209,7210,7211,7212,7213, # 6880 7214,7215,7216,7217,7218,7219,7220,7221,7222,7223,7224,7225,7226,7227,7228,7229, # 6896 7230,7231,7232,7233,7234,7235,7236,7237,7238,7239,7240,7241,7242,7243,7244,7245, # 6912 7246,7247,7248,7249,7250,7251,7252,7253,7254,7255,7256,7257,7258,7259,7260,7261, # 6928 7262,7263,7264,7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277, # 6944 7278,7279,7280,7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293, # 6960 7294,7295,7296,4844,7297,7298,7299,7300,7301,7302,7303,7304,7305,7306,7307,7308, # 6976 7309,7310,7311,7312,7313,7314,7315,7316,4451,7317,7318,7319,7320,7321,7322,7323, # 6992 7324,7325,7326,7327,7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339, # 7008 7340,7341,7342,7343,7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,4173,7354, # 7024 7355,4845,7356,7357,7358,7359,7360,7361,7362,7363,7364,7365,7366,7367,7368,7369, # 7040 7370,7371,7372,7373,7374,7375,7376,7377,7378,7379,7380,7381,7382,7383,7384,7385, # 7056 7386,7387,7388,4846,7389,7390,7391,7392,7393,7394,7395,7396,7397,7398,7399,7400, # 7072 7401,7402,7403,7404,7405,3672,7406,7407,7408,7409,7410,7411,7412,7413,7414,7415, # 7088 7416,7417,7418,7419,7420,7421,7422,7423,7424,7425,7426,7427,7428,7429,7430,7431, # 7104 7432,7433,7434,7435,7436,7437,7438,7439,7440,7441,7442,7443,7444,7445,7446,7447, # 7120 7448,7449,7450,7451,7452,7453,4452,7454,3200,7455,7456,7457,7458,7459,7460,7461, # 7136 7462,7463,7464,7465,7466,7467,7468,7469,7470,7471,7472,7473,7474,4847,7475,7476, # 7152 7477,3133,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487,7488,7489,7490,7491, # 7168 7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,3347,7503,7504,7505,7506, # 7184 7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519,7520,7521,4848, # 7200 7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535,7536,7537, # 7216 7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,3801,4849,7550,7551, # 7232 7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567, # 7248 7568,7569,3035,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582, # 7264 7583,7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598, # 7280 7599,7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614, # 7296 7615,7616,4850,7617,7618,3802,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628, # 7312 7629,7630,7631,7632,4851,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643, # 7328 7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659, # 7344 7660,7661,7662,7663,7664,7665,7666,7667,7668,7669,7670,4453,7671,7672,7673,7674, # 7360 7675,7676,7677,7678,7679,7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690, # 7376 7691,7692,7693,7694,7695,7696,7697,3443,7698,7699,7700,7701,7702,4454,7703,7704, # 7392 7705,7706,7707,7708,7709,7710,7711,7712,7713,2472,7714,7715,7716,7717,7718,7719, # 7408 7720,7721,7722,7723,7724,7725,7726,7727,7728,7729,7730,7731,3954,7732,7733,7734, # 7424 7735,7736,7737,7738,7739,7740,7741,7742,7743,7744,7745,7746,7747,7748,7749,7750, # 7440 3134,7751,7752,4852,7753,7754,7755,4853,7756,7757,7758,7759,7760,4174,7761,7762, # 7456 7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,7777,7778, # 7472 7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791,7792,7793,7794, # 7488 7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,4854,7806,7807,7808,7809, # 7504 7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824,7825, # 7520 4855,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840, # 7536 7841,7842,7843,7844,7845,7846,7847,3955,7848,7849,7850,7851,7852,7853,7854,7855, # 7552 7856,7857,7858,7859,7860,3444,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870, # 7568 7871,7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886, # 7584 7887,7888,7889,7890,7891,4175,7892,7893,7894,7895,7896,4856,4857,7897,7898,7899, # 7600 7900,2598,7901,7902,7903,7904,7905,7906,7907,7908,4455,7909,7910,7911,7912,7913, # 7616 7914,3201,7915,7916,7917,7918,7919,7920,7921,4858,7922,7923,7924,7925,7926,7927, # 7632 7928,7929,7930,7931,7932,7933,7934,7935,7936,7937,7938,7939,7940,7941,7942,7943, # 7648 7944,7945,7946,7947,7948,7949,7950,7951,7952,7953,7954,7955,7956,7957,7958,7959, # 7664 7960,7961,7962,7963,7964,7965,7966,7967,7968,7969,7970,7971,7972,7973,7974,7975, # 7680 7976,7977,7978,7979,7980,7981,4859,7982,7983,7984,7985,7986,7987,7988,7989,7990, # 7696 7991,7992,7993,7994,7995,7996,4860,7997,7998,7999,8000,8001,8002,8003,8004,8005, # 7712 8006,8007,8008,8009,8010,8011,8012,8013,8014,8015,8016,4176,8017,8018,8019,8020, # 7728 8021,8022,8023,4861,8024,8025,8026,8027,8028,8029,8030,8031,8032,8033,8034,8035, # 7744 8036,4862,4456,8037,8038,8039,8040,4863,8041,8042,8043,8044,8045,8046,8047,8048, # 7760 8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063,8064, # 7776 8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079,8080, # 7792 8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095,8096, # 7808 8097,8098,8099,4864,4177,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110, # 7824 8111,8112,8113,8114,8115,8116,8117,8118,8119,8120,4178,8121,8122,8123,8124,8125, # 7840 8126,8127,8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141, # 7856 8142,8143,8144,8145,4865,4866,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155, # 7872 8156,8157,8158,8159,8160,8161,8162,8163,8164,8165,4179,8166,8167,8168,8169,8170, # 7888 8171,8172,8173,8174,8175,8176,8177,8178,8179,8180,8181,4457,8182,8183,8184,8185, # 7904 8186,8187,8188,8189,8190,8191,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201, # 7920 8202,8203,8204,8205,8206,8207,8208,8209,8210,8211,8212,8213,8214,8215,8216,8217, # 7936 8218,8219,8220,8221,8222,8223,8224,8225,8226,8227,8228,8229,8230,8231,8232,8233, # 7952 8234,8235,8236,8237,8238,8239,8240,8241,8242,8243,8244,8245,8246,8247,8248,8249, # 7968 8250,8251,8252,8253,8254,8255,8256,3445,8257,8258,8259,8260,8261,8262,4458,8263, # 7984 8264,8265,8266,8267,8268,8269,8270,8271,8272,4459,8273,8274,8275,8276,3550,8277, # 8000 8278,8279,8280,8281,8282,8283,8284,8285,8286,8287,8288,8289,4460,8290,8291,8292, # 8016 8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,8304,8305,8306,8307,4867, # 8032 8308,8309,8310,8311,8312,3551,8313,8314,8315,8316,8317,8318,8319,8320,8321,8322, # 8048 8323,8324,8325,8326,4868,8327,8328,8329,8330,8331,8332,8333,8334,8335,8336,8337, # 8064 8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8349,8350,8351,8352,8353, # 8080 8354,8355,8356,8357,8358,8359,8360,8361,8362,8363,4869,4461,8364,8365,8366,8367, # 8096 8368,8369,8370,4870,8371,8372,8373,8374,8375,8376,8377,8378,8379,8380,8381,8382, # 8112 8383,8384,8385,8386,8387,8388,8389,8390,8391,8392,8393,8394,8395,8396,8397,8398, # 8128 8399,8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,4871,8411,8412,8413, # 8144 8414,8415,8416,8417,8418,8419,8420,8421,8422,4462,8423,8424,8425,8426,8427,8428, # 8160 8429,8430,8431,8432,8433,2986,8434,8435,8436,8437,8438,8439,8440,8441,8442,8443, # 8176 8444,8445,8446,8447,8448,8449,8450,8451,8452,8453,8454,8455,8456,8457,8458,8459, # 8192 8460,8461,8462,8463,8464,8465,8466,8467,8468,8469,8470,8471,8472,8473,8474,8475, # 8208 8476,8477,8478,4180,8479,8480,8481,8482,8483,8484,8485,8486,8487,8488,8489,8490, # 8224 8491,8492,8493,8494,8495,8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8506, # 8240 8507,8508,8509,8510,8511,8512,8513,8514,8515,8516,8517,8518,8519,8520,8521,8522, # 8256 8523,8524,8525,8526,8527,8528,8529,8530,8531,8532,8533,8534,8535,8536,8537,8538, # 8272 8539,8540,8541,8542,8543,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554, # 8288 8555,8556,8557,8558,8559,8560,8561,8562,8563,8564,4872,8565,8566,8567,8568,8569, # 8304 8570,8571,8572,8573,4873,8574,8575,8576,8577,8578,8579,8580,8581,8582,8583,8584, # 8320 8585,8586,8587,8588,8589,8590,8591,8592,8593,8594,8595,8596,8597,8598,8599,8600, # 8336 8601,8602,8603,8604,8605,3803,8606,8607,8608,8609,8610,8611,8612,8613,4874,3804, # 8352 8614,8615,8616,8617,8618,8619,8620,8621,3956,8622,8623,8624,8625,8626,8627,8628, # 8368 8629,8630,8631,8632,8633,8634,8635,8636,8637,8638,2865,8639,8640,8641,8642,8643, # 8384 8644,8645,8646,8647,8648,8649,8650,8651,8652,8653,8654,8655,8656,4463,8657,8658, # 8400 8659,4875,4876,8660,8661,8662,8663,8664,8665,8666,8667,8668,8669,8670,8671,8672, # 8416 8673,8674,8675,8676,8677,8678,8679,8680,8681,4464,8682,8683,8684,8685,8686,8687, # 8432 8688,8689,8690,8691,8692,8693,8694,8695,8696,8697,8698,8699,8700,8701,8702,8703, # 8448 8704,8705,8706,8707,8708,8709,2261,8710,8711,8712,8713,8714,8715,8716,8717,8718, # 8464 8719,8720,8721,8722,8723,8724,8725,8726,8727,8728,8729,8730,8731,8732,8733,4181, # 8480 8734,8735,8736,8737,8738,8739,8740,8741,8742,8743,8744,8745,8746,8747,8748,8749, # 8496 8750,8751,8752,8753,8754,8755,8756,8757,8758,8759,8760,8761,8762,8763,4877,8764, # 8512 8765,8766,8767,8768,8769,8770,8771,8772,8773,8774,8775,8776,8777,8778,8779,8780, # 8528 8781,8782,8783,8784,8785,8786,8787,8788,4878,8789,4879,8790,8791,8792,4880,8793, # 8544 8794,8795,8796,8797,8798,8799,8800,8801,4881,8802,8803,8804,8805,8806,8807,8808, # 8560 8809,8810,8811,8812,8813,8814,8815,3957,8816,8817,8818,8819,8820,8821,8822,8823, # 8576 8824,8825,8826,8827,8828,8829,8830,8831,8832,8833,8834,8835,8836,8837,8838,8839, # 8592 8840,8841,8842,8843,8844,8845,8846,8847,4882,8848,8849,8850,8851,8852,8853,8854, # 8608 8855,8856,8857,8858,8859,8860,8861,8862,8863,8864,8865,8866,8867,8868,8869,8870, # 8624 8871,8872,8873,8874,8875,8876,8877,8878,8879,8880,8881,8882,8883,8884,3202,8885, # 8640 8886,8887,8888,8889,8890,8891,8892,8893,8894,8895,8896,8897,8898,8899,8900,8901, # 8656 8902,8903,8904,8905,8906,8907,8908,8909,8910,8911,8912,8913,8914,8915,8916,8917, # 8672 8918,8919,8920,8921,8922,8923,8924,4465,8925,8926,8927,8928,8929,8930,8931,8932, # 8688 4883,8933,8934,8935,8936,8937,8938,8939,8940,8941,8942,8943,2214,8944,8945,8946, # 8704 8947,8948,8949,8950,8951,8952,8953,8954,8955,8956,8957,8958,8959,8960,8961,8962, # 8720 8963,8964,8965,4884,8966,8967,8968,8969,8970,8971,8972,8973,8974,8975,8976,8977, # 8736 8978,8979,8980,8981,8982,8983,8984,8985,8986,8987,8988,8989,8990,8991,8992,4885, # 8752 8993,8994,8995,8996,8997,8998,8999,9000,9001,9002,9003,9004,9005,9006,9007,9008, # 8768 9009,9010,9011,9012,9013,9014,9015,9016,9017,9018,9019,9020,9021,4182,9022,9023, # 8784 9024,9025,9026,9027,9028,9029,9030,9031,9032,9033,9034,9035,9036,9037,9038,9039, # 8800 9040,9041,9042,9043,9044,9045,9046,9047,9048,9049,9050,9051,9052,9053,9054,9055, # 8816 9056,9057,9058,9059,9060,9061,9062,9063,4886,9064,9065,9066,9067,9068,9069,4887, # 8832 9070,9071,9072,9073,9074,9075,9076,9077,9078,9079,9080,9081,9082,9083,9084,9085, # 8848 9086,9087,9088,9089,9090,9091,9092,9093,9094,9095,9096,9097,9098,9099,9100,9101, # 8864 9102,9103,9104,9105,9106,9107,9108,9109,9110,9111,9112,9113,9114,9115,9116,9117, # 8880 9118,9119,9120,9121,9122,9123,9124,9125,9126,9127,9128,9129,9130,9131,9132,9133, # 8896 9134,9135,9136,9137,9138,9139,9140,9141,3958,9142,9143,9144,9145,9146,9147,9148, # 8912 9149,9150,9151,4888,9152,9153,9154,9155,9156,9157,9158,9159,9160,9161,9162,9163, # 8928 9164,9165,9166,9167,9168,9169,9170,9171,9172,9173,9174,9175,4889,9176,9177,9178, # 8944 9179,9180,9181,9182,9183,9184,9185,9186,9187,9188,9189,9190,9191,9192,9193,9194, # 8960 9195,9196,9197,9198,9199,9200,9201,9202,9203,4890,9204,9205,9206,9207,9208,9209, # 8976 9210,9211,9212,9213,9214,9215,9216,9217,9218,9219,9220,9221,9222,4466,9223,9224, # 8992 9225,9226,9227,9228,9229,9230,9231,9232,9233,9234,9235,9236,9237,9238,9239,9240, # 9008 9241,9242,9243,9244,9245,4891,9246,9247,9248,9249,9250,9251,9252,9253,9254,9255, # 9024 9256,9257,4892,9258,9259,9260,9261,4893,4894,9262,9263,9264,9265,9266,9267,9268, # 9040 9269,9270,9271,9272,9273,4467,9274,9275,9276,9277,9278,9279,9280,9281,9282,9283, # 9056 9284,9285,3673,9286,9287,9288,9289,9290,9291,9292,9293,9294,9295,9296,9297,9298, # 9072 9299,9300,9301,9302,9303,9304,9305,9306,9307,9308,9309,9310,9311,9312,9313,9314, # 9088 9315,9316,9317,9318,9319,9320,9321,9322,4895,9323,9324,9325,9326,9327,9328,9329, # 9104 9330,9331,9332,9333,9334,9335,9336,9337,9338,9339,9340,9341,9342,9343,9344,9345, # 9120 9346,9347,4468,9348,9349,9350,9351,9352,9353,9354,9355,9356,9357,9358,9359,9360, # 9136 9361,9362,9363,9364,9365,9366,9367,9368,9369,9370,9371,9372,9373,4896,9374,4469, # 9152 9375,9376,9377,9378,9379,4897,9380,9381,9382,9383,9384,9385,9386,9387,9388,9389, # 9168 9390,9391,9392,9393,9394,9395,9396,9397,9398,9399,9400,9401,9402,9403,9404,9405, # 9184 9406,4470,9407,2751,9408,9409,3674,3552,9410,9411,9412,9413,9414,9415,9416,9417, # 9200 9418,9419,9420,9421,4898,9422,9423,9424,9425,9426,9427,9428,9429,3959,9430,9431, # 9216 9432,9433,9434,9435,9436,4471,9437,9438,9439,9440,9441,9442,9443,9444,9445,9446, # 9232 9447,9448,9449,9450,3348,9451,9452,9453,9454,9455,9456,9457,9458,9459,9460,9461, # 9248 9462,9463,9464,9465,9466,9467,9468,9469,9470,9471,9472,4899,9473,9474,9475,9476, # 9264 9477,4900,9478,9479,9480,9481,9482,9483,9484,9485,9486,9487,9488,3349,9489,9490, # 9280 9491,9492,9493,9494,9495,9496,9497,9498,9499,9500,9501,9502,9503,9504,9505,9506, # 9296 9507,9508,9509,9510,9511,9512,9513,9514,9515,9516,9517,9518,9519,9520,4901,9521, # 9312 9522,9523,9524,9525,9526,4902,9527,9528,9529,9530,9531,9532,9533,9534,9535,9536, # 9328 9537,9538,9539,9540,9541,9542,9543,9544,9545,9546,9547,9548,9549,9550,9551,9552, # 9344 9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568, # 9360 9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9581,9582,9583,9584, # 9376 3805,9585,9586,9587,9588,9589,9590,9591,9592,9593,9594,9595,9596,9597,9598,9599, # 9392 9600,9601,9602,4903,9603,9604,9605,9606,9607,4904,9608,9609,9610,9611,9612,9613, # 9408 9614,4905,9615,9616,9617,9618,9619,9620,9621,9622,9623,9624,9625,9626,9627,9628, # 9424 9629,9630,9631,9632,4906,9633,9634,9635,9636,9637,9638,9639,9640,9641,9642,9643, # 9440 4907,9644,9645,9646,9647,9648,9649,9650,9651,9652,9653,9654,9655,9656,9657,9658, # 9456 9659,9660,9661,9662,9663,9664,9665,9666,9667,9668,9669,9670,9671,9672,4183,9673, # 9472 9674,9675,9676,9677,4908,9678,9679,9680,9681,4909,9682,9683,9684,9685,9686,9687, # 9488 9688,9689,9690,4910,9691,9692,9693,3675,9694,9695,9696,2945,9697,9698,9699,9700, # 9504 9701,9702,9703,9704,9705,4911,9706,9707,9708,9709,9710,9711,9712,9713,9714,9715, # 9520 9716,9717,9718,9719,9720,9721,9722,9723,9724,9725,9726,9727,9728,9729,9730,9731, # 9536 9732,9733,9734,9735,4912,9736,9737,9738,9739,9740,4913,9741,9742,9743,9744,9745, # 9552 9746,9747,9748,9749,9750,9751,9752,9753,9754,9755,9756,9757,9758,4914,9759,9760, # 9568 9761,9762,9763,9764,9765,9766,9767,9768,9769,9770,9771,9772,9773,9774,9775,9776, # 9584 9777,9778,9779,9780,9781,9782,4915,9783,9784,9785,9786,9787,9788,9789,9790,9791, # 9600 9792,9793,4916,9794,9795,9796,9797,9798,9799,9800,9801,9802,9803,9804,9805,9806, # 9616 9807,9808,9809,9810,9811,9812,9813,9814,9815,9816,9817,9818,9819,9820,9821,9822, # 9632 9823,9824,9825,9826,9827,9828,9829,9830,9831,9832,9833,9834,9835,9836,9837,9838, # 9648 9839,9840,9841,9842,9843,9844,9845,9846,9847,9848,9849,9850,9851,9852,9853,9854, # 9664 9855,9856,9857,9858,9859,9860,9861,9862,9863,9864,9865,9866,9867,9868,4917,9869, # 9680 9870,9871,9872,9873,9874,9875,9876,9877,9878,9879,9880,9881,9882,9883,9884,9885, # 9696 9886,9887,9888,9889,9890,9891,9892,4472,9893,9894,9895,9896,9897,3806,9898,9899, # 9712 9900,9901,9902,9903,9904,9905,9906,9907,9908,9909,9910,9911,9912,9913,9914,4918, # 9728 9915,9916,9917,4919,9918,9919,9920,9921,4184,9922,9923,9924,9925,9926,9927,9928, # 9744 9929,9930,9931,9932,9933,9934,9935,9936,9937,9938,9939,9940,9941,9942,9943,9944, # 9760 9945,9946,4920,9947,9948,9949,9950,9951,9952,9953,9954,9955,4185,9956,9957,9958, # 9776 9959,9960,9961,9962,9963,9964,9965,4921,9966,9967,9968,4473,9969,9970,9971,9972, # 9792 9973,9974,9975,9976,9977,4474,9978,9979,9980,9981,9982,9983,9984,9985,9986,9987, # 9808 9988,9989,9990,9991,9992,9993,9994,9995,9996,9997,9998,9999,10000,10001,10002,10003, # 9824 10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10015,10016,10017,10018,10019, # 9840 10020,10021,4922,10022,4923,10023,10024,10025,10026,10027,10028,10029,10030,10031,10032,10033, # 9856 10034,10035,10036,10037,10038,10039,10040,10041,10042,10043,10044,10045,10046,10047,10048,4924, # 9872 10049,10050,10051,10052,10053,10054,10055,10056,10057,10058,10059,10060,10061,10062,10063,10064, # 9888 10065,10066,10067,10068,10069,10070,10071,10072,10073,10074,10075,10076,10077,10078,10079,10080, # 9904 10081,10082,10083,10084,10085,10086,10087,4475,10088,10089,10090,10091,10092,10093,10094,10095, # 9920 10096,10097,4476,10098,10099,10100,10101,10102,10103,10104,10105,10106,10107,10108,10109,10110, # 9936 10111,2174,10112,10113,10114,10115,10116,10117,10118,10119,10120,10121,10122,10123,10124,10125, # 9952 10126,10127,10128,10129,10130,10131,10132,10133,10134,10135,10136,10137,10138,10139,10140,3807, # 9968 4186,4925,10141,10142,10143,10144,10145,10146,10147,4477,4187,10148,10149,10150,10151,10152, # 9984 10153,4188,10154,10155,10156,10157,10158,10159,10160,10161,4926,10162,10163,10164,10165,10166, #10000 10167,10168,10169,10170,10171,10172,10173,10174,10175,10176,10177,10178,10179,10180,10181,10182, #10016 10183,10184,10185,10186,10187,10188,10189,10190,10191,10192,3203,10193,10194,10195,10196,10197, #10032 10198,10199,10200,4478,10201,10202,10203,10204,4479,10205,10206,10207,10208,10209,10210,10211, #10048 10212,10213,10214,10215,10216,10217,10218,10219,10220,10221,10222,10223,10224,10225,10226,10227, #10064 10228,10229,10230,10231,10232,10233,10234,4927,10235,10236,10237,10238,10239,10240,10241,10242, #10080 10243,10244,10245,10246,10247,10248,10249,10250,10251,10252,10253,10254,10255,10256,10257,10258, #10096 10259,10260,10261,10262,10263,10264,10265,10266,10267,10268,10269,10270,10271,10272,10273,4480, #10112 4928,4929,10274,10275,10276,10277,10278,10279,10280,10281,10282,10283,10284,10285,10286,10287, #10128 10288,10289,10290,10291,10292,10293,10294,10295,10296,10297,10298,10299,10300,10301,10302,10303, #10144 10304,10305,10306,10307,10308,10309,10310,10311,10312,10313,10314,10315,10316,10317,10318,10319, #10160 10320,10321,10322,10323,10324,10325,10326,10327,10328,10329,10330,10331,10332,10333,10334,4930, #10176 10335,10336,10337,10338,10339,10340,10341,10342,4931,10343,10344,10345,10346,10347,10348,10349, #10192 10350,10351,10352,10353,10354,10355,3088,10356,2786,10357,10358,10359,10360,4189,10361,10362, #10208 10363,10364,10365,10366,10367,10368,10369,10370,10371,10372,10373,10374,10375,4932,10376,10377, #10224 10378,10379,10380,10381,10382,10383,10384,10385,10386,10387,10388,10389,10390,10391,10392,4933, #10240 10393,10394,10395,4934,10396,10397,10398,10399,10400,10401,10402,10403,10404,10405,10406,10407, #10256 10408,10409,10410,10411,10412,3446,10413,10414,10415,10416,10417,10418,10419,10420,10421,10422, #10272 10423,4935,10424,10425,10426,10427,10428,10429,10430,4936,10431,10432,10433,10434,10435,10436, #10288 10437,10438,10439,10440,10441,10442,10443,4937,10444,10445,10446,10447,4481,10448,10449,10450, #10304 10451,10452,10453,10454,10455,10456,10457,10458,10459,10460,10461,10462,10463,10464,10465,10466, #10320 10467,10468,10469,10470,10471,10472,10473,10474,10475,10476,10477,10478,10479,10480,10481,10482, #10336 10483,10484,10485,10486,10487,10488,10489,10490,10491,10492,10493,10494,10495,10496,10497,10498, #10352 10499,10500,10501,10502,10503,10504,10505,4938,10506,10507,10508,10509,10510,2552,10511,10512, #10368 10513,10514,10515,10516,3447,10517,10518,10519,10520,10521,10522,10523,10524,10525,10526,10527, #10384 10528,10529,10530,10531,10532,10533,10534,10535,10536,10537,10538,10539,10540,10541,10542,10543, #10400 4482,10544,4939,10545,10546,10547,10548,10549,10550,10551,10552,10553,10554,10555,10556,10557, #10416 10558,10559,10560,10561,10562,10563,10564,10565,10566,10567,3676,4483,10568,10569,10570,10571, #10432 10572,3448,10573,10574,10575,10576,10577,10578,10579,10580,10581,10582,10583,10584,10585,10586, #10448 10587,10588,10589,10590,10591,10592,10593,10594,10595,10596,10597,10598,10599,10600,10601,10602, #10464 10603,10604,10605,10606,10607,10608,10609,10610,10611,10612,10613,10614,10615,10616,10617,10618, #10480 10619,10620,10621,10622,10623,10624,10625,10626,10627,4484,10628,10629,10630,10631,10632,4940, #10496 10633,10634,10635,10636,10637,10638,10639,10640,10641,10642,10643,10644,10645,10646,10647,10648, #10512 10649,10650,10651,10652,10653,10654,10655,10656,4941,10657,10658,10659,2599,10660,10661,10662, #10528 10663,10664,10665,10666,3089,10667,10668,10669,10670,10671,10672,10673,10674,10675,10676,10677, #10544 10678,10679,10680,4942,10681,10682,10683,10684,10685,10686,10687,10688,10689,10690,10691,10692, #10560 10693,10694,10695,10696,10697,4485,10698,10699,10700,10701,10702,10703,10704,4943,10705,3677, #10576 10706,10707,10708,10709,10710,10711,10712,4944,10713,10714,10715,10716,10717,10718,10719,10720, #10592 10721,10722,10723,10724,10725,10726,10727,10728,4945,10729,10730,10731,10732,10733,10734,10735, #10608 10736,10737,10738,10739,10740,10741,10742,10743,10744,10745,10746,10747,10748,10749,10750,10751, #10624 10752,10753,10754,10755,10756,10757,10758,10759,10760,10761,4946,10762,10763,10764,10765,10766, #10640 10767,4947,4948,10768,10769,10770,10771,10772,10773,10774,10775,10776,10777,10778,10779,10780, #10656 10781,10782,10783,10784,10785,10786,10787,10788,10789,10790,10791,10792,10793,10794,10795,10796, #10672 10797,10798,10799,10800,10801,10802,10803,10804,10805,10806,10807,10808,10809,10810,10811,10812, #10688 10813,10814,10815,10816,10817,10818,10819,10820,10821,10822,10823,10824,10825,10826,10827,10828, #10704 10829,10830,10831,10832,10833,10834,10835,10836,10837,10838,10839,10840,10841,10842,10843,10844, #10720 10845,10846,10847,10848,10849,10850,10851,10852,10853,10854,10855,10856,10857,10858,10859,10860, #10736 10861,10862,10863,10864,10865,10866,10867,10868,10869,10870,10871,10872,10873,10874,10875,10876, #10752 10877,10878,4486,10879,10880,10881,10882,10883,10884,10885,4949,10886,10887,10888,10889,10890, #10768 10891,10892,10893,10894,10895,10896,10897,10898,10899,10900,10901,10902,10903,10904,10905,10906, #10784 10907,10908,10909,10910,10911,10912,10913,10914,10915,10916,10917,10918,10919,4487,10920,10921, #10800 10922,10923,10924,10925,10926,10927,10928,10929,10930,10931,10932,4950,10933,10934,10935,10936, #10816 10937,10938,10939,10940,10941,10942,10943,10944,10945,10946,10947,10948,10949,4488,10950,10951, #10832 10952,10953,10954,10955,10956,10957,10958,10959,4190,10960,10961,10962,10963,10964,10965,10966, #10848 10967,10968,10969,10970,10971,10972,10973,10974,10975,10976,10977,10978,10979,10980,10981,10982, #10864 10983,10984,10985,10986,10987,10988,10989,10990,10991,10992,10993,10994,10995,10996,10997,10998, #10880 10999,11000,11001,11002,11003,11004,11005,11006,3960,11007,11008,11009,11010,11011,11012,11013, #10896 11014,11015,11016,11017,11018,11019,11020,11021,11022,11023,11024,11025,11026,11027,11028,11029, #10912 11030,11031,11032,4951,11033,11034,11035,11036,11037,11038,11039,11040,11041,11042,11043,11044, #10928 11045,11046,11047,4489,11048,11049,11050,11051,4952,11052,11053,11054,11055,11056,11057,11058, #10944 4953,11059,11060,11061,11062,11063,11064,11065,11066,11067,11068,11069,11070,11071,4954,11072, #10960 11073,11074,11075,11076,11077,11078,11079,11080,11081,11082,11083,11084,11085,11086,11087,11088, #10976 11089,11090,11091,11092,11093,11094,11095,11096,11097,11098,11099,11100,11101,11102,11103,11104, #10992 11105,11106,11107,11108,11109,11110,11111,11112,11113,11114,11115,3808,11116,11117,11118,11119, #11008 11120,11121,11122,11123,11124,11125,11126,11127,11128,11129,11130,11131,11132,11133,11134,4955, #11024 11135,11136,11137,11138,11139,11140,11141,11142,11143,11144,11145,11146,11147,11148,11149,11150, #11040 11151,11152,11153,11154,11155,11156,11157,11158,11159,11160,11161,4956,11162,11163,11164,11165, #11056 11166,11167,11168,11169,11170,11171,11172,11173,11174,11175,11176,11177,11178,11179,11180,4957, #11072 11181,11182,11183,11184,11185,11186,4958,11187,11188,11189,11190,11191,11192,11193,11194,11195, #11088 11196,11197,11198,11199,11200,3678,11201,11202,11203,11204,11205,11206,4191,11207,11208,11209, #11104 11210,11211,11212,11213,11214,11215,11216,11217,11218,11219,11220,11221,11222,11223,11224,11225, #11120 11226,11227,11228,11229,11230,11231,11232,11233,11234,11235,11236,11237,11238,11239,11240,11241, #11136 11242,11243,11244,11245,11246,11247,11248,11249,11250,11251,4959,11252,11253,11254,11255,11256, #11152 11257,11258,11259,11260,11261,11262,11263,11264,11265,11266,11267,11268,11269,11270,11271,11272, #11168 11273,11274,11275,11276,11277,11278,11279,11280,11281,11282,11283,11284,11285,11286,11287,11288, #11184 11289,11290,11291,11292,11293,11294,11295,11296,11297,11298,11299,11300,11301,11302,11303,11304, #11200 11305,11306,11307,11308,11309,11310,11311,11312,11313,11314,3679,11315,11316,11317,11318,4490, #11216 11319,11320,11321,11322,11323,11324,11325,11326,11327,11328,11329,11330,11331,11332,11333,11334, #11232 11335,11336,11337,11338,11339,11340,11341,11342,11343,11344,11345,11346,11347,4960,11348,11349, #11248 11350,11351,11352,11353,11354,11355,11356,11357,11358,11359,11360,11361,11362,11363,11364,11365, #11264 11366,11367,11368,11369,11370,11371,11372,11373,11374,11375,11376,11377,3961,4961,11378,11379, #11280 11380,11381,11382,11383,11384,11385,11386,11387,11388,11389,11390,11391,11392,11393,11394,11395, #11296 11396,11397,4192,11398,11399,11400,11401,11402,11403,11404,11405,11406,11407,11408,11409,11410, #11312 11411,4962,11412,11413,11414,11415,11416,11417,11418,11419,11420,11421,11422,11423,11424,11425, #11328 11426,11427,11428,11429,11430,11431,11432,11433,11434,11435,11436,11437,11438,11439,11440,11441, #11344 11442,11443,11444,11445,11446,11447,11448,11449,11450,11451,11452,11453,11454,11455,11456,11457, #11360 11458,11459,11460,11461,11462,11463,11464,11465,11466,11467,11468,11469,4963,11470,11471,4491, #11376 11472,11473,11474,11475,4964,11476,11477,11478,11479,11480,11481,11482,11483,11484,11485,11486, #11392 11487,11488,11489,11490,11491,11492,4965,11493,11494,11495,11496,11497,11498,11499,11500,11501, #11408 11502,11503,11504,11505,11506,11507,11508,11509,11510,11511,11512,11513,11514,11515,11516,11517, #11424 11518,11519,11520,11521,11522,11523,11524,11525,11526,11527,11528,11529,3962,11530,11531,11532, #11440 11533,11534,11535,11536,11537,11538,11539,11540,11541,11542,11543,11544,11545,11546,11547,11548, #11456 11549,11550,11551,11552,11553,11554,11555,11556,11557,11558,11559,11560,11561,11562,11563,11564, #11472 4193,4194,11565,11566,11567,11568,11569,11570,11571,11572,11573,11574,11575,11576,11577,11578, #11488 11579,11580,11581,11582,11583,11584,11585,11586,11587,11588,11589,11590,11591,4966,4195,11592, #11504 11593,11594,11595,11596,11597,11598,11599,11600,11601,11602,11603,11604,3090,11605,11606,11607, #11520 11608,11609,11610,4967,11611,11612,11613,11614,11615,11616,11617,11618,11619,11620,11621,11622, #11536 11623,11624,11625,11626,11627,11628,11629,11630,11631,11632,11633,11634,11635,11636,11637,11638, #11552 11639,11640,11641,11642,11643,11644,11645,11646,11647,11648,11649,11650,11651,11652,11653,11654, #11568 11655,11656,11657,11658,11659,11660,11661,11662,11663,11664,11665,11666,11667,11668,11669,11670, #11584 11671,11672,11673,11674,4968,11675,11676,11677,11678,11679,11680,11681,11682,11683,11684,11685, #11600 11686,11687,11688,11689,11690,11691,11692,11693,3809,11694,11695,11696,11697,11698,11699,11700, #11616 11701,11702,11703,11704,11705,11706,11707,11708,11709,11710,11711,11712,11713,11714,11715,11716, #11632 11717,11718,3553,11719,11720,11721,11722,11723,11724,11725,11726,11727,11728,11729,11730,4969, #11648 11731,11732,11733,11734,11735,11736,11737,11738,11739,11740,4492,11741,11742,11743,11744,11745, #11664 11746,11747,11748,11749,11750,11751,11752,4970,11753,11754,11755,11756,11757,11758,11759,11760, #11680 11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,11776, #11696 11777,11778,11779,11780,11781,11782,11783,11784,11785,11786,11787,11788,11789,11790,4971,11791, #11712 11792,11793,11794,11795,11796,11797,4972,11798,11799,11800,11801,11802,11803,11804,11805,11806, #11728 11807,11808,11809,11810,4973,11811,11812,11813,11814,11815,11816,11817,11818,11819,11820,11821, #11744 11822,11823,11824,11825,11826,11827,11828,11829,11830,11831,11832,11833,11834,3680,3810,11835, #11760 11836,4974,11837,11838,11839,11840,11841,11842,11843,11844,11845,11846,11847,11848,11849,11850, #11776 11851,11852,11853,11854,11855,11856,11857,11858,11859,11860,11861,11862,11863,11864,11865,11866, #11792 11867,11868,11869,11870,11871,11872,11873,11874,11875,11876,11877,11878,11879,11880,11881,11882, #11808 11883,11884,4493,11885,11886,11887,11888,11889,11890,11891,11892,11893,11894,11895,11896,11897, #11824 11898,11899,11900,11901,11902,11903,11904,11905,11906,11907,11908,11909,11910,11911,11912,11913, #11840 11914,11915,4975,11916,11917,11918,11919,11920,11921,11922,11923,11924,11925,11926,11927,11928, #11856 11929,11930,11931,11932,11933,11934,11935,11936,11937,11938,11939,11940,11941,11942,11943,11944, #11872 11945,11946,11947,11948,11949,4976,11950,11951,11952,11953,11954,11955,11956,11957,11958,11959, #11888 11960,11961,11962,11963,11964,11965,11966,11967,11968,11969,11970,11971,11972,11973,11974,11975, #11904 11976,11977,11978,11979,11980,11981,11982,11983,11984,11985,11986,11987,4196,11988,11989,11990, #11920 11991,11992,4977,11993,11994,11995,11996,11997,11998,11999,12000,12001,12002,12003,12004,12005, #11936 12006,12007,12008,12009,12010,12011,12012,12013,12014,12015,12016,12017,12018,12019,12020,12021, #11952 12022,12023,12024,12025,12026,12027,12028,12029,12030,12031,12032,12033,12034,12035,12036,12037, #11968 12038,12039,12040,12041,12042,12043,12044,12045,12046,12047,12048,12049,12050,12051,12052,12053, #11984 12054,12055,12056,12057,12058,12059,12060,12061,4978,12062,12063,12064,12065,12066,12067,12068, #12000 12069,12070,12071,12072,12073,12074,12075,12076,12077,12078,12079,12080,12081,12082,12083,12084, #12016 12085,12086,12087,12088,12089,12090,12091,12092,12093,12094,12095,12096,12097,12098,12099,12100, #12032 12101,12102,12103,12104,12105,12106,12107,12108,12109,12110,12111,12112,12113,12114,12115,12116, #12048 12117,12118,12119,12120,12121,12122,12123,4979,12124,12125,12126,12127,12128,4197,12129,12130, #12064 12131,12132,12133,12134,12135,12136,12137,12138,12139,12140,12141,12142,12143,12144,12145,12146, #12080 12147,12148,12149,12150,12151,12152,12153,12154,4980,12155,12156,12157,12158,12159,12160,4494, #12096 12161,12162,12163,12164,3811,12165,12166,12167,12168,12169,4495,12170,12171,4496,12172,12173, #12112 12174,12175,12176,3812,12177,12178,12179,12180,12181,12182,12183,12184,12185,12186,12187,12188, #12128 12189,12190,12191,12192,12193,12194,12195,12196,12197,12198,12199,12200,12201,12202,12203,12204, #12144 12205,12206,12207,12208,12209,12210,12211,12212,12213,12214,12215,12216,12217,12218,12219,12220, #12160 12221,4981,12222,12223,12224,12225,12226,12227,12228,12229,12230,12231,12232,12233,12234,12235, #12176 4982,12236,12237,12238,12239,12240,12241,12242,12243,12244,12245,4983,12246,12247,12248,12249, #12192 4984,12250,12251,12252,12253,12254,12255,12256,12257,12258,12259,12260,12261,12262,12263,12264, #12208 4985,12265,4497,12266,12267,12268,12269,12270,12271,12272,12273,12274,12275,12276,12277,12278, #12224 12279,12280,12281,12282,12283,12284,12285,12286,12287,4986,12288,12289,12290,12291,12292,12293, #12240 12294,12295,12296,2473,12297,12298,12299,12300,12301,12302,12303,12304,12305,12306,12307,12308, #12256 12309,12310,12311,12312,12313,12314,12315,12316,12317,12318,12319,3963,12320,12321,12322,12323, #12272 12324,12325,12326,12327,12328,12329,12330,12331,12332,4987,12333,12334,12335,12336,12337,12338, #12288 12339,12340,12341,12342,12343,12344,12345,12346,12347,12348,12349,12350,12351,12352,12353,12354, #12304 12355,12356,12357,12358,12359,3964,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369, #12320 12370,3965,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384, #12336 12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400, #12352 12401,12402,12403,12404,12405,12406,12407,12408,4988,12409,12410,12411,12412,12413,12414,12415, #12368 12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431, #12384 12432,12433,12434,12435,12436,12437,12438,3554,12439,12440,12441,12442,12443,12444,12445,12446, #12400 12447,12448,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462, #12416 12463,12464,4989,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477, #12432 12478,12479,12480,4990,12481,12482,12483,12484,12485,12486,12487,12488,12489,4498,12490,12491, #12448 12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507, #12464 12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523, #12480 12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,12535,12536,12537,12538,12539, #12496 12540,12541,12542,12543,12544,12545,12546,12547,12548,12549,12550,12551,4991,12552,12553,12554, #12512 12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570, #12528 12571,12572,12573,12574,12575,12576,12577,12578,3036,12579,12580,12581,12582,12583,3966,12584, #12544 12585,12586,12587,12588,12589,12590,12591,12592,12593,12594,12595,12596,12597,12598,12599,12600, #12560 12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616, #12576 12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632, #12592 12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,4499,12647, #12608 12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663, #12624 12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679, #12640 12680,12681,12682,12683,12684,12685,12686,12687,12688,12689,12690,12691,12692,12693,12694,12695, #12656 12696,12697,12698,4992,12699,12700,12701,12702,12703,12704,12705,12706,12707,12708,12709,12710, #12672 12711,12712,12713,12714,12715,12716,12717,12718,12719,12720,12721,12722,12723,12724,12725,12726, #12688 12727,12728,12729,12730,12731,12732,12733,12734,12735,12736,12737,12738,12739,12740,12741,12742, #12704 12743,12744,12745,12746,12747,12748,12749,12750,12751,12752,12753,12754,12755,12756,12757,12758, #12720 12759,12760,12761,12762,12763,12764,12765,12766,12767,12768,12769,12770,12771,12772,12773,12774, #12736 12775,12776,12777,12778,4993,2175,12779,12780,12781,12782,12783,12784,12785,12786,4500,12787, #12752 12788,12789,12790,12791,12792,12793,12794,12795,12796,12797,12798,12799,12800,12801,12802,12803, #12768 12804,12805,12806,12807,12808,12809,12810,12811,12812,12813,12814,12815,12816,12817,12818,12819, #12784 12820,12821,12822,12823,12824,12825,12826,4198,3967,12827,12828,12829,12830,12831,12832,12833, #12800 12834,12835,12836,12837,12838,12839,12840,12841,12842,12843,12844,12845,12846,12847,12848,12849, #12816 12850,12851,12852,12853,12854,12855,12856,12857,12858,12859,12860,12861,4199,12862,12863,12864, #12832 12865,12866,12867,12868,12869,12870,12871,12872,12873,12874,12875,12876,12877,12878,12879,12880, #12848 12881,12882,12883,12884,12885,12886,12887,4501,12888,12889,12890,12891,12892,12893,12894,12895, #12864 12896,12897,12898,12899,12900,12901,12902,12903,12904,12905,12906,12907,12908,12909,12910,12911, #12880 12912,4994,12913,12914,12915,12916,12917,12918,12919,12920,12921,12922,12923,12924,12925,12926, #12896 12927,12928,12929,12930,12931,12932,12933,12934,12935,12936,12937,12938,12939,12940,12941,12942, #12912 12943,12944,12945,12946,12947,12948,12949,12950,12951,12952,12953,12954,12955,12956,1772,12957, #12928 12958,12959,12960,12961,12962,12963,12964,12965,12966,12967,12968,12969,12970,12971,12972,12973, #12944 12974,12975,12976,12977,12978,12979,12980,12981,12982,12983,12984,12985,12986,12987,12988,12989, #12960 12990,12991,12992,12993,12994,12995,12996,12997,4502,12998,4503,12999,13000,13001,13002,13003, #12976 4504,13004,13005,13006,13007,13008,13009,13010,13011,13012,13013,13014,13015,13016,13017,13018, #12992 13019,13020,13021,13022,13023,13024,13025,13026,13027,13028,13029,3449,13030,13031,13032,13033, #13008 13034,13035,13036,13037,13038,13039,13040,13041,13042,13043,13044,13045,13046,13047,13048,13049, #13024 13050,13051,13052,13053,13054,13055,13056,13057,13058,13059,13060,13061,13062,13063,13064,13065, #13040 13066,13067,13068,13069,13070,13071,13072,13073,13074,13075,13076,13077,13078,13079,13080,13081, #13056 13082,13083,13084,13085,13086,13087,13088,13089,13090,13091,13092,13093,13094,13095,13096,13097, #13072 13098,13099,13100,13101,13102,13103,13104,13105,13106,13107,13108,13109,13110,13111,13112,13113, #13088 13114,13115,13116,13117,13118,3968,13119,4995,13120,13121,13122,13123,13124,13125,13126,13127, #13104 4505,13128,13129,13130,13131,13132,13133,13134,4996,4506,13135,13136,13137,13138,13139,4997, #13120 13140,13141,13142,13143,13144,13145,13146,13147,13148,13149,13150,13151,13152,13153,13154,13155, #13136 13156,13157,13158,13159,4998,13160,13161,13162,13163,13164,13165,13166,13167,13168,13169,13170, #13152 13171,13172,13173,13174,13175,13176,4999,13177,13178,13179,13180,13181,13182,13183,13184,13185, #13168 13186,13187,13188,13189,13190,13191,13192,13193,13194,13195,13196,13197,13198,13199,13200,13201, #13184 13202,13203,13204,13205,13206,5000,13207,13208,13209,13210,13211,13212,13213,13214,13215,13216, #13200 13217,13218,13219,13220,13221,13222,13223,13224,13225,13226,13227,4200,5001,13228,13229,13230, #13216 13231,13232,13233,13234,13235,13236,13237,13238,13239,13240,3969,13241,13242,13243,13244,3970, #13232 13245,13246,13247,13248,13249,13250,13251,13252,13253,13254,13255,13256,13257,13258,13259,13260, #13248 13261,13262,13263,13264,13265,13266,13267,13268,3450,13269,13270,13271,13272,13273,13274,13275, #13264 13276,5002,13277,13278,13279,13280,13281,13282,13283,13284,13285,13286,13287,13288,13289,13290, #13280 13291,13292,13293,13294,13295,13296,13297,13298,13299,13300,13301,13302,3813,13303,13304,13305, #13296 13306,13307,13308,13309,13310,13311,13312,13313,13314,13315,13316,13317,13318,13319,13320,13321, #13312 13322,13323,13324,13325,13326,13327,13328,4507,13329,13330,13331,13332,13333,13334,13335,13336, #13328 13337,13338,13339,13340,13341,5003,13342,13343,13344,13345,13346,13347,13348,13349,13350,13351, #13344 13352,13353,13354,13355,13356,13357,13358,13359,13360,13361,13362,13363,13364,13365,13366,13367, #13360 5004,13368,13369,13370,13371,13372,13373,13374,13375,13376,13377,13378,13379,13380,13381,13382, #13376 13383,13384,13385,13386,13387,13388,13389,13390,13391,13392,13393,13394,13395,13396,13397,13398, #13392 13399,13400,13401,13402,13403,13404,13405,13406,13407,13408,13409,13410,13411,13412,13413,13414, #13408 13415,13416,13417,13418,13419,13420,13421,13422,13423,13424,13425,13426,13427,13428,13429,13430, #13424 13431,13432,4508,13433,13434,13435,4201,13436,13437,13438,13439,13440,13441,13442,13443,13444, #13440 13445,13446,13447,13448,13449,13450,13451,13452,13453,13454,13455,13456,13457,5005,13458,13459, #13456 13460,13461,13462,13463,13464,13465,13466,13467,13468,13469,13470,4509,13471,13472,13473,13474, #13472 13475,13476,13477,13478,13479,13480,13481,13482,13483,13484,13485,13486,13487,13488,13489,13490, #13488 13491,13492,13493,13494,13495,13496,13497,13498,13499,13500,13501,13502,13503,13504,13505,13506, #13504 13507,13508,13509,13510,13511,13512,13513,13514,13515,13516,13517,13518,13519,13520,13521,13522, #13520 13523,13524,13525,13526,13527,13528,13529,13530,13531,13532,13533,13534,13535,13536,13537,13538, #13536 13539,13540,13541,13542,13543,13544,13545,13546,13547,13548,13549,13550,13551,13552,13553,13554, #13552 13555,13556,13557,13558,13559,13560,13561,13562,13563,13564,13565,13566,13567,13568,13569,13570, #13568 13571,13572,13573,13574,13575,13576,13577,13578,13579,13580,13581,13582,13583,13584,13585,13586, #13584 13587,13588,13589,13590,13591,13592,13593,13594,13595,13596,13597,13598,13599,13600,13601,13602, #13600 13603,13604,13605,13606,13607,13608,13609,13610,13611,13612,13613,13614,13615,13616,13617,13618, #13616 13619,13620,13621,13622,13623,13624,13625,13626,13627,13628,13629,13630,13631,13632,13633,13634, #13632 13635,13636,13637,13638,13639,13640,13641,13642,5006,13643,13644,13645,13646,13647,13648,13649, #13648 13650,13651,5007,13652,13653,13654,13655,13656,13657,13658,13659,13660,13661,13662,13663,13664, #13664 13665,13666,13667,13668,13669,13670,13671,13672,13673,13674,13675,13676,13677,13678,13679,13680, #13680 13681,13682,13683,13684,13685,13686,13687,13688,13689,13690,13691,13692,13693,13694,13695,13696, #13696 13697,13698,13699,13700,13701,13702,13703,13704,13705,13706,13707,13708,13709,13710,13711,13712, #13712 13713,13714,13715,13716,13717,13718,13719,13720,13721,13722,13723,13724,13725,13726,13727,13728, #13728 13729,13730,13731,13732,13733,13734,13735,13736,13737,13738,13739,13740,13741,13742,13743,13744, #13744 13745,13746,13747,13748,13749,13750,13751,13752,13753,13754,13755,13756,13757,13758,13759,13760, #13760 13761,13762,13763,13764,13765,13766,13767,13768,13769,13770,13771,13772,13773,13774,3273,13775, #13776 13776,13777,13778,13779,13780,13781,13782,13783,13784,13785,13786,13787,13788,13789,13790,13791, #13792 13792,13793,13794,13795,13796,13797,13798,13799,13800,13801,13802,13803,13804,13805,13806,13807, #13808 13808,13809,13810,13811,13812,13813,13814,13815,13816,13817,13818,13819,13820,13821,13822,13823, #13824 13824,13825,13826,13827,13828,13829,13830,13831,13832,13833,13834,13835,13836,13837,13838,13839, #13840 13840,13841,13842,13843,13844,13845,13846,13847,13848,13849,13850,13851,13852,13853,13854,13855, #13856 13856,13857,13858,13859,13860,13861,13862,13863,13864,13865,13866,13867,13868,13869,13870,13871, #13872 13872,13873,13874,13875,13876,13877,13878,13879,13880,13881,13882,13883,13884,13885,13886,13887, #13888 13888,13889,13890,13891,13892,13893,13894,13895,13896,13897,13898,13899,13900,13901,13902,13903, #13904 13904,13905,13906,13907,13908,13909,13910,13911,13912,13913,13914,13915,13916,13917,13918,13919, #13920 13920,13921,13922,13923,13924,13925,13926,13927,13928,13929,13930,13931,13932,13933,13934,13935, #13936 13936,13937,13938,13939,13940,13941,13942,13943,13944,13945,13946,13947,13948,13949,13950,13951, #13952 13952,13953,13954,13955,13956,13957,13958,13959,13960,13961,13962,13963,13964,13965,13966,13967, #13968 13968,13969,13970,13971,13972) #13973 # flake8: noqa
mit
peterbarker/ardupilot-1
mk/PX4/Tools/genmsg/src/genmsg/srvs.py
216
3017
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, 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 Willow Garage, 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. """ ROS Service Description Language Spec Implements http://ros.org/wiki/srv """ import os import sys from . names import is_legal_resource_name, is_legal_resource_base_name, package_resource_name, resource_name class SrvSpec(object): def __init__(self, request, response, text, full_name = '', short_name = '', package = ''): alt_package, alt_short_name = package_resource_name(full_name) if not package: package = alt_package if not short_name: short_name = alt_short_name self.request = request self.response = response self.text = text self.full_name = full_name self.short_name = short_name self.package = package def __eq__(self, other): if not other or not isinstance(other, SrvSpec): return False return self.request == other.request and \ self.response == other.response and \ self.text == other.text and \ self.full_name == other.full_name and \ self.short_name == other.short_name and \ self.package == other.package def __ne__(self, other): if not other or not isinstance(other, SrvSpec): return True return not self.__eq__(other) def __repr__(self): return "SrvSpec[%s, %s]"%(repr(self.request), repr(self.response))
gpl-3.0
rivy/xbmc-script.audio.pandora
resources/lib/pithos/pandora/blowfish.py
5
19552
# # blowfish.py # Copyright (C) 2002 Michael Gilfix <mgilfix@eecs.tufts.edu> # # This module is open source; you can redistribute it and/or # modify it under the terms of the GPL or Artistic License. # These licenses are available at http://www.opensource.org # # This software must be used and distributed in accordance # with the law. The author claims no liability for its # misuse. # # 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. # """ Blowfish Encryption This module is a pure python implementation of Bruce Schneier's encryption scheme 'Blowfish'. Blowish is a 16-round Feistel Network cipher and offers substantial speed gains over DES. The key is a string of length anywhere between 64 and 448 bits, or equivalently 8 and 56 bytes. The encryption and decryption functions operate on 64-bit blocks, or 8 byte strings. Send questions, comments, bugs my way: Michael Gilfix <mgilfix@eecs.tufts.edu> """ __author__ = "Michael Gilfix <mgilfix@eecs.tufts.edu>" class Blowfish: """Blowfish encryption Scheme This class implements the encryption and decryption functionality of the Blowfish cipher. Public functions: def __init__ (self, key) Creates an instance of blowfish using 'key' as the encryption key. Key is a string of length ranging from 8 to 56 bytes (64 to 448 bits). Once the instance of the object is created, the key is no longer necessary. def encrypt (self, data): Encrypt an 8 byte (64-bit) block of text where 'data' is an 8 byte string. Returns an 8-byte encrypted string. def decrypt (self, data): Decrypt an 8 byte (64-bit) encrypted block of text, where 'data' is the 8 byte encrypted string. Returns an 8-byte string of plaintext. def cipher (self, xl, xr, direction): Encrypts a 64-bit block of data where xl is the upper 32-bits and xr is the lower 32-bits. 'direction' is the direction to apply the cipher, either ENCRYPT or DECRYPT constants. returns a tuple of either encrypted or decrypted data of the left half and right half of the 64-bit block. Private members: def __round_func (self, xl) Performs an obscuring function on the 32-bit block of data 'xl', which is the left half of the 64-bit block of data. Returns the 32-bit result as a long integer. """ # Cipher directions ENCRYPT = 0 DECRYPT = 1 # For the __round_func modulus = long (2) ** 32 def __init__ (self, key): if not key or len (key) < 8 or len (key) > 56: raise RuntimeError, "Attempted to initialize Blowfish cipher with key of invalid length: %s" %len (key) self.p_boxes = [ 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, 0x9216D5D9, 0x8979FB1B ] self.s_boxes = [ [ 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A ], [ 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 ], [ 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 ], [ 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 ] ] # Cycle through the p-boxes and round-robin XOR the # key with the p-boxes key_len = len (key) index = 0 for i in range (len (self.p_boxes)): val = (ord (key[index % key_len]) << 24) + \ (ord (key[(index + 1) % key_len]) << 16) + \ (ord (key[(index + 2) % key_len]) << 8) + \ ord (key[(index + 3) % key_len]) self.p_boxes[i] = self.p_boxes[i] ^ val index = index + 4 # For the chaining process l, r = 0, 0 # Begin chain replacing the p-boxes for i in range (0, len (self.p_boxes), 2): l, r = self.cipher (l, r, self.ENCRYPT) self.p_boxes[i] = l self.p_boxes[i + 1] = r # Chain replace the s-boxes for i in range (len (self.s_boxes)): for j in range (0, len (self.s_boxes[i]), 2): l, r = self.cipher (l, r, self.ENCRYPT) self.s_boxes[i][j] = l self.s_boxes[i][j + 1] = r def cipher (self, xl, xr, direction): if direction == self.ENCRYPT: for i in range (16): xl = xl ^ self.p_boxes[i] xr = self.__round_func (xl) ^ xr xl, xr = xr, xl xl, xr = xr, xl xr = xr ^ self.p_boxes[16] xl = xl ^ self.p_boxes[17] else: for i in range (17, 1, -1): xl = xl ^ self.p_boxes[i] xr = self.__round_func (xl) ^ xr xl, xr = xr, xl xl, xr = xr, xl xr = xr ^ self.p_boxes[1] xl = xl ^ self.p_boxes[0] return xl, xr def __round_func (self, xl): a = (xl & 0xFF000000) >> 24 b = (xl & 0x00FF0000) >> 16 c = (xl & 0x0000FF00) >> 8 d = xl & 0x000000FF # Perform all ops as longs then and out the last 32-bits to # obtain the integer f = (long (self.s_boxes[0][a]) + long (self.s_boxes[1][b])) % self.modulus f = f ^ long (self.s_boxes[2][c]) f = f + long (self.s_boxes[3][d]) f = (f % self.modulus) & 0xFFFFFFFF return f def encrypt (self, data): if not len (data) == 8: raise RuntimeError, "Attempted to encrypt data of invalid block length: %s" %len (data) # Use big endianess since that's what everyone else uses xl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) xr = ord (data[7]) | (ord (data[6]) << 8) | (ord (data[5]) << 16) | (ord (data[4]) << 24) cl, cr = self.cipher (xl, xr, self.ENCRYPT) chars = ''.join ([ chr ((cl >> 24) & 0xFF), chr ((cl >> 16) & 0xFF), chr ((cl >> 8) & 0xFF), chr (cl & 0xFF), chr ((cr >> 24) & 0xFF), chr ((cr >> 16) & 0xFF), chr ((cr >> 8) & 0xFF), chr (cr & 0xFF) ]) return chars def decrypt (self, data): if not len (data) == 8: raise RuntimeError, "Attempted to encrypt data of invalid block length: %s" %len (data) # Use big endianess since that's what everyone else uses cl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) cr = ord (data[7]) | (ord (data[6]) << 8) | (ord (data[5]) << 16) | (ord (data[4]) << 24) xl, xr = self.cipher (cl, cr, self.DECRYPT) chars = ''.join ([ chr ((xl >> 24) & 0xFF), chr ((xl >> 16) & 0xFF), chr ((xl >> 8) & 0xFF), chr (xl & 0xFF), chr ((xr >> 24) & 0xFF), chr ((xr >> 16) & 0xFF), chr ((xr >> 8) & 0xFF), chr (xr & 0xFF) ]) return chars def blocksize (self): return 8 def key_length (self): return 56 def key_bits (self): return 56 * 8
gpl-3.0
caioserra/apiAdwords
tests/adspygoogle/adwords/examples/basic_operations_unittest.py
2
5729
#!/usr/bin/python # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests to cover Basic Operations examples.""" __author__ = 'api.kwinter@gmail.com (Kevin Winter)' import os import sys sys.path.insert(0, os.path.join('..', '..', '..', '..')) import time import unittest from examples.adspygoogle.adwords.v201309.basic_operations import add_ad_groups from examples.adspygoogle.adwords.v201309.basic_operations import add_campaigns from examples.adspygoogle.adwords.v201309.basic_operations import add_keywords from examples.adspygoogle.adwords.v201309.basic_operations import add_text_ads from examples.adspygoogle.adwords.v201309.basic_operations import delete_ad from examples.adspygoogle.adwords.v201309.basic_operations import delete_ad_group from examples.adspygoogle.adwords.v201309.basic_operations import delete_campaign from examples.adspygoogle.adwords.v201309.basic_operations import delete_keyword from examples.adspygoogle.adwords.v201309.basic_operations import get_ad_groups from examples.adspygoogle.adwords.v201309.basic_operations import get_campaigns from examples.adspygoogle.adwords.v201309.basic_operations import get_campaigns_with_awql from examples.adspygoogle.adwords.v201309.basic_operations import get_keywords from examples.adspygoogle.adwords.v201309.basic_operations import get_text_ads from examples.adspygoogle.adwords.v201309.basic_operations import pause_ad from examples.adspygoogle.adwords.v201309.basic_operations import update_ad_group from examples.adspygoogle.adwords.v201309.basic_operations import update_campaign from examples.adspygoogle.adwords.v201309.basic_operations import update_keyword from tests.adspygoogle.adwords import client from tests.adspygoogle.adwords import SERVER_V201309 from tests.adspygoogle.adwords import TEST_VERSION_V201309 from tests.adspygoogle.adwords import util from tests.adspygoogle.adwords import VERSION_V201309 class BasicOperations(unittest.TestCase): """Unittest suite for Account Management code examples.""" SERVER = SERVER_V201309 VERSION = VERSION_V201309 client.debug = False loaded = False def setUp(self): """Prepare unittest.""" time.sleep(5) client.use_mcc = False if not self.__class__.loaded: self.__class__.campaign_id = util.CreateTestCampaign( client) self.__class__.ad_group_id = util.CreateTestAdGroup( client, self.__class__.campaign_id) self.__class__.ad_id = util.CreateTestAd(client, self.__class__.ad_group_id) self.__class__.keyword_id = util.CreateTestKeyword( client, self.__class__.ad_group_id) self.__class__.loaded = True def testAddAdGroups(self): """Tests whether we can add ad groups.""" add_ad_groups.main(client, self.__class__.campaign_id) def testAddCampaigns(self): """Tests whether we can add campaigns.""" add_campaigns.main(client) def testAddKeywords(self): """Tests whether we can add keywords.""" add_keywords.main(client, self.__class__.ad_group_id) def testAddTextAds(self): """Tests whether we can add text ads.""" add_text_ads.main(client, self.__class__.ad_group_id) def testGetAdGroups(self): """Tests whether we can get ad groups.""" get_ad_groups.main(client, self.__class__.campaign_id) def testGetCampaigns(self): """Tests whether we can get campaigns.""" get_campaigns.main(client) def testGetCampaignsWithAwql(self): """Tests whether we can get campaigns with awql.""" get_campaigns_with_awql.main(client) def testGetKeywords(self): """Tests whether we can get keywords.""" get_keywords.main(client) def testGetTextAds(self): """Tests whether we can get text ads.""" get_text_ads.main(client, self.__class__.ad_group_id) def testUpdateAdGroup(self): """Tests whether we can update an ad group.""" update_ad_group.main(client, self.__class__.ad_group_id) def testUpdateCampaign(self): """Tests whether we can update a campaign.""" update_campaign.main(client, self.__class__.campaign_id) def testUpdateKeyword(self): """Tests whether we can update a keyword.""" update_keyword.main(client, self.__class__.ad_group_id, self.__class__.keyword_id) def testPauseAd(self): """Tests whether we can pause an ad.""" pause_ad.main(client, self.__class__.ad_group_id, self.__class__.ad_id) def testZDeleteAd(self): """Tests whether we can delete an ad.""" delete_ad.main(client, self.__class__.ad_group_id, self.__class__.ad_id) def testZDeleteKeyword(self): """Tests whether we can delete a keyword.""" delete_keyword.main(client, self.__class__.ad_group_id, self.__class__.keyword_id) def testZDeleteAdGroup(self): """Tests whether we can delete an ad group.""" delete_ad_group.main(client, self.__class__.ad_group_id) def testZDeleteCampaign(self): """Tests whether we can delete a campaign.""" delete_campaign.main(client, self.__class__.campaign_id) if __name__ == '__main__': if TEST_VERSION_V201309: unittest.main()
apache-2.0
vinodkc/spark
examples/src/main/python/ml/vector_slicer_example.py
27
1496
# # 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. # # $example on$ from pyspark.ml.feature import VectorSlicer from pyspark.ml.linalg import Vectors from pyspark.sql.types import Row # $example off$ from pyspark.sql import SparkSession if __name__ == "__main__": spark = SparkSession\ .builder\ .appName("VectorSlicerExample")\ .getOrCreate() # $example on$ df = spark.createDataFrame([ Row(userFeatures=Vectors.sparse(3, {0: -2.0, 1: 2.3})), Row(userFeatures=Vectors.dense([-2.0, 2.3, 0.0]))]) slicer = VectorSlicer(inputCol="userFeatures", outputCol="features", indices=[1]) output = slicer.transform(df) output.select("userFeatures", "features").show() # $example off$ spark.stop()
apache-2.0
ARPA-SIMC/arkimet
python/tests/test_scan_odimh5.py
1
14226
import unittest import os import arkimet as arki import datetime class TestScanODIMH5(unittest.TestCase): def read(self, pathname, size, format="odimh5"): """ Read all the metadata from a file """ ds = arki.dataset.Reader({ "format": format, "name": os.path.basename(pathname), "path": pathname, "type": "file", }) mds = ds.query_data() self.assertEqual(len(mds), 1) md = mds[0] source = md.to_python("source") self.assertEqual(source, { "type": "source", "style": "BLOB", "format": "odimh5", "basedir": os.getcwd(), "file": pathname, "offset": 0, "size": size, }) data = md.data self.assertEqual(len(data), size) self.assertEqual(data[1:4], b"HDF") notes = md.get_notes() self.assertEqual(len(notes), 1) self.assertEqual(notes[0]["type"], "note") self.assertEqual(notes[0]["value"], "Scanned from {}".format(os.path.basename(pathname))) self.assertIsInstance(notes[0]["time"], datetime.datetime) return md def test_pvol(self): """ Scan an ODIMH5 polar volume """ md = self.read("inbound/odimh5/PVOL_v20.h5", 320696) self.assertEqual(md["origin"], "ODIMH5(wmo, rad, plc)") self.assertEqual(md["product"], "ODIMH5(PVOL, SCAN)") self.assertEqual(md["level"], "ODIMH5(0, 27)") self.assertEqual(md["task"], "task") self.assertEqual(md["quantity"], "ACRR, BRDR, CLASS, DBZH, DBZV, HGHT, KDP, LDR, PHIDP, QIND, RATE, RHOHV," " SNR, SQI, TH, TV, UWND, VIL, VRAD, VWND, WRAD, ZDR, ad, ad_dev, chi2," " dbz, dbz_dev, dd, dd_dev, def, def_dev, div, div_dev, ff, ff_dev, n," " rhohv, rhohv_dev, w, w_dev, z, z_dev") self.assertEqual(md["area"], "ODIMH5(lat=44456700, lon=11623600, radius=1000)") self.assertEqual(md["reftime"], "2000-01-02T03:04:05Z") self.assertNotIn("run", md) self.assertNotIn("timerange", md) def test_pvol_without_how(self): """ Scan an ODIMH5 polar volume without how group """ md = self.read("inbound/odimh5/ZOUFPLAN.h5", 516709) self.assertEqual(md["origin"], "ODIMH5(16106, , )") self.assertEqual(md["product"], "ODIMH5(PVOL, SCAN)") self.assertEqual(md["level"], "ODIMH5(-0.2, 16)") self.assertEqual(md["task"], "DPC Standard Scan") self.assertEqual(md["quantity"], "DBZH, QIND, VRAD") self.assertEqual(md["area"], "ODIMH5(lat=46562500, lon=12970300, radius=0)") self.assertEqual(md["reftime"], "2020-05-29T15:30:00Z") self.assertNotIn("run", md) self.assertNotIn("timerange", md) def test_time_without_seconds(self): md = self.read("inbound/odimh5/000461.odimh5", 458556) self.assertEqual(md["reftime"], "2020-05-30T04:40:00Z") def test_comp_cappi(self): md = self.read("inbound/odimh5/COMP_CAPPI_v20.h5", 49113) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(COMP, CAPPI)") self.assertEqual(md["level"], "GRIB1(105, 00010)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") def test_comp_etop(self): md = self.read("inbound/odimh5/COMP_ETOP_v20.h5", 49113) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(COMP, ETOP)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "HGHT") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("level", md) def test_comp_lbm(self): md = self.read("inbound/odimh5/COMP_LBM_v20.h5", 49057) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(COMP, NEW:LBM_ARPA)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("level", md) def test_comp_max(self): md = self.read("inbound/odimh5/COMP_MAX_v20.h5", 49049) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(COMP, MAX)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("level", md) def test_comp_pcappi(self): md = self.read("inbound/odimh5/COMP_PCAPPI_v20.h5", 49113) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(COMP, PCAPPI)") self.assertEqual(md["level"], "GRIB1(105, 00010)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") def test_comp_ppi(self): md = self.read("inbound/odimh5/COMP_PPI_v20.h5", 49113) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(COMP, PPI)") self.assertEqual(md["level"], "ODIMH5(10, 10)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") def test_comp_rr(self): md = self.read("inbound/odimh5/COMP_RR_v20.h5", 49049) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(COMP, RR)") self.assertEqual(md["timerange"], "Timedef(0s, 1, 3600s)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "ACRR") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("level", md) def test_comp_vil(self): md = self.read("inbound/odimh5/COMP_VIL_v20.h5", 49097) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(COMP, VIL)") self.assertEqual(md["level"], "GRIB1(106, 010, 000)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "VIL") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("timerange", md) def test_image_cappi(self): md = self.read("inbound/odimh5/IMAGE_CAPPI_v20.h5", 49113) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(IMAGE, CAPPI)") self.assertEqual(md["level"], "GRIB1(105, 00500)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("timerange", md) def test_image_etop(self): md = self.read("inbound/odimh5/IMAGE_ETOP_v20.h5", 49113) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(IMAGE, ETOP)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "HGHT") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("level", md) def test_image_hvmi(self): md = self.read("inbound/odimh5/IMAGE_HVMI_v20.h5", 68777) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(IMAGE, HVMI)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("level", md) def test_image_max(self): md = self.read("inbound/odimh5/IMAGE_MAX_v20.h5", 49049) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(IMAGE, MAX)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("level", md) def test_image_pcappi(self): md = self.read("inbound/odimh5/IMAGE_PCAPPI_v20.h5", 49113) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(IMAGE, PCAPPI)") self.assertEqual(md["level"], "GRIB1(105, 00500)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") def test_image_ppi(self): md = self.read("inbound/odimh5/IMAGE_PPI_v20.h5", 49113) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(IMAGE, PPI)") self.assertEqual(md["level"], "ODIMH5(0.5, 0.5)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") def test_image_rr(self): md = self.read("inbound/odimh5/IMAGE_RR_v20.h5", 49049) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(IMAGE, RR)") self.assertEqual(md["timerange"], "Timedef(0s, 1, 3600s)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "ACRR") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("level", md) def test_image_vil(self): md = self.read("inbound/odimh5/IMAGE_VIL_v20.h5", 49097) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(IMAGE, VIL)") self.assertEqual(md["level"], "GRIB1(106, 010, 000)") self.assertEqual(md["reftime"], "2013-03-18T14:30:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "VIL") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") def test_image_zlr_bb(self): md = self.read("inbound/odimh5/IMAGE_ZLR-BB_v20.h5", 62161) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(IMAGE, NEW:LBM_ARPA)") self.assertEqual(md["reftime"], "2013-03-18T10:00:00Z") self.assertEqual(md["task"], "ZLR-BB") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=42314117, latlast=46912151, lonfirst=8273203, lonlast=14987079, type=0)") self.assertNotIn("level", md) def test_xsec(self): md = self.read("inbound/odimh5/XSEC_v21.h5", 19717) self.assertEqual(md["origin"], "ODIMH5(16144, IY46, itspc)") self.assertEqual(md["product"], "ODIMH5(XSEC, XSEC)") self.assertEqual(md["reftime"], "2013-11-04T14:10:00Z") self.assertEqual(md["task"], "XZS") self.assertEqual(md["quantity"], "DBZH") self.assertEqual(md["area"], "GRIB(latfirst=44320636, latlast=44821945, lonfirst=11122189, lonlast=12546566, type=0)") self.assertNotIn("level", md) def test_empty(self): """ Check that the scanner silently discard an empty file """ ds = arki.dataset.Reader({ "format": "odimh5", "name": "empty.h5", "path": "inbound/odimh5/empty.h5", "type": "file", }) mds = ds.query_data() self.assertEqual(len(mds), 0)
gpl-2.0
garyjs/Newfiesautodialer
newfies/dialer_audio/views.py
3
6471
# # Newfies-Dialer License # http://www.newfies-dialer.org # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-2013 Star2Billing S.L. # # The Initial Developer of the Original Code is # Arezqui Belaid <info@star2billing.com> # from django.conf import settings from django.contrib.sites.models import Site from django.contrib.auth.decorators import login_required, \ permission_required from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render_to_response, get_object_or_404 from django.template.context import RequestContext from django.utils.translation import ugettext as _ from dialer_audio.constants import AUDIO_COLUMN_NAME from dialer_audio.forms import DialerAudioFileForm from audiofield.models import AudioFile from common.common_functions import current_view, get_pagination_vars import os.path @permission_required('audiofield.view_audio', login_url='/') @login_required def audio_list(request): """AudioFile list for the logged in user **Attributes**: * ``template`` - frontend/audio/audio_list.html **Logic Description**: * List all audios which belong to the logged in user. """ sort_col_field_list = ['id', 'name', 'updated_date'] default_sort_field = 'id' pagination_data =\ get_pagination_vars(request, sort_col_field_list, default_sort_field) PAGE_SIZE = pagination_data['PAGE_SIZE'] sort_order = pagination_data['sort_order'] audio_list = AudioFile.objects.filter(user=request.user).order_by(sort_order) domain = Site.objects.get_current().domain template = 'frontend/audio/audio_list.html' data = { 'module': current_view(request), 'audio_list': audio_list, 'total_audio': audio_list.count(), 'PAGE_SIZE': PAGE_SIZE, 'AUDIO_COLUMN_NAME': AUDIO_COLUMN_NAME, 'col_name_with_order': pagination_data['col_name_with_order'], 'domain': domain, 'msg': request.session.get('msg'), 'AUDIO_DEBUG': settings.AUDIO_DEBUG, } request.session['msg'] = '' request.session['error_msg'] = '' return render_to_response(template, data, context_instance=RequestContext(request)) @permission_required('audiofield.add_audiofile', login_url='/') @login_required def audio_add(request): """Add new Audio for the logged in user **Attributes**: * ``form`` - SurveyCustomerAudioFileForm * ``template`` - frontend/audio/audio_change.html **Logic Description**: * Add a new audio which will belong to the logged in user via the CustomerAudioFileForm & get redirected to the audio list """ form = DialerAudioFileForm() if request.method == 'POST': form = DialerAudioFileForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() request.session["msg"] = _('"%(name)s" added.') %\ {'name': request.POST['name']} return HttpResponseRedirect('/audio/') template = 'frontend/audio/audio_change.html' data = { 'module': current_view(request), 'form': form, 'action': 'add', 'AUDIO_DEBUG': settings.AUDIO_DEBUG, } return render_to_response(template, data, context_instance=RequestContext(request)) def delete_audio_file(obj): """Delete audio file from computer drive""" if obj.audio_file: if os.path.exists(obj.audio_file.path): os.remove(obj.audio_file.path) return True @permission_required('audiofield.delete_audiofile', login_url='/') @login_required def audio_del(request, object_id): """Delete a audio for a logged in user **Attributes**: * ``object_id`` - Selected audio object * ``object_list`` - Selected audio objects **Logic Description**: * Delete selected the audio from the audio list """ if int(object_id) != 0: audio = get_object_or_404( AudioFile, pk=int(object_id), user=request.user) request.session["msg"] = \ _('"%(name)s" is deleted.') % {'name': audio.name} # 1) remove audio file from drive delete_audio_file(audio) # 2) delete audio audio.delete() else: try: # When object_id is 0 (Multiple records delete) values = request.POST.getlist('select') values = ", ".join(["%s" % el for el in values]) audio_list = AudioFile.objects\ .filter(user=request.user)\ .extra(where=['id IN (%s)' % values]) request.session["msg"] = _('%(count)s audio(s) are deleted.')\ % {'count': audio_list.count()} # 1) remove audio file from drive for audio in audio_list: delete_audio_file(audio) # 2) delete audio audio_list.delete() except: raise Http404 return HttpResponseRedirect('/audio/') @permission_required('audiofield.change_audiofile', login_url='/') @login_required def audio_change(request, object_id): """Update Audio for the logged in user **Attributes**: * ``form`` - SurveyCustomerAudioFileForm * ``template`` - frontend/audio/audio_change.html **Logic Description**: * Update audio which is belong to the logged in user via the CustomerAudioFileForm & get redirected to the audio list """ obj = get_object_or_404(AudioFile, pk=object_id, user=request.user) form = DialerAudioFileForm(instance=obj) if request.method == 'POST': if request.POST.get('delete'): return HttpResponseRedirect('/audio/del/%s/' % object_id) form = DialerAudioFileForm( request.POST, request.FILES, instance=obj) if form.is_valid(): form.save() return HttpResponseRedirect('/audio/') template = 'frontend/audio/audio_change.html' data = { 'form': form, 'module': current_view(request), 'action': 'update', 'AUDIO_DEBUG': settings.AUDIO_DEBUG, } return render_to_response(template, data, context_instance=RequestContext(request))
mpl-2.0
kohnle-lernmodule/exe201based
exe/engine/orientacionestutoriafpdidevice.py
11
6130
#!/usr/bin/python # -*- coding: utf-8 -*- # =========================================================================== # iDevice Orientaciones tutoria creado para la FPD por José Ramón Jiménez Reyes # =========================================================================== """ FPD - Guidelines Teacher Orientaciones tutoria iDevice """ import logging from exe.engine.idevice import Idevice from exe.engine.translate import lateTranslate from exe.engine.field import TextAreaField import re log = logging.getLogger(__name__) # =========================================================================== class OrientacionestutoriafpdIdevice(Idevice): """ El iDevice Orientaciones tutoria permite al profesorado conocer los objetivos del aprendizje del alumnado """ persistenceVersion = 9 def __init__(self, activity = "", answer = ""): """ Initialize """ Idevice.__init__(self, x_(u"FPD - Guidelines Teacher"), x_(u"Jose Ramon Jimenez Reyes"), x_(u"""Guidelines Teacher is an iDevice that lets the teacher know the learning objectives of the students."""), u"", u"orientacionesfpd") # self.emphasis = Idevice.SomeEmphasis self.emphasis = "_orientacionesfpd" self._activityInstruc = x_(u"""Enter the text that will appear on this iDevice""") self.systemResources += ["common.js"] self.activityTextArea = TextAreaField(x_(u'Guidelines Teacher Text'), self._activityInstruc, activity) self.activityTextArea.idevice = self # Properties activityInstruc = lateTranslate('activityInstruc') def getResourcesField(self, this_resource): """ implement the specific resource finding mechanism for this iDevice: """ # be warned that before upgrading, this iDevice field could not exist: if hasattr(self, 'activityTextArea')\ and hasattr(self.activityTextArea, 'images'): for this_image in self.activityTextArea.images: if hasattr(this_image, '_imageResource') \ and this_resource == this_image._imageResource: return self.activityTextArea return None def getRichTextFields(self): fields_list = [] if hasattr(self, 'activityTextArea'): fields_list.append(self.activityTextArea) return fields_list def burstHTML(self, i): # Parasabermasfpd Idevice: title = i.find(name='span', attrs={'class' : 'iDeviceTitle' }) self.title = title.renderContents().decode('utf-8') reflections = i.findAll(name='div', attrs={'id' : re.compile('^ta') }) # should be exactly two of these: # 1st = field[0] == Activity if len(reflections) >= 1: self.activityTextArea.content_wo_resourcePaths = \ reflections[0].renderContents().decode('utf-8') # and add the LOCAL resource paths back in: self.activityTextArea.content_w_resourcePaths = \ self.activityTextArea.MassageResourceDirsIntoContent( \ self.activityTextArea.content_wo_resourcePaths) self.activityTextArea.content = \ self.activityTextArea.content_w_resourcePaths def upgradeToVersion1(self): """ Upgrades the node from version 0 to 1. """ log.debug(u"Upgrading iDevice") self.icon = u"orientacionesfpd" def upgradeToVersion2(self): """ Upgrades the node from 1 (v0.5) to 2 (v0.6). Old packages will loose their icons, but they will load. """ log.debug(u"Upgrading iDevice") # self.emphasis = Idevice.SomeEmphasis self.emphasis = "_orientacionesfpd" def upgradeToVersion3(self): """ Upgrades v0.6 to v0.7. """ self.lastIdevice = False def upgradeToVersion4(self): """ Upgrades to exe v0.10 """ self._upgradeIdeviceToVersion1() self._activityInstruc = self.__dict__['activityInstruc'] def upgradeToVersion5(self): """ Upgrades to exe v0.10 """ self._upgradeIdeviceToVersion1() def upgradeToVersion6(self): """ Upgrades to v0.12 """ self._upgradeIdeviceToVersion2() # self.systemResources += ["common.js"] def upgradeToVersion7(self): """ Upgrades to somewhere before version 0.25 (post-v0.24) Taking the old unicode string fields, and converting them into image-enabled TextAreaFields: """ self.activityTextArea = TextAreaField(x_(u'Guidelines Teacher Text:'), self._activityInstruc, self.activity) self.activityTextArea.idevice = self def upgradeToVersion8(self): """ Delete icon from system resources """ self._upgradeIdeviceToVersion3() def upgradeToVersion9(self): if self._title == u"FPD - Orientaciones Tutoria": self._title = u"FPD - Guidelines Teacher" if self._purpose == u"""Orientaciones alumnado es un iDevice que permite al profesorado conocer los objetivos del aprendizje del alumnado.""": self._purpose = u"""Guidelines Teacher is an iDevice that lets the teacher know the learning objectives of the students.""" if self._activityInstruc == u"""Introduce el texto que aparecer&aacute; en este iDevice""": self._activityInstruc = u"""Enter the text that will appear on this iDevice""" if self.activityTextArea._name == u'Texto Orientaciones tutor&iacute;a': self.activityTextArea._name = u'Guidelines Teacher Text' if self.activityTextArea._name == u'Texto Orientaciones tutor&iacute;a:': self.activityTextArea._name = u'Guidelines Teacher Text:' # ===========================================================================
gpl-2.0
ARTFL-Project/PhiloLogic4
www/scripts/get_term_groups.py
2
2111
#!/usr/bin/env python3 import json import os from wsgiref.handlers import CGIHandler from philologic.runtime.DB import DB from philologic.runtime.Query import split_terms from philologic.runtime.QuerySyntax import group_terms, parse_query import sys sys.path.append("..") import custom_functions try: from custom_functions import WebConfig except ImportError: from philologic.runtime import WebConfig try: from custom_functions import WSGIHandler except ImportError: from philologic.runtime import WSGIHandler def term_group(environ, start_response): status = "200 OK" headers = [("Content-type", "application/json; charset=UTF-8"), ("Access-Control-Allow-Origin", "*")] start_response(status, headers) config = WebConfig(os.path.abspath(os.path.dirname(__file__)).replace("scripts", "")) db = DB(config.db_path + "/data/") request = WSGIHandler(environ, config) if not request["q"]: dump = json.dumps({"original_query": "", "term_groups": []}) else: hits = db.query( request["q"], request["method"], request["arg"], sort_order=request["sort_order"], **request.metadata ) parsed = parse_query(request.q) group = group_terms(parsed) all_groups = split_terms(group) term_groups = [] for g in all_groups: term_group = "" not_started = False for kind, term in g: if kind == "NOT": if not_started is False: not_started = True term_group += " NOT " elif kind == "OR": term_group += "|" elif kind == "TERM": term_group += " %s " % term elif kind == "QUOTE": term_group += " %s " % term term_group = term_group.strip() term_groups.append(term_group) dump = json.dumps({"term_groups": term_groups, "original_query": request.original_q}) yield dump.encode("utf8") if __name__ == "__main__": CGIHandler().run(term_group)
gpl-3.0
joker946/nova
nova/tests/unit/api/openstack/compute/test_flavors.py
7
25600
# Copyright 2012 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. import six.moves.urllib.parse as urlparse import webob from nova.api.openstack import common from nova.api.openstack.compute import flavors as flavors_v2 from nova.api.openstack.compute.plugins.v3 import flavors as flavors_v21 import nova.compute.flavors from nova import context from nova import db from nova import exception from nova import test from nova.tests.unit.api.openstack import fakes from nova.tests.unit import matchers NS = "{http://docs.openstack.org/compute/api/v1.1}" ATOMNS = "{http://www.w3.org/2005/Atom}" FAKE_FLAVORS = { 'flavor 1': { "flavorid": '1', "name": 'flavor 1', "memory_mb": '256', "root_gb": '10', "ephemeral_gb": '20', "swap": '10', "disabled": False, "vcpus": '', }, 'flavor 2': { "flavorid": '2', "name": 'flavor 2', "memory_mb": '512', "root_gb": '20', "ephemeral_gb": '10', "swap": '5', "disabled": False, "vcpus": '', }, } def fake_flavor_get_by_flavor_id(flavorid, ctxt=None): return FAKE_FLAVORS['flavor %s' % flavorid] def fake_get_all_flavors_sorted_list(context=None, inactive=False, filters=None, sort_key='flavorid', sort_dir='asc', limit=None, marker=None): if marker in ['99999']: raise exception.MarkerNotFound(marker) def reject_min(db_attr, filter_attr): return (filter_attr in filters and int(flavor[db_attr]) < int(filters[filter_attr])) filters = filters or {} res = [] for (flavor_name, flavor) in FAKE_FLAVORS.items(): if reject_min('memory_mb', 'min_memory_mb'): continue elif reject_min('root_gb', 'min_root_gb'): continue res.append(flavor) res = sorted(res, key=lambda item: item[sort_key]) output = [] marker_found = True if marker is None else False for flavor in res: if not marker_found and marker == flavor['flavorid']: marker_found = True elif marker_found: if limit is None or len(output) < int(limit): output.append(flavor) return output def fake_get_limit_and_marker(request, max_limit=1): params = common.get_pagination_params(request) limit = params.get('limit', max_limit) limit = min(max_limit, limit) marker = params.get('marker') return limit, marker def empty_get_all_flavors_sorted_list(context=None, inactive=False, filters=None, sort_key='flavorid', sort_dir='asc', limit=None, marker=None): return [] def return_flavor_not_found(flavor_id, ctxt=None): raise exception.FlavorNotFound(flavor_id=flavor_id) class FlavorsTestV21(test.TestCase): _prefix = "/v3" Controller = flavors_v21.FlavorsController fake_request = fakes.HTTPRequestV3 _rspv = "v3" _fake = "" def setUp(self): super(FlavorsTestV21, self).setUp() self.flags(osapi_compute_extension=[]) fakes.stub_out_networking(self.stubs) fakes.stub_out_rate_limiting(self.stubs) self.stubs.Set(nova.compute.flavors, "get_all_flavors_sorted_list", fake_get_all_flavors_sorted_list) self.stubs.Set(nova.compute.flavors, "get_flavor_by_flavor_id", fake_flavor_get_by_flavor_id) self.controller = self.Controller() def _set_expected_body(self, expected, ephemeral, swap, disabled): # NOTE(oomichi): On v2.1 API, some extensions of v2.0 are merged # as core features and we can get the following parameters as the # default. expected['OS-FLV-EXT-DATA:ephemeral'] = ephemeral expected['OS-FLV-DISABLED:disabled'] = disabled expected['swap'] = swap def test_get_flavor_by_invalid_id(self): self.stubs.Set(nova.compute.flavors, "get_flavor_by_flavor_id", return_flavor_not_found) req = self.fake_request.blank(self._prefix + '/flavors/asdf') self.assertRaises(webob.exc.HTTPNotFound, self.controller.show, req, 'asdf') def test_get_flavor_by_id(self): req = self.fake_request.blank(self._prefix + '/flavors/1') flavor = self.controller.show(req, '1') expected = { "flavor": { "id": "1", "name": "flavor 1", "ram": "256", "disk": "10", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, } self._set_expected_body(expected['flavor'], ephemeral='20', swap='10', disabled=False) self.assertEqual(flavor, expected) def test_get_flavor_with_custom_link_prefix(self): self.flags(osapi_compute_link_prefix='http://zoo.com:42', osapi_glance_link_prefix='http://circus.com:34') req = self.fake_request.blank(self._prefix + '/flavors/1') flavor = self.controller.show(req, '1') expected = { "flavor": { "id": "1", "name": "flavor 1", "ram": "256", "disk": "10", "vcpus": "", "links": [ { "rel": "self", "href": "http://zoo.com:42/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://zoo.com:42" + self._fake + "/flavors/1", }, ], }, } self._set_expected_body(expected['flavor'], ephemeral='20', swap='10', disabled=False) self.assertEqual(expected, flavor) def test_get_flavor_list(self): req = self.fake_request.blank(self._prefix + '/flavors') flavor = self.controller.index(req) expected = { "flavors": [ { "id": "1", "name": "flavor 1", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self.assertEqual(flavor, expected) def test_get_flavor_list_with_marker(self): self.maxDiff = None url = self._prefix + '/flavors?limit=1&marker=1' req = self.fake_request.blank(url) flavor = self.controller.index(req) expected = { "flavors": [ { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], 'flavors_links': [ {'href': 'http://localhost/' + self._rspv + '/flavors?limit=1&marker=2', 'rel': 'next'} ] } self.assertThat(flavor, matchers.DictMatches(expected)) def test_get_flavor_list_with_invalid_marker(self): req = self.fake_request.blank(self._prefix + '/flavors?marker=99999') self.assertRaises(webob.exc.HTTPBadRequest, self.controller.index, req) def test_get_flavor_detail_with_limit(self): url = self._prefix + '/flavors/detail?limit=1' req = self.fake_request.blank(url) response = self.controller.detail(req) response_list = response["flavors"] response_links = response["flavors_links"] expected_flavors = [ { "id": "1", "name": "flavor 1", "ram": "256", "disk": "10", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, ] self._set_expected_body(expected_flavors[0], ephemeral='20', swap='10', disabled=False) self.assertEqual(response_list, expected_flavors) self.assertEqual(response_links[0]['rel'], 'next') href_parts = urlparse.urlparse(response_links[0]['href']) self.assertEqual('/' + self._rspv + '/flavors/detail', href_parts.path) params = urlparse.parse_qs(href_parts.query) self.assertThat({'limit': ['1'], 'marker': ['1']}, matchers.DictMatches(params)) def test_get_flavor_with_limit(self): req = self.fake_request.blank(self._prefix + '/flavors?limit=2') response = self.controller.index(req) response_list = response["flavors"] response_links = response["flavors_links"] expected_flavors = [ { "id": "1", "name": "flavor 1", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], } ] self.assertEqual(response_list, expected_flavors) self.assertEqual(response_links[0]['rel'], 'next') href_parts = urlparse.urlparse(response_links[0]['href']) self.assertEqual('/' + self._rspv + '/flavors', href_parts.path) params = urlparse.parse_qs(href_parts.query) self.assertThat({'limit': ['2'], 'marker': ['2']}, matchers.DictMatches(params)) def test_get_flavor_with_default_limit(self): self.stubs.Set(common, "get_limit_and_marker", fake_get_limit_and_marker) self.flags(osapi_max_limit=1) req = fakes.HTTPRequest.blank('/v2/fake/flavors?limit=2') response = self.controller.index(req) response_list = response["flavors"] response_links = response["flavors_links"] expected_flavors = [ { "id": "1", "name": "flavor 1", "links": [ { "rel": "self", "href": "http://localhost/v2/fake/flavors/1", }, { "rel": "bookmark", "href": "http://localhost/fake/flavors/1", } ] } ] self.assertEqual(response_list, expected_flavors) self.assertEqual(response_links[0]['rel'], 'next') href_parts = urlparse.urlparse(response_links[0]['href']) self.assertEqual('/v2/fake/flavors', href_parts.path) params = urlparse.parse_qs(href_parts.query) self.assertThat({'limit': ['2'], 'marker': ['1']}, matchers.DictMatches(params)) def test_get_flavor_list_detail(self): req = self.fake_request.blank(self._prefix + '/flavors/detail') flavor = self.controller.detail(req) expected = { "flavors": [ { "id": "1", "name": "flavor 1", "ram": "256", "disk": "10", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, { "id": "2", "name": "flavor 2", "ram": "512", "disk": "20", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self._set_expected_body(expected['flavors'][0], ephemeral='20', swap='10', disabled=False) self._set_expected_body(expected['flavors'][1], ephemeral='10', swap='5', disabled=False) self.assertEqual(expected, flavor) def test_get_empty_flavor_list(self): self.stubs.Set(nova.compute.flavors, "get_all_flavors_sorted_list", empty_get_all_flavors_sorted_list) req = self.fake_request.blank(self._prefix + '/flavors') flavors = self.controller.index(req) expected = {'flavors': []} self.assertEqual(flavors, expected) def test_get_flavor_list_filter_min_ram(self): # Flavor lists may be filtered by minRam. req = self.fake_request.blank(self._prefix + '/flavors?minRam=512') flavor = self.controller.index(req) expected = { "flavors": [ { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self.assertEqual(flavor, expected) def test_get_flavor_list_filter_invalid_min_ram(self): # Ensure you cannot list flavors with invalid minRam param. req = self.fake_request.blank(self._prefix + '/flavors?minRam=NaN') self.assertRaises(webob.exc.HTTPBadRequest, self.controller.index, req) def test_get_flavor_list_filter_min_disk(self): # Flavor lists may be filtered by minDisk. req = self.fake_request.blank(self._prefix + '/flavors?minDisk=20') flavor = self.controller.index(req) expected = { "flavors": [ { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self.assertEqual(flavor, expected) def test_get_flavor_list_filter_invalid_min_disk(self): # Ensure you cannot list flavors with invalid minDisk param. req = self.fake_request.blank(self._prefix + '/flavors?minDisk=NaN') self.assertRaises(webob.exc.HTTPBadRequest, self.controller.index, req) def test_get_flavor_list_detail_min_ram_and_min_disk(self): """Tests that filtering work on flavor details and that minRam and minDisk filters can be combined """ req = self.fake_request.blank(self._prefix + '/flavors/detail' '?minRam=256&minDisk=20') flavor = self.controller.detail(req) expected = { "flavors": [ { "id": "2", "name": "flavor 2", "ram": "512", "disk": "20", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self._set_expected_body(expected['flavors'][0], ephemeral='10', swap='5', disabled=False) self.assertEqual(expected, flavor) class FlavorsTestV20(FlavorsTestV21): _prefix = "/v2/fake" Controller = flavors_v2.Controller fake_request = fakes.HTTPRequest _rspv = "v2/fake" _fake = "/fake" def _set_expected_body(self, expected, ephemeral, swap, disabled): pass class DisabledFlavorsWithRealDBTestV21(test.TestCase): """Tests that disabled flavors should not be shown nor listed.""" Controller = flavors_v21.FlavorsController _prefix = "/v3" fake_request = fakes.HTTPRequestV3 def setUp(self): super(DisabledFlavorsWithRealDBTestV21, self).setUp() # Add a new disabled type to the list of flavors self.req = self.fake_request.blank(self._prefix + '/flavors') self.context = self.req.environ['nova.context'] self.admin_context = context.get_admin_context() self.disabled_type = self._create_disabled_instance_type() self.inst_types = db.flavor_get_all( self.admin_context) self.controller = self.Controller() def tearDown(self): db.flavor_destroy( self.admin_context, self.disabled_type['name']) super(DisabledFlavorsWithRealDBTestV21, self).tearDown() def _create_disabled_instance_type(self): inst_types = db.flavor_get_all(self.admin_context) inst_type = inst_types[0] del inst_type['id'] inst_type['name'] += '.disabled' inst_type['flavorid'] = unicode(max( [int(flavor['flavorid']) for flavor in inst_types]) + 1) inst_type['disabled'] = True disabled_type = db.flavor_create( self.admin_context, inst_type) return disabled_type def test_index_should_not_list_disabled_flavors_to_user(self): self.context.is_admin = False flavor_list = self.controller.index(self.req)['flavors'] api_flavorids = set(f['id'] for f in flavor_list) db_flavorids = set(i['flavorid'] for i in self.inst_types) disabled_flavorid = str(self.disabled_type['flavorid']) self.assertIn(disabled_flavorid, db_flavorids) self.assertEqual(db_flavorids - set([disabled_flavorid]), api_flavorids) def test_index_should_list_disabled_flavors_to_admin(self): self.context.is_admin = True flavor_list = self.controller.index(self.req)['flavors'] api_flavorids = set(f['id'] for f in flavor_list) db_flavorids = set(i['flavorid'] for i in self.inst_types) disabled_flavorid = str(self.disabled_type['flavorid']) self.assertIn(disabled_flavorid, db_flavorids) self.assertEqual(db_flavorids, api_flavorids) def test_show_should_include_disabled_flavor_for_user(self): """Counterintuitively we should show disabled flavors to all users and not just admins. The reason is that, when a user performs a server-show request, we want to be able to display the pretty flavor name ('512 MB Instance') and not just the flavor-id even if the flavor id has been marked disabled. """ self.context.is_admin = False flavor = self.controller.show( self.req, self.disabled_type['flavorid'])['flavor'] self.assertEqual(flavor['name'], self.disabled_type['name']) def test_show_should_include_disabled_flavor_for_admin(self): self.context.is_admin = True flavor = self.controller.show( self.req, self.disabled_type['flavorid'])['flavor'] self.assertEqual(flavor['name'], self.disabled_type['name']) class DisabledFlavorsWithRealDBTestV20(DisabledFlavorsWithRealDBTestV21): """Tests that disabled flavors should not be shown nor listed.""" Controller = flavors_v2.Controller _prefix = "/v2/fake" fake_request = fakes.HTTPRequest class ParseIsPublicTestV21(test.TestCase): Controller = flavors_v21.FlavorsController def setUp(self): super(ParseIsPublicTestV21, self).setUp() self.controller = self.Controller() def assertPublic(self, expected, is_public): self.assertIs(expected, self.controller._parse_is_public(is_public), '%s did not return %s' % (is_public, expected)) def test_None(self): self.assertPublic(True, None) def test_truthy(self): self.assertPublic(True, True) self.assertPublic(True, 't') self.assertPublic(True, 'true') self.assertPublic(True, 'yes') self.assertPublic(True, '1') def test_falsey(self): self.assertPublic(False, False) self.assertPublic(False, 'f') self.assertPublic(False, 'false') self.assertPublic(False, 'no') self.assertPublic(False, '0') def test_string_none(self): self.assertPublic(None, 'none') self.assertPublic(None, 'None') def test_other(self): self.assertRaises( webob.exc.HTTPBadRequest, self.assertPublic, None, 'other') class ParseIsPublicTestV20(ParseIsPublicTestV21): Controller = flavors_v2.Controller
apache-2.0
sundayliu/npm-www
node_modules/npm/node_modules/node-gyp/gyp/tools/pretty_vcproj.py
2637
9586
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Make the format of a vcproj really pretty. This script normalize and sort an xml. It also fetches all the properties inside linked vsprops and include them explicitly in the vcproj. It outputs the resulting xml to stdout. """ __author__ = 'nsylvain (Nicolas Sylvain)' import os import sys from xml.dom.minidom import parse from xml.dom.minidom import Node REPLACEMENTS = dict() ARGUMENTS = None class CmpTuple(object): """Compare function between 2 tuple.""" def __call__(self, x, y): return cmp(x[0], y[0]) class CmpNode(object): """Compare function between 2 xml nodes.""" def __call__(self, x, y): def get_string(node): node_string = "node" node_string += node.nodeName if node.nodeValue: node_string += node.nodeValue if node.attributes: # We first sort by name, if present. node_string += node.getAttribute("Name") all_nodes = [] for (name, value) in node.attributes.items(): all_nodes.append((name, value)) all_nodes.sort(CmpTuple()) for (name, value) in all_nodes: node_string += name node_string += value return node_string return cmp(get_string(x), get_string(y)) def PrettyPrintNode(node, indent=0): if node.nodeType == Node.TEXT_NODE: if node.data.strip(): print '%s%s' % (' '*indent, node.data.strip()) return if node.childNodes: node.normalize() # Get the number of attributes attr_count = 0 if node.attributes: attr_count = node.attributes.length # Print the main tag if attr_count == 0: print '%s<%s>' % (' '*indent, node.nodeName) else: print '%s<%s' % (' '*indent, node.nodeName) all_attributes = [] for (name, value) in node.attributes.items(): all_attributes.append((name, value)) all_attributes.sort(CmpTuple()) for (name, value) in all_attributes: print '%s %s="%s"' % (' '*indent, name, value) print '%s>' % (' '*indent) if node.nodeValue: print '%s %s' % (' '*indent, node.nodeValue) for sub_node in node.childNodes: PrettyPrintNode(sub_node, indent=indent+2) print '%s</%s>' % (' '*indent, node.nodeName) def FlattenFilter(node): """Returns a list of all the node and sub nodes.""" node_list = [] if (node.attributes and node.getAttribute('Name') == '_excluded_files'): # We don't add the "_excluded_files" filter. return [] for current in node.childNodes: if current.nodeName == 'Filter': node_list.extend(FlattenFilter(current)) else: node_list.append(current) return node_list def FixFilenames(filenames, current_directory): new_list = [] for filename in filenames: if filename: for key in REPLACEMENTS: filename = filename.replace(key, REPLACEMENTS[key]) os.chdir(current_directory) filename = filename.strip('"\' ') if filename.startswith('$'): new_list.append(filename) else: new_list.append(os.path.abspath(filename)) return new_list def AbsoluteNode(node): """Makes all the properties we know about in this node absolute.""" if node.attributes: for (name, value) in node.attributes.items(): if name in ['InheritedPropertySheets', 'RelativePath', 'AdditionalIncludeDirectories', 'IntermediateDirectory', 'OutputDirectory', 'AdditionalLibraryDirectories']: # We want to fix up these paths path_list = value.split(';') new_list = FixFilenames(path_list, os.path.dirname(ARGUMENTS[1])) node.setAttribute(name, ';'.join(new_list)) if not value: node.removeAttribute(name) def CleanupVcproj(node): """For each sub node, we call recursively this function.""" for sub_node in node.childNodes: AbsoluteNode(sub_node) CleanupVcproj(sub_node) # Normalize the node, and remove all extranous whitespaces. for sub_node in node.childNodes: if sub_node.nodeType == Node.TEXT_NODE: sub_node.data = sub_node.data.replace("\r", "") sub_node.data = sub_node.data.replace("\n", "") sub_node.data = sub_node.data.rstrip() # Fix all the semicolon separated attributes to be sorted, and we also # remove the dups. if node.attributes: for (name, value) in node.attributes.items(): sorted_list = sorted(value.split(';')) unique_list = [] for i in sorted_list: if not unique_list.count(i): unique_list.append(i) node.setAttribute(name, ';'.join(unique_list)) if not value: node.removeAttribute(name) if node.childNodes: node.normalize() # For each node, take a copy, and remove it from the list. node_array = [] while node.childNodes and node.childNodes[0]: # Take a copy of the node and remove it from the list. current = node.childNodes[0] node.removeChild(current) # If the child is a filter, we want to append all its children # to this same list. if current.nodeName == 'Filter': node_array.extend(FlattenFilter(current)) else: node_array.append(current) # Sort the list. node_array.sort(CmpNode()) # Insert the nodes in the correct order. for new_node in node_array: # But don't append empty tool node. if new_node.nodeName == 'Tool': if new_node.attributes and new_node.attributes.length == 1: # This one was empty. continue if new_node.nodeName == 'UserMacro': continue node.appendChild(new_node) def GetConfiguationNodes(vcproj): #TODO(nsylvain): Find a better way to navigate the xml. nodes = [] for node in vcproj.childNodes: if node.nodeName == "Configurations": for sub_node in node.childNodes: if sub_node.nodeName == "Configuration": nodes.append(sub_node) return nodes def GetChildrenVsprops(filename): dom = parse(filename) if dom.documentElement.attributes: vsprops = dom.documentElement.getAttribute('InheritedPropertySheets') return FixFilenames(vsprops.split(';'), os.path.dirname(filename)) return [] def SeekToNode(node1, child2): # A text node does not have properties. if child2.nodeType == Node.TEXT_NODE: return None # Get the name of the current node. current_name = child2.getAttribute("Name") if not current_name: # There is no name. We don't know how to merge. return None # Look through all the nodes to find a match. for sub_node in node1.childNodes: if sub_node.nodeName == child2.nodeName: name = sub_node.getAttribute("Name") if name == current_name: return sub_node # No match. We give up. return None def MergeAttributes(node1, node2): # No attributes to merge? if not node2.attributes: return for (name, value2) in node2.attributes.items(): # Don't merge the 'Name' attribute. if name == 'Name': continue value1 = node1.getAttribute(name) if value1: # The attribute exist in the main node. If it's equal, we leave it # untouched, otherwise we concatenate it. if value1 != value2: node1.setAttribute(name, ';'.join([value1, value2])) else: # The attribute does nto exist in the main node. We append this one. node1.setAttribute(name, value2) # If the attribute was a property sheet attributes, we remove it, since # they are useless. if name == 'InheritedPropertySheets': node1.removeAttribute(name) def MergeProperties(node1, node2): MergeAttributes(node1, node2) for child2 in node2.childNodes: child1 = SeekToNode(node1, child2) if child1: MergeProperties(child1, child2) else: node1.appendChild(child2.cloneNode(True)) def main(argv): """Main function of this vcproj prettifier.""" global ARGUMENTS ARGUMENTS = argv # check if we have exactly 1 parameter. if len(argv) < 2: print ('Usage: %s "c:\\path\\to\\vcproj.vcproj" [key1=value1] ' '[key2=value2]' % argv[0]) return 1 # Parse the keys for i in range(2, len(argv)): (key, value) = argv[i].split('=') REPLACEMENTS[key] = value # Open the vcproj and parse the xml. dom = parse(argv[1]) # First thing we need to do is find the Configuration Node and merge them # with the vsprops they include. for configuration_node in GetConfiguationNodes(dom.documentElement): # Get the property sheets associated with this configuration. vsprops = configuration_node.getAttribute('InheritedPropertySheets') # Fix the filenames to be absolute. vsprops_list = FixFilenames(vsprops.strip().split(';'), os.path.dirname(argv[1])) # Extend the list of vsprops with all vsprops contained in the current # vsprops. for current_vsprops in vsprops_list: vsprops_list.extend(GetChildrenVsprops(current_vsprops)) # Now that we have all the vsprops, we need to merge them. for current_vsprops in vsprops_list: MergeProperties(configuration_node, parse(current_vsprops).documentElement) # Now that everything is merged, we need to cleanup the xml. CleanupVcproj(dom.documentElement) # Finally, we use the prett xml function to print the vcproj back to the # user. #print dom.toprettyxml(newl="\n") PrettyPrintNode(dom.documentElement) return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
isc
kursitet/edx-platform
common/lib/capa/capa/safe_exec/tests/test_lazymod.py
152
1667
"""Test lazymod.py""" import sys import unittest from capa.safe_exec.lazymod import LazyModule class ModuleIsolation(object): """ Manage changes to sys.modules so that we can roll back imported modules. Create this object, it will snapshot the currently imported modules. When you call `clean_up()`, it will delete any module imported since its creation. """ def __init__(self): # Save all the names of all the imported modules. self.mods = set(sys.modules) def clean_up(self): # Get a list of modules that didn't exist when we were created new_mods = [m for m in sys.modules if m not in self.mods] # and delete them all so another import will run code for real again. for m in new_mods: del sys.modules[m] class TestLazyMod(unittest.TestCase): def setUp(self): super(TestLazyMod, self).setUp() # Each test will remove modules that it imported. self.addCleanup(ModuleIsolation().clean_up) def test_simple(self): # Import some stdlib module that has not been imported before self.assertNotIn("colorsys", sys.modules) colorsys = LazyModule("colorsys") hsv = colorsys.rgb_to_hsv(.3, .4, .2) self.assertEqual(hsv[0], 0.25) def test_dotted(self): # wsgiref is a module with submodules that is not already imported. # Any similar module would do. This test demonstrates that the module # is not already im self.assertNotIn("wsgiref.util", sys.modules) wsgiref_util = LazyModule("wsgiref.util") self.assertEqual(wsgiref_util.guess_scheme({}), "http")
agpl-3.0
rsvip/Django
tests/model_options/test_tablespaces.py
337
5389
from __future__ import unicode_literals from django.apps import apps from django.conf import settings from django.db import connection from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models.tablespaces import ( Article, ArticleRef, Authors, Reviewers, Scientist, ScientistRef, ) def sql_for_table(model): with connection.schema_editor(collect_sql=True) as editor: editor.create_model(model) return editor.collected_sql[0] def sql_for_index(model): return '\n'.join(connection.schema_editor()._model_indexes_sql(model)) # We can't test the DEFAULT_TABLESPACE and DEFAULT_INDEX_TABLESPACE settings # because they're evaluated when the model class is defined. As a consequence, # @override_settings doesn't work, and the tests depend class TablespacesTests(TestCase): def setUp(self): # The unmanaged models need to be removed after the test in order to # prevent bad interactions with the flush operation in other tests. self._old_models = apps.app_configs['model_options'].models.copy() for model in Article, Authors, Reviewers, Scientist: model._meta.managed = True def tearDown(self): for model in Article, Authors, Reviewers, Scientist: model._meta.managed = False apps.app_configs['model_options'].models = self._old_models apps.all_models['model_options'] = self._old_models apps.clear_cache() def assertNumContains(self, haystack, needle, count): real_count = haystack.count(needle) self.assertEqual(real_count, count, "Found %d instances of '%s', " "expected %d" % (real_count, needle, count)) @skipUnlessDBFeature('supports_tablespaces') def test_tablespace_for_model(self): sql = sql_for_table(Scientist).lower() if settings.DEFAULT_INDEX_TABLESPACE: # 1 for the table self.assertNumContains(sql, 'tbl_tbsp', 1) # 1 for the index on the primary key self.assertNumContains(sql, settings.DEFAULT_INDEX_TABLESPACE, 1) else: # 1 for the table + 1 for the index on the primary key self.assertNumContains(sql, 'tbl_tbsp', 2) @skipIfDBFeature('supports_tablespaces') def test_tablespace_ignored_for_model(self): # No tablespace-related SQL self.assertEqual(sql_for_table(Scientist), sql_for_table(ScientistRef)) @skipUnlessDBFeature('supports_tablespaces') def test_tablespace_for_indexed_field(self): sql = sql_for_table(Article).lower() if settings.DEFAULT_INDEX_TABLESPACE: # 1 for the table self.assertNumContains(sql, 'tbl_tbsp', 1) # 1 for the primary key + 1 for the index on code self.assertNumContains(sql, settings.DEFAULT_INDEX_TABLESPACE, 2) else: # 1 for the table + 1 for the primary key + 1 for the index on code self.assertNumContains(sql, 'tbl_tbsp', 3) # 1 for the index on reference self.assertNumContains(sql, 'idx_tbsp', 1) @skipIfDBFeature('supports_tablespaces') def test_tablespace_ignored_for_indexed_field(self): # No tablespace-related SQL self.assertEqual(sql_for_table(Article), sql_for_table(ArticleRef)) @skipUnlessDBFeature('supports_tablespaces') def test_tablespace_for_many_to_many_field(self): sql = sql_for_table(Authors).lower() # The join table of the ManyToManyField goes to the model's tablespace, # and its indexes too, unless DEFAULT_INDEX_TABLESPACE is set. if settings.DEFAULT_INDEX_TABLESPACE: # 1 for the table self.assertNumContains(sql, 'tbl_tbsp', 1) # 1 for the primary key self.assertNumContains(sql, settings.DEFAULT_INDEX_TABLESPACE, 1) else: # 1 for the table + 1 for the index on the primary key self.assertNumContains(sql, 'tbl_tbsp', 2) self.assertNumContains(sql, 'idx_tbsp', 0) sql = sql_for_index(Authors).lower() # The ManyToManyField declares no db_tablespace, its indexes go to # the model's tablespace, unless DEFAULT_INDEX_TABLESPACE is set. if settings.DEFAULT_INDEX_TABLESPACE: self.assertNumContains(sql, settings.DEFAULT_INDEX_TABLESPACE, 2) else: self.assertNumContains(sql, 'tbl_tbsp', 2) self.assertNumContains(sql, 'idx_tbsp', 0) sql = sql_for_table(Reviewers).lower() # The join table of the ManyToManyField goes to the model's tablespace, # and its indexes too, unless DEFAULT_INDEX_TABLESPACE is set. if settings.DEFAULT_INDEX_TABLESPACE: # 1 for the table self.assertNumContains(sql, 'tbl_tbsp', 1) # 1 for the primary key self.assertNumContains(sql, settings.DEFAULT_INDEX_TABLESPACE, 1) else: # 1 for the table + 1 for the index on the primary key self.assertNumContains(sql, 'tbl_tbsp', 2) self.assertNumContains(sql, 'idx_tbsp', 0) sql = sql_for_index(Reviewers).lower() # The ManyToManyField declares db_tablespace, its indexes go there. self.assertNumContains(sql, 'tbl_tbsp', 0) self.assertNumContains(sql, 'idx_tbsp', 2)
bsd-3-clause
iambibhas/django
django/contrib/gis/tests/relatedapp/tests.py
18
15753
from __future__ import unicode_literals from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.tests.utils import no_oracle from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.test.utils import override_settings from django.utils import timezone if HAS_GEOS: from django.contrib.gis.db.models import Collect, Count, Extent, F, Union from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.geos import GEOSGeometry, Point, MultiPoint from .models import City, Location, DirectoryEntry, Parcel, Book, Author, Article, Event @skipUnlessDBFeature("gis_enabled") class RelatedGeoModelTest(TestCase): fixtures = ['initial'] def test02_select_related(self): "Testing `select_related` on geographic models (see #7126)." qs1 = City.objects.order_by('id') qs2 = City.objects.order_by('id').select_related() qs3 = City.objects.order_by('id').select_related('location') # Reference data for what's in the fixtures. cities = ( ('Aurora', 'TX', -97.516111, 33.058333), ('Roswell', 'NM', -104.528056, 33.387222), ('Kecksburg', 'PA', -79.460734, 40.18476), ) for qs in (qs1, qs2, qs3): for ref, c in zip(cities, qs): nm, st, lon, lat = ref self.assertEqual(nm, c.name) self.assertEqual(st, c.state) self.assertEqual(Point(lon, lat), c.location.point) @skipUnlessDBFeature("has_transform_method") def test03_transform_related(self): "Testing the `transform` GeoQuerySet method on related geographic models." # All the transformations are to state plane coordinate systems using # US Survey Feet (thus a tolerance of 0 implies error w/in 1 survey foot). tol = 0 def check_pnt(ref, pnt): self.assertAlmostEqual(ref.x, pnt.x, tol) self.assertAlmostEqual(ref.y, pnt.y, tol) self.assertEqual(ref.srid, pnt.srid) # Each city transformed to the SRID of their state plane coordinate system. transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'), ('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'), ('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'), ) for name, srid, wkt in transformed: # Doing this implicitly sets `select_related` select the location. # TODO: Fix why this breaks on Oracle. qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point')) check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point) @skipUnlessDBFeature("supports_extent_aggr") def test04a_related_extent_aggregate(self): "Testing the `extent` GeoQuerySet aggregates on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Extent('location__point')) # One for all locations, one that excludes New Mexico (Roswell). all_extent = (-104.528056, 29.763374, -79.460734, 40.18476) txpa_extent = (-97.516111, 29.763374, -79.460734, 40.18476) e1 = City.objects.extent(field_name='location__point') e2 = City.objects.exclude(state='NM').extent(field_name='location__point') e3 = aggs['location__point__extent'] # The tolerance value is to four decimal places because of differences # between the Oracle and PostGIS spatial backends on the extent calculation. tol = 4 for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]: for ref_val, e_val in zip(ref, e): self.assertAlmostEqual(ref_val, e_val, tol) @skipUnlessDBFeature("has_unionagg_method") def test04b_related_union_aggregate(self): "Testing the `unionagg` GeoQuerySet aggregates on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Union('location__point')) # These are the points that are components of the aggregate geographic # union that is returned. Each point # corresponds to City PK. p1 = Point(-104.528056, 33.387222) p2 = Point(-97.516111, 33.058333) p3 = Point(-79.460734, 40.18476) p4 = Point(-96.801611, 32.782057) p5 = Point(-95.363151, 29.763374) # The second union aggregate is for a union # query that includes limiting information in the WHERE clause (in other # words a `.filter()` precedes the call to `.unionagg()`). ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326) ref_u2 = MultiPoint(p2, p3, srid=4326) u1 = City.objects.unionagg(field_name='location__point') u2 = City.objects.exclude( name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth'), ).unionagg(field_name='location__point') u3 = aggs['location__point__union'] self.assertEqual(type(u1), MultiPoint) self.assertEqual(type(u3), MultiPoint) # Ordering of points in the result of the union is not defined and # implementation-dependent (DB backend, GEOS version) self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u1}) self.assertSetEqual({p.ewkt for p in ref_u2}, {p.ewkt for p in u2}) self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3}) def test05_select_related_fk_to_subclass(self): "Testing that calling select_related on a query over a model with an FK to a model subclass works" # Regression test for #9752. list(DirectoryEntry.objects.all().select_related()) def test06_f_expressions(self): "Testing F() expressions on GeometryFields." # Constructing a dummy parcel border and getting the City instance for # assigning the FK. b1 = GEOSGeometry( 'POLYGON((-97.501205 33.052520,-97.501205 33.052576,' '-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))', srid=4326 ) pcity = City.objects.get(name='Aurora') # First parcel has incorrect center point that is equal to the City; # it also has a second border that is different from the first as a # 100ft buffer around the City. c1 = pcity.location.point c2 = c1.transform(2276, clone=True) b2 = c2.buffer(100) Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2) # Now creating a second Parcel where the borders are the same, just # in different coordinate systems. The center points are also the # same (but in different coordinate systems), and this time they # actually correspond to the centroid of the border. c1 = b1.centroid c2 = c1.transform(2276, clone=True) Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1) # Should return the second Parcel, which has the center within the # border. qs = Parcel.objects.filter(center1__within=F('border1')) self.assertEqual(1, len(qs)) self.assertEqual('P2', qs[0].name) if connection.features.supports_transform: # This time center2 is in a different coordinate system and needs # to be wrapped in transformation SQL. qs = Parcel.objects.filter(center2__within=F('border1')) self.assertEqual(1, len(qs)) self.assertEqual('P2', qs[0].name) # Should return the first Parcel, which has the center point equal # to the point in the City ForeignKey. qs = Parcel.objects.filter(center1=F('city__location__point')) self.assertEqual(1, len(qs)) self.assertEqual('P1', qs[0].name) if connection.features.supports_transform: # This time the city column should be wrapped in transformation SQL. qs = Parcel.objects.filter(border2__contains=F('city__location__point')) self.assertEqual(1, len(qs)) self.assertEqual('P1', qs[0].name) def test07_values(self): "Testing values() and values_list() and GeoQuerySets." # GeoQuerySet and GeoValuesQuerySet, and GeoValuesListQuerySet respectively. gqs = Location.objects.all() gvqs = Location.objects.values() gvlqs = Location.objects.values_list() # Incrementing through each of the models, dictionaries, and tuples # returned by the different types of GeoQuerySets. for m, d, t in zip(gqs, gvqs, gvlqs): # The values should be Geometry objects and not raw strings returned # by the spatial database. self.assertIsInstance(d['point'], Geometry) self.assertIsInstance(t[1], Geometry) self.assertEqual(m.point, d['point']) self.assertEqual(m.point, t[1]) @override_settings(USE_TZ=True) def test_07b_values(self): "Testing values() and values_list() with aware datetime. See #21565." Event.objects.create(name="foo", when=timezone.now()) list(Event.objects.values_list('when')) def test08_defer_only(self): "Testing defer() and only() on Geographic models." qs = Location.objects.all() def_qs = Location.objects.defer('point') for loc, def_loc in zip(qs, def_qs): self.assertEqual(loc.point, def_loc.point) def test09_pk_relations(self): "Ensuring correct primary key column is selected across relations. See #10757." # The expected ID values -- notice the last two location IDs # are out of order. Dallas and Houston have location IDs that differ # from their PKs -- this is done to ensure that the related location # ID column is selected instead of ID column for the city. city_ids = (1, 2, 3, 4, 5) loc_ids = (1, 2, 3, 5, 4) ids_qs = City.objects.order_by('id').values('id', 'location__id') for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids): self.assertEqual(val_dict['id'], c_id) self.assertEqual(val_dict['location__id'], l_id) # TODO: fix on Oracle -- qs2 returns an empty result for an unknown reason @no_oracle def test10_combine(self): "Testing the combination of two GeoQuerySets. See #10807." buf1 = City.objects.get(name='Aurora').location.point.buffer(0.1) buf2 = City.objects.get(name='Kecksburg').location.point.buffer(0.1) qs1 = City.objects.filter(location__point__within=buf1) qs2 = City.objects.filter(location__point__within=buf2) combined = qs1 | qs2 names = [c.name for c in combined] self.assertEqual(2, len(names)) self.assertIn('Aurora', names) self.assertIn('Kecksburg', names) def test11_geoquery_pickle(self): "Ensuring GeoQuery objects are unpickled correctly. See #10839." import pickle from django.contrib.gis.db.models.sql import GeoQuery qs = City.objects.all() q_str = pickle.dumps(qs.query) q = pickle.loads(q_str) self.assertEqual(GeoQuery, q.__class__) # TODO: fix on Oracle -- get the following error because the SQL is ordered # by a geometry object, which Oracle apparently doesn't like: # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type @no_oracle def test12a_count(self): "Testing `Count` aggregate use with the `GeoManager` on geo-fields." # The City, 'Fort Worth' uses the same location as Dallas. dallas = City.objects.get(name='Dallas') # Count annotation should be 2 for the Dallas location now. loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id) self.assertEqual(2, loc.num_cities) def test12b_count(self): "Testing `Count` aggregate use with the `GeoManager` on non geo-fields. See #11087." # Should only be one author (Trevor Paglen) returned by this query, and # the annotation should have 3 for the number of books, see #11087. # Also testing with a `GeoValuesQuerySet`, see #11489. qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1) vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1) self.assertEqual(1, len(qs)) self.assertEqual(3, qs[0].num_books) self.assertEqual(1, len(vqs)) self.assertEqual(3, vqs[0]['num_books']) # TODO: fix on Oracle -- get the following error because the SQL is ordered # by a geometry object, which Oracle apparently doesn't like: # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type @no_oracle def test13c_count(self): "Testing `Count` aggregate with `.values()`. See #15305." qs = Location.objects.filter(id=5).annotate(num_cities=Count('city')).values('id', 'point', 'num_cities') self.assertEqual(1, len(qs)) self.assertEqual(2, qs[0]['num_cities']) self.assertIsInstance(qs[0]['point'], GEOSGeometry) # TODO: The phantom model does appear on Oracle. @no_oracle def test13_select_related_null_fk(self): "Testing `select_related` on a nullable ForeignKey via `GeoManager`. See #11381." Book.objects.create(title='Without Author') b = Book.objects.select_related('author').get(title='Without Author') # Should be `None`, and not a 'dummy' model. self.assertEqual(None, b.author) @skipUnlessDBFeature("supports_collect_aggr") def test14_collect(self): "Testing the `collect` GeoQuerySet method and `Collect` aggregate." # Reference query: # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN # "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id") # WHERE "relatedapp_city"."state" = 'TX'; ref_geom = GEOSGeometry( 'MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,' '-95.363151 29.763374,-96.801611 32.782057)' ) c1 = City.objects.filter(state='TX').collect(field_name='location__point') c2 = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect'] for coll in (c1, c2): # Even though Dallas and Ft. Worth share same point, Collect doesn't # consolidate -- that's why 4 points in MultiPoint. self.assertEqual(4, len(coll)) self.assertTrue(ref_geom.equals(coll)) def test15_invalid_select_related(self): "Testing doing select_related on the related name manager of a unique FK. See #13934." qs = Article.objects.select_related('author__article') # This triggers TypeError when `get_default_columns` has no `local_only` # keyword. The TypeError is swallowed if QuerySet is actually # evaluated as list generation swallows TypeError in CPython. str(qs.query) def test16_annotated_date_queryset(self): "Ensure annotated date querysets work if spatial backend is used. See #14648." birth_years = [dt.year for dt in list(Author.objects.annotate(num_books=Count('books')).dates('dob', 'year'))] birth_years.sort() self.assertEqual([1950, 1974], birth_years) # TODO: Related tests for KML, GML, and distance lookups.
bsd-3-clause
nikolay-saskovets/Feedly
feedly/tests/feeds/cassandra.py
4
1939
from feedly.tests.feeds.base import TestBaseFeed, implementation import pytest from feedly.feeds.cassandra import CassandraFeed from feedly.utils import datetime_to_epoch from feedly.activity import Activity class CustomActivity(Activity): @property def serialization_id(self): ''' Shorter serialization id than used by default ''' if self.object_id >= 10 ** 10 or self.verb.id >= 10 ** 3: raise TypeError('Fatal: object_id / verb have too many digits !') if not self.time: raise TypeError('Cant serialize activities without a time') milliseconds = str(int(datetime_to_epoch(self.time) * 1000)) # shorter than the default version serialization_id_str = '%s%0.2d%0.2d' % ( milliseconds, self.object_id % 100, self.verb.id) serialization_id = int(serialization_id_str) return serialization_id class CassandraCustomFeed(CassandraFeed): activity_class = CustomActivity @pytest.mark.usefixtures("cassandra_reset") class TestCassandraBaseFeed(TestBaseFeed): feed_cls = CassandraFeed def test_add_insert_activity(self): pass def test_add_remove_activity(self): pass @pytest.mark.usefixtures("cassandra_reset") class TestCassandraCustomFeed(TestBaseFeed): feed_cls = CassandraCustomFeed activity_class = CustomActivity def test_add_insert_activity(self): pass def test_add_remove_activity(self): pass @implementation def test_custom_activity(self): assert self.test_feed.count() == 0 self.feed_cls.insert_activity( self.activity ) self.test_feed.add(self.activity) assert self.test_feed.count() == 1 assert self.activity == self.test_feed[:10][0] assert type(self.activity) == type(self.test_feed[0][0]) # make sure nothing is wrong with the activity storage
bsd-3-clause
TNT-Samuel/Coding-Projects
DNS Server/Source - Copy/Lib/site-packages/prompt_toolkit/contrib/validators/base.py
20
1240
from __future__ import unicode_literals from prompt_toolkit.validation import Validator, ValidationError from six import string_types class SentenceValidator(Validator): """ Validate input only when it appears in this list of sentences. :param sentences: List of sentences. :param ignore_case: If True, case-insensitive comparisons. """ def __init__(self, sentences, ignore_case=False, error_message='Invalid input', move_cursor_to_end=False): assert all(isinstance(s, string_types) for s in sentences) assert isinstance(ignore_case, bool) assert isinstance(error_message, string_types) self.sentences = list(sentences) self.ignore_case = ignore_case self.error_message = error_message self.move_cursor_to_end = move_cursor_to_end if ignore_case: self.sentences = set([s.lower() for s in self.sentences]) def validate(self, document): if document.text not in self.sentences: if self.move_cursor_to_end: index = len(document.text) else: index = 0 raise ValidationError(cursor_position=index, message=self.error_message)
gpl-3.0
ShinyROM/android_external_chromium_org
content/test/gpu/gpu_tests/webgl_conformance_expectations.py
23
9671
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion, # linux, chromeos, android # # GPU vendors: # amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm, # vivante # # Specific GPUs can be listed as a tuple with vendor name and device ID. # Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604') # Device IDs must be paired with a GPU vendor. class WebGLConformanceExpectations(test_expectations.TestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('gl-enable-vertex-attrib.html', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) # Fails everywhere. self.Skip('conformance/glsl/misc/large-loop-compile.html', bug=322764) self.Skip('conformance/textures/texture-size-limit.html', bug=322789) # Windows failures. self.Fail('conformance/ogles/GL/atan/atan_001_to_008.html', ['win'], bug=322794) self.Fail('conformance/ogles/GL/atan/atan_009_to_012.html', ['win'], bug=322794) self.Skip('conformance/ogles/GL/control_flow/control_flow_001_to_008.html', ['win'], bug=322795) # Windows/Intel failures self.Fail('conformance/textures/texture-size.html', ['win', 'intel'], bug=121139) self.Fail('conformance/rendering/gl-scissor-test.html', ['win', 'intel'], bug=314997) # Windows/AMD failures self.Fail('conformance/rendering/more-than-65536-indices.html', ['win', 'amd'], bug=314997) # Windows 7/Intel failures self.Fail('conformance/context/context-lost-restored.html', ['win7', 'intel']) self.Fail('conformance/context/premultiplyalpha-test.html', ['win7', 'intel']) self.Fail('conformance/extensions/oes-texture-float-with-image-data.html', ['win7', 'intel']) self.Fail('conformance/extensions/oes-texture-float.html', ['win7', 'intel']) self.Fail('conformance/limits/gl-min-attribs.html', ['win7', 'intel']) self.Fail('conformance/limits/gl-max-texture-dimensions.html', ['win7', 'intel']) self.Fail('conformance/limits/gl-min-textures.html', ['win7', 'intel']) self.Fail('conformance/limits/gl-min-uniforms.html', ['win7', 'intel']) self.Fail('conformance/rendering/gl-clear.html', ['win7', 'intel']) self.Fail('conformance/textures/copy-tex-image-and-sub-image-2d.html', ['win7', 'intel']) self.Fail('conformance/textures/gl-teximage.html', ['win7', 'intel']) self.Fail('conformance/textures/tex-image-and-sub-image-2d-with-array-buffer-view.html', ['win7', 'intel']) self.Fail('conformance/textures/tex-image-and-sub-image-2d-with-image-data.html', ['win7', 'intel']) self.Fail('conformance/textures/tex-image-and-sub-image-2d-with-image-data-rgb565.html', ['win7', 'intel']) self.Fail('conformance/textures/tex-image-and-sub-image-2d-with-image-data-rgba4444.html', ['win7', 'intel']) self.Fail('conformance/textures/tex-image-and-sub-image-2d-with-image-data-rgba5551.html', ['win7', 'intel']) self.Fail('conformance/textures/tex-image-with-format-and-type.html', ['win7', 'intel']) self.Fail('conformance/textures/tex-sub-image-2d.html', ['win7', 'intel']) self.Fail('conformance/textures/texparameter-test.html', ['win7', 'intel']) self.Fail('conformance/textures/texture-active-bind-2.html', ['win7', 'intel']) self.Fail('conformance/textures/texture-active-bind.html', ['win7', 'intel']) self.Fail('conformance/textures/texture-complete.html', ['win7', 'intel']) self.Fail('conformance/textures/texture-formats-test.html', ['win7', 'intel']) self.Fail('conformance/textures/texture-mips.html', ['win7', 'intel']) self.Fail('conformance/textures/texture-npot.html', ['win7', 'intel']) self.Fail('conformance/textures/texture-size-cube-maps.html', ['win7', 'intel']) self.Fail('conformance/context/context-attribute-preserve-drawing-buffer.html', ['win7', 'intel'], bug=322770) # Mac failures. self.Fail('conformance/glsl/misc/shaders-with-varyings.html', ['mac'], bug=322760) self.Fail('conformance/context/context-attribute-preserve-drawing-buffer.html', ['mac'], bug=322770) self.Skip('conformance/ogles/GL/control_flow/control_flow_001_to_008.html', ['mac'], bug=322795) # Mac/Intel failures self.Fail('conformance/rendering/gl-scissor-test.html', ['mac', 'intel'], bug=314997) # The following two tests hang the WindowServer. self.Skip('conformance/canvas/drawingbuffer-static-canvas-test.html', ['mac', 'intel'], bug=303915) self.Skip('conformance/canvas/drawingbuffer-test.html', ['mac', 'intel'], bug=303915) # The following three tests only fail. # Radar 13499677 self.Fail( 'conformance/glsl/functions/glsl-function-smoothstep-gentype.html', ['mac', 'intel'], bug=225642) # Radar 13499466 self.Fail('conformance/limits/gl-max-texture-dimensions.html', ['mac', 'intel'], bug=225642) # Radar 13499623 self.Fail('conformance/textures/texture-size.html', ['mac', 'intel'], bug=225642) self.Skip('conformance/ogles/GL/control_flow/control_flow_009_to_010.html', ['mac', 'intel'], bug=322795) self.Fail('conformance/ogles/GL/operators/operators_009_to_016.html', ['mac', 'intel'], bug=322795) # Mac/Intel failures on 10.7 self.Skip('conformance/glsl/functions/glsl-function-asin.html', ['lion', 'intel']) self.Skip('conformance/glsl/functions/glsl-function-dot.html', ['lion', 'intel']) self.Skip('conformance/glsl/functions/glsl-function-faceforward.html', ['lion', 'intel']) self.Skip('conformance/glsl/functions/glsl-function-length.html', ['lion', 'intel']) self.Skip('conformance/glsl/functions/glsl-function-normalize.html', ['lion', 'intel']) self.Skip('conformance/glsl/functions/glsl-function-reflect.html', ['lion', 'intel']) self.Skip( 'conformance/glsl/functions/glsl-function-smoothstep-gentype.html', ['lion', 'intel']) self.Skip('conformance/limits/gl-max-texture-dimensions.html', ['lion', 'intel']) self.Skip('conformance/rendering/line-loop-tri-fan.html', ['lion', 'intel']) self.Skip('conformance/ogles/GL/control_flow/control_flow_009_to_010.html', ['lion'], bug=322795) self.Skip('conformance/ogles/GL/dot/dot_001_to_006.html', ['lion', 'intel'], bug=323736) self.Skip('conformance/ogles/GL/faceforward/faceforward_001_to_006.html', ['lion', 'intel'], bug=323736) self.Skip('conformance/ogles/GL/length/length_001_to_006.html', ['lion', 'intel'], bug=323736) self.Skip('conformance/ogles/GL/normalize/normalize_001_to_006.html', ['lion', 'intel'], bug=323736) self.Skip('conformance/ogles/GL/reflect/reflect_001_to_006.html', ['lion', 'intel'], bug=323736) self.Skip('conformance/ogles/GL/refract/refract_001_to_006.html', ['lion', 'intel'], bug=323736) self.Skip('conformance/ogles/GL/tan/tan_001_to_006.html', ['lion', 'intel'], bug=323736) # Mac/ATI failures self.Skip('conformance/extensions/oes-texture-float-with-image-data.html', ['mac', 'amd'], bug=308328) self.Skip('conformance/rendering/gl-clear.html', ['mac', 'amd'], bug=308328) self.Skip('conformance/textures/tex-image-and-sub-image-2d-with-array-buffer-view.html', ['mac', 'amd'], bug=308328) self.Skip('conformance/textures/tex-image-and-sub-image-2d-with-image-data.html', ['mac', 'amd'], bug=308328) self.Skip('conformance/textures/tex-image-and-sub-image-2d-with-image-data-rgb565.html', ['mac', 'amd'], bug=308328) self.Skip('conformance/textures/tex-image-and-sub-image-2d-with-image-data-rgba4444.html', ['mac', 'amd'], bug=308328) self.Skip('conformance/textures/tex-image-and-sub-image-2d-with-image-data-rgba5551.html', ['mac', 'amd'], bug=308328) self.Fail('conformance/canvas/drawingbuffer-test.html', ['mac', 'amd'], bug=314997) # Linux/NVIDIA failures self.Fail('conformance/glsl/misc/empty_main.vert.html', ['linux', ('nvidia', 0x1040)], bug=325884) self.Fail('conformance/glsl/misc/gl_position_unset.vert.html', ['linux', ('nvidia', 0x1040)], bug=325884) self.Fail('conformance/uniforms/uniform-location.html', ['linux', ('nvidia', 0x1040)], bug=325884) # Android failures self.Fail('conformance/textures/texture-npot-video.html', ['android'], bug=306485) # The following test is very slow and therefore times out on Android bot. self.Skip('conformance/rendering/multisample-corruption.html', ['android']) self.Fail('conformance/canvas/drawingbuffer-test.html', ['android'], bug=314997) self.Fail('conformance/glsl/misc/empty_main.vert.html', ['android'], bug=315976) self.Fail('conformance/glsl/misc/gl_position_unset.vert.html', ['android'], bug=315976) # Skip slow tests. self.Skip('conformance/context/context-creation-and-destruction.html', bug=322689) self.Skip('conformance/rendering/multisample-corruption.html', bug=322689)
bsd-3-clause
MycChiu/tensorflow
third_party/llvm/expand_cmake_vars.py
168
2679
# 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. # ============================================================================== """Expands CMake variables in a text file.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re import sys _CMAKE_DEFINE_REGEX = re.compile(r"\s*#cmakedefine\s+([A-Za-z_0-9]*)(\s.*)?$") _CMAKE_DEFINE01_REGEX = re.compile(r"\s*#cmakedefine01\s+([A-Za-z_0-9]*)") _CMAKE_VAR_REGEX = re.compile(r"\${([A-Za-z_0-9]*)}") def _parse_args(argv): """Parses arguments with the form KEY=VALUE into a dictionary.""" result = {} for arg in argv: k, v = arg.split("=") result[k] = v return result def _expand_variables(input_str, cmake_vars): """Expands ${VARIABLE}s in 'input_str', using dictionary 'cmake_vars'. Args: input_str: the string containing ${VARIABLE} expressions to expand. cmake_vars: a dictionary mapping variable names to their values. Returns: The expanded string. """ def replace(match): if match.group(1) in cmake_vars: return cmake_vars[match.group(1)] return "" return _CMAKE_VAR_REGEX.sub(replace, input_str) def _expand_cmakedefines(line, cmake_vars): """Expands #cmakedefine declarations, using a dictionary 'cmake_vars'.""" # Handles #cmakedefine lines match = _CMAKE_DEFINE_REGEX.match(line) if match: name = match.group(1) suffix = match.group(2) or "" if name in cmake_vars: return "#define {}{}\n".format(name, _expand_variables(suffix, cmake_vars)) else: return "/* #undef {} */\n".format(name) # Handles #cmakedefine01 lines match = _CMAKE_DEFINE01_REGEX.match(line) if match: name = match.group(1) value = cmake_vars.get(name, "0") return "#define {} {}\n".format(name, value) # Otherwise return the line unchanged. return _expand_variables(line, cmake_vars) def main(): cmake_vars = _parse_args(sys.argv[1:]) for line in sys.stdin: sys.stdout.write(_expand_cmakedefines(line, cmake_vars)) if __name__ == "__main__": main()
apache-2.0
charbeljc/account-financial-tools
account_constraints/model/account_move.py
36
1613
# -*- coding: utf-8 -*- ############################################################################## # # Author Joel Grand-Guillaume. Copyright 2012 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/>. # ############################################################################## from openerp import models, api, exceptions, _ class AccountMove(models.Model): _inherit = "account.move" @api.constrains('journal_id', 'period_id', 'date') def _check_fiscal_year(self): for move in self: if move.journal_id.allow_date_fy: date_start = move.period_id.fiscalyear_id.date_start date_stop = move.period_id.fiscalyear_id.date_stop if not date_start <= move.date <= date_stop: raise exceptions.Warning( _('You cannot create entries with date not in the ' 'fiscal year of the chosen period')) return True
agpl-3.0
EdDev/vdsm
lib/vdsm/network/netinfo/qos.py
1
2562
# # Copyright 2015 Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license from __future__ import absolute_import from collections import defaultdict from vdsm.network import tc NON_VLANNED_ID = 5000 DEFAULT_CLASSID = '%x' % NON_VLANNED_ID def report_network_qos(nets_info, devs_info): """Augment netinfo information with QoS data for the engine""" qdiscs = defaultdict(list) for qdisc in tc.qdiscs(dev=None): # None -> all dev qdiscs qdiscs[qdisc['dev']].append(qdisc) for net, attrs in nets_info.iteritems(): iface = attrs['iface'] if iface in devs_info['bridges']: host_ports = [port for port in attrs['ports'] if not port.startswith('vnet')] if not host_ports: # Port-less bridge continue iface, = host_ports if iface in devs_info['vlans']: vlan_id = devs_info['vlans'][iface]['vlanid'] iface = devs_info['vlans'][iface]['iface'] iface_qdiscs = qdiscs.get(iface) if iface_qdiscs is None: continue class_id = (get_root_qdisc(iface_qdiscs)['handle'] + '%x' % vlan_id) else: iface_qdiscs = qdiscs.get(iface) if iface_qdiscs is None: continue class_id = (get_root_qdisc(iface_qdiscs)['handle'] + DEFAULT_CLASSID) # Now that iface is either a bond or a nic, let's get the QoS info classes = [cls for cls in tc.classes(iface, classid=class_id) if cls['kind'] == 'hfsc'] if classes: cls, = classes attrs['hostQos'] = {'out': cls['hfsc']} def get_root_qdisc(qdiscs): for qdisc in qdiscs: if 'root' in qdisc: return qdisc
gpl-2.0
bandoche/python-oauth2
tests/test_oauth.py
301
53269
# -*- coding: utf-8 -*- """ The MIT License Copyright (c) 2009 Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import sys import os import unittest import oauth2 as oauth import random import time import urllib import urlparse from types import ListType import mock import httplib2 # Fix for python2.5 compatibility try: from urlparse import parse_qs, parse_qsl except ImportError: from cgi import parse_qs, parse_qsl sys.path[0:0] = [os.path.join(os.path.dirname(__file__), ".."),] class TestError(unittest.TestCase): def test_message(self): try: raise oauth.Error except oauth.Error, e: self.assertEqual(e.message, 'OAuth error occurred.') msg = 'OMG THINGS BROKE!!!!' try: raise oauth.Error(msg) except oauth.Error, e: self.assertEqual(e.message, msg) def test_str(self): try: raise oauth.Error except oauth.Error, e: self.assertEquals(str(e), 'OAuth error occurred.') class TestGenerateFunctions(unittest.TestCase): def test_build_auth_header(self): header = oauth.build_authenticate_header() self.assertEqual(header['WWW-Authenticate'], 'OAuth realm=""') self.assertEqual(len(header), 1) realm = 'http://example.myrealm.com/' header = oauth.build_authenticate_header(realm) self.assertEqual(header['WWW-Authenticate'], 'OAuth realm="%s"' % realm) self.assertEqual(len(header), 1) def test_build_xoauth_string(self): consumer = oauth.Consumer('consumer_token', 'consumer_secret') token = oauth.Token('user_token', 'user_secret') url = "https://mail.google.com/mail/b/joe@example.com/imap/" xoauth_string = oauth.build_xoauth_string(url, consumer, token) method, oauth_url, oauth_string = xoauth_string.split(' ') self.assertEqual("GET", method) self.assertEqual(url, oauth_url) returned = {} parts = oauth_string.split(',') for part in parts: var, val = part.split('=') returned[var] = val.strip('"') self.assertEquals('HMAC-SHA1', returned['oauth_signature_method']) self.assertEquals('user_token', returned['oauth_token']) self.assertEquals('consumer_token', returned['oauth_consumer_key']) self.assertTrue('oauth_signature' in returned, 'oauth_signature') def test_escape(self): string = 'http://whatever.com/~someuser/?test=test&other=other' self.assert_('~' in oauth.escape(string)) string = '../../../../../../../etc/passwd' self.assert_('../' not in oauth.escape(string)) def test_gen_nonce(self): nonce = oauth.generate_nonce() self.assertEqual(len(nonce), 8) nonce = oauth.generate_nonce(20) self.assertEqual(len(nonce), 20) def test_gen_verifier(self): verifier = oauth.generate_verifier() self.assertEqual(len(verifier), 8) verifier = oauth.generate_verifier(16) self.assertEqual(len(verifier), 16) def test_gen_timestamp(self): exp = int(time.time()) now = oauth.generate_timestamp() self.assertEqual(exp, now) class TestConsumer(unittest.TestCase): def setUp(self): self.key = 'my-key' self.secret = 'my-secret' self.consumer = oauth.Consumer(key=self.key, secret=self.secret) def test_init(self): self.assertEqual(self.consumer.key, self.key) self.assertEqual(self.consumer.secret, self.secret) def test_basic(self): self.assertRaises(ValueError, lambda: oauth.Consumer(None, None)) self.assertRaises(ValueError, lambda: oauth.Consumer('asf', None)) self.assertRaises(ValueError, lambda: oauth.Consumer(None, 'dasf')) def test_str(self): res = dict(parse_qsl(str(self.consumer))) self.assertTrue('oauth_consumer_key' in res) self.assertTrue('oauth_consumer_secret' in res) self.assertEquals(res['oauth_consumer_key'], self.consumer.key) self.assertEquals(res['oauth_consumer_secret'], self.consumer.secret) class TestToken(unittest.TestCase): def setUp(self): self.key = 'my-key' self.secret = 'my-secret' self.token = oauth.Token(self.key, self.secret) def test_basic(self): self.assertRaises(ValueError, lambda: oauth.Token(None, None)) self.assertRaises(ValueError, lambda: oauth.Token('asf', None)) self.assertRaises(ValueError, lambda: oauth.Token(None, 'dasf')) def test_init(self): self.assertEqual(self.token.key, self.key) self.assertEqual(self.token.secret, self.secret) self.assertEqual(self.token.callback, None) self.assertEqual(self.token.callback_confirmed, None) self.assertEqual(self.token.verifier, None) def test_set_callback(self): self.assertEqual(self.token.callback, None) self.assertEqual(self.token.callback_confirmed, None) cb = 'http://www.example.com/my-callback' self.token.set_callback(cb) self.assertEqual(self.token.callback, cb) self.assertEqual(self.token.callback_confirmed, 'true') self.token.set_callback(None) self.assertEqual(self.token.callback, None) # TODO: The following test should probably not pass, but it does # To fix this, check for None and unset 'true' in set_callback # Additionally, should a confirmation truly be done of the callback? self.assertEqual(self.token.callback_confirmed, 'true') def test_set_verifier(self): self.assertEqual(self.token.verifier, None) v = oauth.generate_verifier() self.token.set_verifier(v) self.assertEqual(self.token.verifier, v) self.token.set_verifier() self.assertNotEqual(self.token.verifier, v) self.token.set_verifier('') self.assertEqual(self.token.verifier, '') def test_get_callback_url(self): self.assertEqual(self.token.get_callback_url(), None) self.token.set_verifier() self.assertEqual(self.token.get_callback_url(), None) cb = 'http://www.example.com/my-callback?save=1&return=true' v = oauth.generate_verifier() self.token.set_callback(cb) self.token.set_verifier(v) url = self.token.get_callback_url() verifier_str = '&oauth_verifier=%s' % v self.assertEqual(url, '%s%s' % (cb, verifier_str)) cb = 'http://www.example.com/my-callback-no-query' v = oauth.generate_verifier() self.token.set_callback(cb) self.token.set_verifier(v) url = self.token.get_callback_url() verifier_str = '?oauth_verifier=%s' % v self.assertEqual(url, '%s%s' % (cb, verifier_str)) def test_to_string(self): string = 'oauth_token_secret=%s&oauth_token=%s' % (self.secret, self.key) self.assertEqual(self.token.to_string(), string) self.token.set_callback('http://www.example.com/my-callback') string += '&oauth_callback_confirmed=true' self.assertEqual(self.token.to_string(), string) def _compare_tokens(self, new): self.assertEqual(self.token.key, new.key) self.assertEqual(self.token.secret, new.secret) # TODO: What about copying the callback to the new token? # self.assertEqual(self.token.callback, new.callback) self.assertEqual(self.token.callback_confirmed, new.callback_confirmed) # TODO: What about copying the verifier to the new token? # self.assertEqual(self.token.verifier, new.verifier) def test_to_string(self): tok = oauth.Token('tooken', 'seecret') self.assertEqual(str(tok), 'oauth_token_secret=seecret&oauth_token=tooken') def test_from_string(self): self.assertRaises(ValueError, lambda: oauth.Token.from_string('')) self.assertRaises(ValueError, lambda: oauth.Token.from_string('blahblahblah')) self.assertRaises(ValueError, lambda: oauth.Token.from_string('blah=blah')) self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token_secret=asfdasf')) self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token_secret=')) self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token=asfdasf')) self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token=')) self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token=&oauth_token_secret=')) self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token=tooken%26oauth_token_secret=seecret')) string = self.token.to_string() new = oauth.Token.from_string(string) self._compare_tokens(new) self.token.set_callback('http://www.example.com/my-callback') string = self.token.to_string() new = oauth.Token.from_string(string) self._compare_tokens(new) class ReallyEqualMixin: def failUnlessReallyEqual(self, a, b, msg=None): self.failUnlessEqual(a, b, msg=msg) self.failUnlessEqual(type(a), type(b), msg="a :: %r, b :: %r, %r" % (a, b, msg)) class TestFuncs(unittest.TestCase): def test_to_unicode(self): self.failUnlessRaises(TypeError, oauth.to_unicode, '\xae') self.failUnlessRaises(TypeError, oauth.to_unicode_optional_iterator, '\xae') self.failUnlessRaises(TypeError, oauth.to_unicode_optional_iterator, ['\xae']) self.failUnlessEqual(oauth.to_unicode(':-)'), u':-)') self.failUnlessEqual(oauth.to_unicode(u'\u00ae'), u'\u00ae') self.failUnlessEqual(oauth.to_unicode('\xc2\xae'), u'\u00ae') self.failUnlessEqual(oauth.to_unicode_optional_iterator([':-)']), [u':-)']) self.failUnlessEqual(oauth.to_unicode_optional_iterator([u'\u00ae']), [u'\u00ae']) class TestRequest(unittest.TestCase, ReallyEqualMixin): def test_setter(self): url = "http://example.com" method = "GET" req = oauth.Request(method) self.assertTrue(not hasattr(req, 'url') or req.url is None) self.assertTrue(not hasattr(req, 'normalized_url') or req.normalized_url is None) def test_deleter(self): url = "http://example.com" method = "GET" req = oauth.Request(method, url) try: del req.url url = req.url self.fail("AttributeError should have been raised on empty url.") except AttributeError: pass except Exception, e: self.fail(str(e)) def test_url(self): url1 = "http://example.com:80/foo.php" url2 = "https://example.com:443/foo.php" exp1 = "http://example.com/foo.php" exp2 = "https://example.com/foo.php" method = "GET" req = oauth.Request(method, url1) self.assertEquals(req.normalized_url, exp1) self.assertEquals(req.url, url1) req = oauth.Request(method, url2) self.assertEquals(req.normalized_url, exp2) self.assertEquals(req.url, url2) def test_bad_url(self): request = oauth.Request() try: request.url = "ftp://example.com" self.fail("Invalid URL scheme was accepted.") except ValueError: pass def test_unset_consumer_and_token(self): consumer = oauth.Consumer('my_consumer_key', 'my_consumer_secret') token = oauth.Token('my_key', 'my_secret') request = oauth.Request("GET", "http://example.com/fetch.php") request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token) self.assertEquals(consumer.key, request['oauth_consumer_key']) self.assertEquals(token.key, request['oauth_token']) def test_no_url_set(self): consumer = oauth.Consumer('my_consumer_key', 'my_consumer_secret') token = oauth.Token('my_key', 'my_secret') request = oauth.Request() try: try: request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token) except TypeError: self.fail("Signature method didn't check for a normalized URL.") except ValueError: pass def test_url_query(self): url = "https://www.google.com/m8/feeds/contacts/default/full/?alt=json&max-contacts=10" normalized_url = urlparse.urlunparse(urlparse.urlparse(url)[:3] + (None, None, None)) method = "GET" req = oauth.Request(method, url) self.assertEquals(req.url, url) self.assertEquals(req.normalized_url, normalized_url) def test_get_parameter(self): url = "http://example.com" method = "GET" params = {'oauth_consumer' : 'asdf'} req = oauth.Request(method, url, parameters=params) self.assertEquals(req.get_parameter('oauth_consumer'), 'asdf') self.assertRaises(oauth.Error, req.get_parameter, 'blah') def test_get_nonoauth_parameters(self): oauth_params = { 'oauth_consumer': 'asdfasdfasdf' } other_params = { u'foo': u'baz', u'bar': u'foo', u'multi': [u'FOO',u'BAR'], u'uni_utf8': u'\xae', u'uni_unicode': u'\u00ae', u'uni_unicode_2': u'åÅøØ', } params = oauth_params params.update(other_params) req = oauth.Request("GET", "http://example.com", params) self.assertEquals(other_params, req.get_nonoauth_parameters()) def test_to_header(self): realm = "http://sp.example.com/" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", 'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", } req = oauth.Request("GET", realm, params) header, value = req.to_header(realm).items()[0] parts = value.split('OAuth ') vars = parts[1].split(', ') self.assertTrue(len(vars), (len(params) + 1)) res = {} for v in vars: var, val = v.split('=') res[var] = urllib.unquote(val.strip('"')) self.assertEquals(realm, res['realm']) del res['realm'] self.assertTrue(len(res), len(params)) for key, val in res.items(): self.assertEquals(val, params.get(key)) def test_to_postdata_nonascii(self): realm = "http://sp.example.com/" params = { 'nonasciithing': u'q\xbfu\xe9 ,aasp u?..a.s', 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", 'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", } req = oauth.Request("GET", realm, params) self.failUnlessReallyEqual(req.to_postdata(), 'nonasciithing=q%C2%BFu%C3%A9%20%2Caasp%20u%3F..a.s&oauth_nonce=4572616e48616d6d65724c61686176&oauth_timestamp=137131200&oauth_consumer_key=0685bd9184jfhq22&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=ad180jjd733klru7&oauth_signature=wOJIO9A2W5mFwDgiDvZbTSMK%252FPY%253D') def test_to_postdata(self): realm = "http://sp.example.com/" params = { 'multi': ['FOO','BAR'], 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", 'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", } req = oauth.Request("GET", realm, params) flat = [('multi','FOO'),('multi','BAR')] del params['multi'] flat.extend(params.items()) kf = lambda x: x[0] self.assertEquals(sorted(flat, key=kf), sorted(parse_qsl(req.to_postdata()), key=kf)) def test_to_url(self): url = "http://sp.example.com/" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", 'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", } req = oauth.Request("GET", url, params) exp = urlparse.urlparse("%s?%s" % (url, urllib.urlencode(params))) res = urlparse.urlparse(req.to_url()) self.assertEquals(exp.scheme, res.scheme) self.assertEquals(exp.netloc, res.netloc) self.assertEquals(exp.path, res.path) a = parse_qs(exp.query) b = parse_qs(res.query) self.assertEquals(a, b) def test_to_url_with_query(self): url = "https://www.google.com/m8/feeds/contacts/default/full/?alt=json&max-contacts=10" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", 'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", } req = oauth.Request("GET", url, params) # Note: the url above already has query parameters, so append new ones with & exp = urlparse.urlparse("%s&%s" % (url, urllib.urlencode(params))) res = urlparse.urlparse(req.to_url()) self.assertEquals(exp.scheme, res.scheme) self.assertEquals(exp.netloc, res.netloc) self.assertEquals(exp.path, res.path) a = parse_qs(exp.query) b = parse_qs(res.query) self.assertTrue('alt' in b) self.assertTrue('max-contacts' in b) self.assertEquals(b['alt'], ['json']) self.assertEquals(b['max-contacts'], ['10']) self.assertEquals(a, b) def test_signature_base_string_nonascii_nonutf8(self): consumer = oauth.Consumer('consumer_token', 'consumer_secret') url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\u2766,+CA' req = oauth.Request("GET", url) self.failUnlessReallyEqual(req.normalized_url, u'http://api.simplegeo.com/1.0/places/address.json') req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\xe2\x9d\xa6,+CA' req = oauth.Request("GET", url) self.failUnlessReallyEqual(req.normalized_url, u'http://api.simplegeo.com/1.0/places/address.json') req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA' req = oauth.Request("GET", url) self.failUnlessReallyEqual(req.normalized_url, u'http://api.simplegeo.com/1.0/places/address.json') req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA' req = oauth.Request("GET", url) self.failUnlessReallyEqual(req.normalized_url, u'http://api.simplegeo.com/1.0/places/address.json') req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) self.failUnlessReallyEqual(req['oauth_signature'], 'WhufgeZKyYpKsI70GZaiDaYwl6g=') def test_signature_base_string_with_query(self): url = "https://www.google.com/m8/feeds/contacts/default/full/?alt=json&max-contacts=10" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", 'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", } req = oauth.Request("GET", url, params) self.assertEquals(req.normalized_url, 'https://www.google.com/m8/feeds/contacts/default/full/') self.assertEquals(req.url, 'https://www.google.com/m8/feeds/contacts/default/full/?alt=json&max-contacts=10') normalized_params = parse_qsl(req.get_normalized_parameters()) self.assertTrue(len(normalized_params), len(params) + 2) normalized_params = dict(normalized_params) for key, value in params.iteritems(): if key == 'oauth_signature': continue self.assertEquals(value, normalized_params[key]) self.assertEquals(normalized_params['alt'], 'json') self.assertEquals(normalized_params['max-contacts'], '10') def test_get_normalized_parameters_empty(self): url = "http://sp.example.com/?empty=" req = oauth.Request("GET", url) res = req.get_normalized_parameters() expected='empty=' self.assertEquals(expected, res) def test_get_normalized_parameters_duplicate(self): url = "http://example.com/v2/search/videos?oauth_nonce=79815175&oauth_timestamp=1295397962&oauth_consumer_key=mykey&oauth_signature_method=HMAC-SHA1&q=car&oauth_version=1.0&offset=10&oauth_signature=spWLI%2FGQjid7sQVd5%2FarahRxzJg%3D" req = oauth.Request("GET", url) res = req.get_normalized_parameters() expected='oauth_consumer_key=mykey&oauth_nonce=79815175&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1295397962&oauth_version=1.0&offset=10&q=car' self.assertEquals(expected, res) def test_get_normalized_parameters_from_url(self): # example copied from # https://github.com/ciaranj/node-oauth/blob/master/tests/oauth.js # which in turns says that it was copied from # http://oauth.net/core/1.0/#sig_base_example . url = "http://photos.example.net/photos?file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original" req = oauth.Request("GET", url) res = req.get_normalized_parameters() expected = 'file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original' self.assertEquals(expected, res) def test_signing_base(self): # example copied from # https://github.com/ciaranj/node-oauth/blob/master/tests/oauth.js # which in turns says that it was copied from # http://oauth.net/core/1.0/#sig_base_example . url = "http://photos.example.net/photos?file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original" req = oauth.Request("GET", url) sm = oauth.SignatureMethod_HMAC_SHA1() consumer = oauth.Consumer('dpf43f3p2l4k3l03', 'foo') key, raw = sm.signing_base(req, consumer, None) expected = 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal' self.assertEquals(expected, raw) def test_get_normalized_parameters(self): url = "http://sp.example.com/" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", 'multi': ['FOO','BAR', u'\u00ae', '\xc2\xae'], 'multi_same': ['FOO','FOO'], 'uni_utf8_bytes': '\xc2\xae', 'uni_unicode_object': u'\u00ae' } req = oauth.Request("GET", url, params) res = req.get_normalized_parameters() expected='multi=BAR&multi=FOO&multi=%C2%AE&multi=%C2%AE&multi_same=FOO&multi_same=FOO&oauth_consumer_key=0685bd9184jfhq22&oauth_nonce=4572616e48616d6d65724c61686176&oauth_signature_method=HMAC-SHA1&oauth_timestamp=137131200&oauth_token=ad180jjd733klru7&oauth_version=1.0&uni_unicode_object=%C2%AE&uni_utf8_bytes=%C2%AE' self.assertEquals(expected, res) def test_get_normalized_parameters_ignores_auth_signature(self): url = "http://sp.example.com/" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_signature': "some-random-signature-%d" % random.randint(1000, 2000), 'oauth_token': "ad180jjd733klru7", } req = oauth.Request("GET", url, params) res = req.get_normalized_parameters() self.assertNotEquals(urllib.urlencode(sorted(params.items())), res) foo = params.copy() del foo["oauth_signature"] self.assertEqual(urllib.urlencode(sorted(foo.items())), res) def test_set_signature_method(self): consumer = oauth.Consumer('key', 'secret') client = oauth.Client(consumer) class Blah: pass try: client.set_signature_method(Blah()) self.fail("Client.set_signature_method() accepted invalid method.") except ValueError: pass m = oauth.SignatureMethod_HMAC_SHA1() client.set_signature_method(m) self.assertEquals(m, client.method) def test_get_normalized_string_escapes_spaces_properly(self): url = "http://sp.example.com/" params = { "some_random_data": random.randint(100, 1000), "data": "This data with a random number (%d) has spaces!" % random.randint(1000, 2000), } req = oauth.Request("GET", url, params) res = req.get_normalized_parameters() expected = urllib.urlencode(sorted(params.items())).replace('+', '%20') self.assertEqual(expected, res) @mock.patch('oauth2.Request.make_timestamp') @mock.patch('oauth2.Request.make_nonce') def test_request_nonutf8_bytes(self, mock_make_nonce, mock_make_timestamp): mock_make_nonce.return_value = 5 mock_make_timestamp.return_value = 6 tok = oauth.Token(key="tok-test-key", secret="tok-test-secret") con = oauth.Consumer(key="con-test-key", secret="con-test-secret") params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_token': tok.key, 'oauth_consumer_key': con.key } # If someone passes a sequence of bytes which is not ascii for # url, we'll raise an exception as early as possible. url = "http://sp.example.com/\x92" # It's actually cp1252-encoding... self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) # And if they pass an unicode, then we'll use it. url = u'http://sp.example.com/\u2019' req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_signature'], 'cMzvCkhvLL57+sTIxLITTHfkqZk=') # And if it is a utf-8-encoded-then-percent-encoded non-ascii # thing, we'll decode it and use it. url = "http://sp.example.com/%E2%80%99" req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_signature'], 'yMLKOyNKC/DkyhUOb8DLSvceEWE=') # Same thing with the params. url = "http://sp.example.com/" # If someone passes a sequence of bytes which is not ascii in # params, we'll raise an exception as early as possible. params['non_oauth_thing'] = '\xae', # It's actually cp1252-encoding... self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) # And if they pass a unicode, then we'll use it. params['non_oauth_thing'] = u'\u2019' req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_signature'], '0GU50m0v60CVDB5JnoBXnvvvKx4=') # And if it is a utf-8-encoded non-ascii thing, we'll decode # it and use it. params['non_oauth_thing'] = '\xc2\xae' req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_signature'], 'pqOCu4qvRTiGiXB8Z61Jsey0pMM=') # Also if there are non-utf8 bytes in the query args. url = "http://sp.example.com/?q=\x92" # cp1252 self.assertRaises(TypeError, oauth.Request, method="GET", url=url, parameters=params) def test_request_hash_of_body(self): tok = oauth.Token(key="token", secret="tok-test-secret") con = oauth.Consumer(key="consumer", secret="con-test-secret") # Example 1a from Appendix A.1 of # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # Except that we get a differetn result than they do. params = { 'oauth_version': "1.0", 'oauth_token': tok.key, 'oauth_nonce': 10288510250934, 'oauth_timestamp': 1236874155, 'oauth_consumer_key': con.key } url = u"http://www.example.com/resource" req = oauth.Request(method="PUT", url=url, parameters=params, body="Hello World!", is_form_encoded=False) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_body_hash'], 'Lve95gjOVATpfV8EL5X4nxwjKHE=') self.failUnlessReallyEqual(req['oauth_signature'], 't+MX8l/0S8hdbVQL99nD0X1fPnM=') # oauth-bodyhash.html A.1 has # '08bUFF%2Fjmp59mWB7cSgCYBUpJ0U%3D', but I don't see how that # is possible. # Example 1b params = { 'oauth_version': "1.0", 'oauth_token': tok.key, 'oauth_nonce': 10369470270925, 'oauth_timestamp': 1236874236, 'oauth_consumer_key': con.key } req = oauth.Request(method="PUT", url=url, parameters=params, body="Hello World!", is_form_encoded=False) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_body_hash'], 'Lve95gjOVATpfV8EL5X4nxwjKHE=') self.failUnlessReallyEqual(req['oauth_signature'], 'CTFmrqJIGT7NsWJ42OrujahTtTc=') # Appendix A.2 params = { 'oauth_version': "1.0", 'oauth_token': tok.key, 'oauth_nonce': 8628868109991, 'oauth_timestamp': 1238395022, 'oauth_consumer_key': con.key } req = oauth.Request(method="GET", url=url, parameters=params, is_form_encoded=False) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, None) self.failUnlessReallyEqual(req['oauth_body_hash'], '2jmj7l5rSw0yVb/vlWAYkK/YBwk=') self.failUnlessReallyEqual(req['oauth_signature'], 'Zhl++aWSP0O3/hYQ0CuBc7jv38I=') def test_sign_request(self): url = "http://sp.example.com/" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200" } tok = oauth.Token(key="tok-test-key", secret="tok-test-secret") con = oauth.Consumer(key="con-test-key", secret="con-test-secret") params['oauth_token'] = tok.key params['oauth_consumer_key'] = con.key req = oauth.Request(method="GET", url=url, parameters=params) methods = { 'DX01TdHws7OninCLK9VztNTH1M4=': oauth.SignatureMethod_HMAC_SHA1(), 'con-test-secret&tok-test-secret': oauth.SignatureMethod_PLAINTEXT() } for exp, method in methods.items(): req.sign_request(method, con, tok) self.assertEquals(req['oauth_signature_method'], method.name) self.assertEquals(req['oauth_signature'], exp) # Also if there are non-ascii chars in the URL. url = "http://sp.example.com/\xe2\x80\x99" # utf-8 bytes req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) self.assertEquals(req['oauth_signature'], 'loFvp5xC7YbOgd9exIO6TxB7H4s=') url = u'http://sp.example.com/\u2019' # Python unicode object req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) self.assertEquals(req['oauth_signature'], 'loFvp5xC7YbOgd9exIO6TxB7H4s=') # Also if there are non-ascii chars in the query args. url = "http://sp.example.com/?q=\xe2\x80\x99" # utf-8 bytes req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) self.assertEquals(req['oauth_signature'], 'IBw5mfvoCsDjgpcsVKbyvsDqQaU=') url = u'http://sp.example.com/?q=\u2019' # Python unicode object req = oauth.Request(method="GET", url=url, parameters=params) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), con, tok) self.assertEquals(req['oauth_signature'], 'IBw5mfvoCsDjgpcsVKbyvsDqQaU=') def test_from_request(self): url = "http://sp.example.com/" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", 'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", } req = oauth.Request("GET", url, params) headers = req.to_header() # Test from the headers req = oauth.Request.from_request("GET", url, headers) self.assertEquals(req.method, "GET") self.assertEquals(req.url, url) self.assertEquals(params, req.copy()) # Test with bad OAuth headers bad_headers = { 'Authorization' : 'OAuth this is a bad header' } self.assertRaises(oauth.Error, oauth.Request.from_request, "GET", url, bad_headers) # Test getting from query string qs = urllib.urlencode(params) req = oauth.Request.from_request("GET", url, query_string=qs) exp = parse_qs(qs, keep_blank_values=False) for k, v in exp.iteritems(): exp[k] = urllib.unquote(v[0]) self.assertEquals(exp, req.copy()) # Test that a boned from_request() call returns None req = oauth.Request.from_request("GET", url) self.assertEquals(None, req) def test_from_token_and_callback(self): url = "http://sp.example.com/" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': "137131200", 'oauth_consumer_key': "0685bd9184jfhq22", 'oauth_signature_method': "HMAC-SHA1", 'oauth_token': "ad180jjd733klru7", 'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", } tok = oauth.Token(key="tok-test-key", secret="tok-test-secret") req = oauth.Request.from_token_and_callback(tok) self.assertFalse('oauth_callback' in req) self.assertEquals(req['oauth_token'], tok.key) req = oauth.Request.from_token_and_callback(tok, callback=url) self.assertTrue('oauth_callback' in req) self.assertEquals(req['oauth_callback'], url) def test_from_consumer_and_token(self): url = "http://sp.example.com/" tok = oauth.Token(key="tok-test-key", secret="tok-test-secret") tok.set_verifier('this_is_a_test_verifier') con = oauth.Consumer(key="con-test-key", secret="con-test-secret") req = oauth.Request.from_consumer_and_token(con, token=tok, http_method="GET", http_url=url) self.assertEquals(req['oauth_token'], tok.key) self.assertEquals(req['oauth_consumer_key'], con.key) self.assertEquals(tok.verifier, req['oauth_verifier']) class SignatureMethod_Bad(oauth.SignatureMethod): name = "BAD" def signing_base(self, request, consumer, token): return "" def sign(self, request, consumer, token): return "invalid-signature" class TestServer(unittest.TestCase): def setUp(self): url = "http://sp.example.com/" params = { 'oauth_version': "1.0", 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': int(time.time()), 'bar': 'blerg', 'multi': ['FOO','BAR'], 'foo': 59 } self.consumer = oauth.Consumer(key="consumer-key", secret="consumer-secret") self.token = oauth.Token(key="token-key", secret="token-secret") params['oauth_token'] = self.token.key params['oauth_consumer_key'] = self.consumer.key self.request = oauth.Request(method="GET", url=url, parameters=params) signature_method = oauth.SignatureMethod_HMAC_SHA1() self.request.sign_request(signature_method, self.consumer, self.token) def test_init(self): server = oauth.Server(signature_methods={'HMAC-SHA1' : oauth.SignatureMethod_HMAC_SHA1()}) self.assertTrue('HMAC-SHA1' in server.signature_methods) self.assertTrue(isinstance(server.signature_methods['HMAC-SHA1'], oauth.SignatureMethod_HMAC_SHA1)) server = oauth.Server() self.assertEquals(server.signature_methods, {}) def test_add_signature_method(self): server = oauth.Server() res = server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1()) self.assertTrue(len(res) == 1) self.assertTrue('HMAC-SHA1' in res) self.assertTrue(isinstance(res['HMAC-SHA1'], oauth.SignatureMethod_HMAC_SHA1)) res = server.add_signature_method(oauth.SignatureMethod_PLAINTEXT()) self.assertTrue(len(res) == 2) self.assertTrue('PLAINTEXT' in res) self.assertTrue(isinstance(res['PLAINTEXT'], oauth.SignatureMethod_PLAINTEXT)) def test_verify_request(self): server = oauth.Server() server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1()) parameters = server.verify_request(self.request, self.consumer, self.token) self.assertTrue('bar' in parameters) self.assertTrue('foo' in parameters) self.assertTrue('multi' in parameters) self.assertEquals(parameters['bar'], 'blerg') self.assertEquals(parameters['foo'], 59) self.assertEquals(parameters['multi'], ['FOO','BAR']) def test_build_authenticate_header(self): server = oauth.Server() headers = server.build_authenticate_header('example.com') self.assertTrue('WWW-Authenticate' in headers) self.assertEquals('OAuth realm="example.com"', headers['WWW-Authenticate']) def test_no_version(self): url = "http://sp.example.com/" params = { 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': int(time.time()), 'bar': 'blerg', 'multi': ['FOO','BAR'], 'foo': 59 } self.consumer = oauth.Consumer(key="consumer-key", secret="consumer-secret") self.token = oauth.Token(key="token-key", secret="token-secret") params['oauth_token'] = self.token.key params['oauth_consumer_key'] = self.consumer.key self.request = oauth.Request(method="GET", url=url, parameters=params) signature_method = oauth.SignatureMethod_HMAC_SHA1() self.request.sign_request(signature_method, self.consumer, self.token) server = oauth.Server() server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1()) parameters = server.verify_request(self.request, self.consumer, self.token) def test_invalid_version(self): url = "http://sp.example.com/" params = { 'oauth_version': '222.9922', 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': int(time.time()), 'bar': 'blerg', 'multi': ['foo','bar'], 'foo': 59 } consumer = oauth.Consumer(key="consumer-key", secret="consumer-secret") token = oauth.Token(key="token-key", secret="token-secret") params['oauth_token'] = token.key params['oauth_consumer_key'] = consumer.key request = oauth.Request(method="GET", url=url, parameters=params) signature_method = oauth.SignatureMethod_HMAC_SHA1() request.sign_request(signature_method, consumer, token) server = oauth.Server() server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1()) self.assertRaises(oauth.Error, server.verify_request, request, consumer, token) def test_invalid_signature_method(self): url = "http://sp.example.com/" params = { 'oauth_version': '1.0', 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': int(time.time()), 'bar': 'blerg', 'multi': ['FOO','BAR'], 'foo': 59 } consumer = oauth.Consumer(key="consumer-key", secret="consumer-secret") token = oauth.Token(key="token-key", secret="token-secret") params['oauth_token'] = token.key params['oauth_consumer_key'] = consumer.key request = oauth.Request(method="GET", url=url, parameters=params) signature_method = SignatureMethod_Bad() request.sign_request(signature_method, consumer, token) server = oauth.Server() server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1()) self.assertRaises(oauth.Error, server.verify_request, request, consumer, token) def test_missing_signature(self): url = "http://sp.example.com/" params = { 'oauth_version': '1.0', 'oauth_nonce': "4572616e48616d6d65724c61686176", 'oauth_timestamp': int(time.time()), 'bar': 'blerg', 'multi': ['FOO','BAR'], 'foo': 59 } consumer = oauth.Consumer(key="consumer-key", secret="consumer-secret") token = oauth.Token(key="token-key", secret="token-secret") params['oauth_token'] = token.key params['oauth_consumer_key'] = consumer.key request = oauth.Request(method="GET", url=url, parameters=params) signature_method = oauth.SignatureMethod_HMAC_SHA1() request.sign_request(signature_method, consumer, token) del request['oauth_signature'] server = oauth.Server() server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1()) self.assertRaises(oauth.MissingSignature, server.verify_request, request, consumer, token) # Request Token: http://oauth-sandbox.sevengoslings.net/request_token # Auth: http://oauth-sandbox.sevengoslings.net/authorize # Access Token: http://oauth-sandbox.sevengoslings.net/access_token # Two-legged: http://oauth-sandbox.sevengoslings.net/two_legged # Three-legged: http://oauth-sandbox.sevengoslings.net/three_legged # Key: bd37aed57e15df53 # Secret: 0e9e6413a9ef49510a4f68ed02cd class TestClient(unittest.TestCase): # oauth_uris = { # 'request_token': '/request_token.php', # 'access_token': '/access_token.php' # } oauth_uris = { 'request_token': '/request_token', 'authorize': '/authorize', 'access_token': '/access_token', 'two_legged': '/two_legged', 'three_legged': '/three_legged' } consumer_key = 'bd37aed57e15df53' consumer_secret = '0e9e6413a9ef49510a4f68ed02cd' host = 'http://oauth-sandbox.sevengoslings.net' def setUp(self): self.consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) self.body = { 'foo': 'bar', 'bar': 'foo', 'multi': ['FOO','BAR'], 'blah': 599999 } def _uri(self, type): uri = self.oauth_uris.get(type) if uri is None: raise KeyError("%s is not a valid OAuth URI type." % type) return "%s%s" % (self.host, uri) def create_simple_multipart_data(self, data): boundary = '---Boundary-%d' % random.randint(1,1000) crlf = '\r\n' items = [] for key, value in data.iteritems(): items += [ '--'+boundary, 'Content-Disposition: form-data; name="%s"'%str(key), '', str(value), ] items += ['', '--'+boundary+'--', ''] content_type = 'multipart/form-data; boundary=%s' % boundary return content_type, crlf.join(items) def test_init(self): class Blah(): pass try: client = oauth.Client(Blah()) self.fail("Client.__init__() accepted invalid Consumer.") except ValueError: pass consumer = oauth.Consumer('token', 'secret') try: client = oauth.Client(consumer, Blah()) self.fail("Client.__init__() accepted invalid Token.") except ValueError: pass def test_access_token_get(self): """Test getting an access token via GET.""" client = oauth.Client(self.consumer, None) resp, content = client.request(self._uri('request_token'), "GET") self.assertEquals(int(resp['status']), 200) def test_access_token_post(self): """Test getting an access token via POST.""" client = oauth.Client(self.consumer, None) resp, content = client.request(self._uri('request_token'), "POST") self.assertEquals(int(resp['status']), 200) res = dict(parse_qsl(content)) self.assertTrue('oauth_token' in res) self.assertTrue('oauth_token_secret' in res) def _two_legged(self, method): client = oauth.Client(self.consumer, None) return client.request(self._uri('two_legged'), method, body=urllib.urlencode(self.body)) def test_two_legged_post(self): """A test of a two-legged OAuth POST request.""" resp, content = self._two_legged("POST") self.assertEquals(int(resp['status']), 200) def test_two_legged_get(self): """A test of a two-legged OAuth GET request.""" resp, content = self._two_legged("GET") self.assertEquals(int(resp['status']), 200) @mock.patch('httplib2.Http.request') def test_multipart_post_does_not_alter_body(self, mockHttpRequest): random_result = random.randint(1,100) data = { 'rand-%d'%random.randint(1,100):random.randint(1,100), } content_type, body = self.create_simple_multipart_data(data) client = oauth.Client(self.consumer, None) uri = self._uri('two_legged') def mockrequest(cl, ur, **kw): self.failUnless(cl is client) self.failUnless(ur is uri) self.failUnlessEqual(frozenset(kw.keys()), frozenset(['method', 'body', 'redirections', 'connection_type', 'headers'])) self.failUnlessEqual(kw['body'], body) self.failUnlessEqual(kw['connection_type'], None) self.failUnlessEqual(kw['method'], 'POST') self.failUnlessEqual(kw['redirections'], httplib2.DEFAULT_MAX_REDIRECTS) self.failUnless(isinstance(kw['headers'], dict)) return random_result mockHttpRequest.side_effect = mockrequest result = client.request(uri, 'POST', headers={'Content-Type':content_type}, body=body) self.assertEqual(result, random_result) @mock.patch('httplib2.Http.request') def test_url_with_query_string(self, mockHttpRequest): uri = 'http://example.com/foo/bar/?show=thundercats&character=snarf' client = oauth.Client(self.consumer, None) random_result = random.randint(1,100) def mockrequest(cl, ur, **kw): self.failUnless(cl is client) self.failUnlessEqual(frozenset(kw.keys()), frozenset(['method', 'body', 'redirections', 'connection_type', 'headers'])) self.failUnlessEqual(kw['body'], '') self.failUnlessEqual(kw['connection_type'], None) self.failUnlessEqual(kw['method'], 'GET') self.failUnlessEqual(kw['redirections'], httplib2.DEFAULT_MAX_REDIRECTS) self.failUnless(isinstance(kw['headers'], dict)) req = oauth.Request.from_consumer_and_token(self.consumer, None, http_method='GET', http_url=uri, parameters={}) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), self.consumer, None) expected = parse_qsl(urlparse.urlparse(req.to_url()).query) actual = parse_qsl(urlparse.urlparse(ur).query) self.failUnlessEqual(len(expected), len(actual)) actual = dict(actual) for key, value in expected: if key not in ('oauth_signature', 'oauth_nonce', 'oauth_timestamp'): self.failUnlessEqual(actual[key], value) return random_result mockHttpRequest.side_effect = mockrequest client.request(uri, 'GET') @mock.patch('httplib2.Http.request') @mock.patch('oauth2.Request.from_consumer_and_token') def test_multiple_values_for_a_key(self, mockReqConstructor, mockHttpRequest): client = oauth.Client(self.consumer, None) request = oauth.Request("GET", "http://example.com/fetch.php", parameters={'multi': ['1', '2']}) mockReqConstructor.return_value = request client.request('http://whatever', 'POST', body='multi=1&multi=2') self.failUnlessEqual(mockReqConstructor.call_count, 1) self.failUnlessEqual(mockReqConstructor.call_args[1]['parameters'], {'multi': ['1', '2']}) self.failUnless('multi=1' in mockHttpRequest.call_args[1]['body']) self.failUnless('multi=2' in mockHttpRequest.call_args[1]['body']) if __name__ == "__main__": unittest.main()
mit
flyher/pymo
android/pgs4a-0.9.6/python-install/lib/python2.7/test/test_cookielib.py
74
72202
# -*- 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 everytime 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)
mit
was4444/chromium.src
chrome/common/extensions/docs/server2/url_fetcher_urllib2.py
37
1153
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import time from future import Future from url_fetcher import UrlFetcher from urllib2 import urlopen, Request, HTTPError class UrlFetcherUrllib2(UrlFetcher): """UrlFetcher implementation for use outside of AppEngine. Does NOT support async fetching, so FetchAsync calls are still blocking. """ class _Response(object): def __init__(self, code, content=None, headers={}): self.status_code = code self.content = content self.headers = headers def FetchImpl(self, url, headers): request = Request(url, headers=headers) try: urlresponse = urlopen(request) response = self._Response(urlresponse.code, urlresponse.read(), urlresponse.headers.dict) urlresponse.close() return response except HTTPError as e: return self._Response(e.code, e.reason, e.headers.dict) def FetchAsyncImpl(self, url, headers): return Future(callback=lambda: self.FetchImpl(url, headers))
bsd-3-clause
Baisang/antcoin
contrib/pyminer/pyminer.py
1257
6438
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file license.txt or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import sys from multiprocessing import Process ERR_SLEEP = 15 MAX_NONCE = 1000000L settings = {} pp = pprint.PrettyPrinter(indent=4) class BitcoinRPC: OBJID = 1 def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) self.authhdr = "Basic %s" % (base64.b64encode(authpair)) self.conn = httplib.HTTPConnection(host, port, False, 30) def rpc(self, method, params=None): self.OBJID += 1 obj = { 'version' : '1.1', 'method' : method, 'id' : self.OBJID } if params is None: obj['params'] = [] else: obj['params'] = params self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self.authhdr, 'Content-type' : 'application/json' }) resp = self.conn.getresponse() if resp is None: print "JSON-RPC: no response" return None body = resp.read() resp_obj = json.loads(body) if resp_obj is None: print "JSON-RPC: cannot JSON-decode body" return None if 'error' in resp_obj and resp_obj['error'] != None: return resp_obj['error'] if 'result' not in resp_obj: print "JSON-RPC: no result in object" return None return resp_obj['result'] def getblockcount(self): return self.rpc('getblockcount') def getwork(self, data=None): return self.rpc('getwork', data) def uint32(x): return x & 0xffffffffL def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) def bufreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): word = struct.unpack('@I', in_buf[i:i+4])[0] out_words.append(struct.pack('@I', bytereverse(word))) return ''.join(out_words) def wordreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): out_words.append(in_buf[i:i+4]) out_words.reverse() return ''.join(out_words) class Miner: def __init__(self, id): self.id = id self.max_nonce = MAX_NONCE def work(self, datastr, targetstr): # decode work data hex string to binary static_data = datastr.decode('hex') static_data = bufreverse(static_data) # the first 76b of 80b do not change blk_hdr = static_data[:76] # decode 256-bit target value targetbin = targetstr.decode('hex') targetbin = targetbin[::-1] # byte-swap and dword-swap targetbin_str = targetbin.encode('hex') target = long(targetbin_str, 16) # pre-hash first 76b of block header static_hash = hashlib.sha256() static_hash.update(blk_hdr) for nonce in xrange(self.max_nonce): # encode 32-bit nonce value nonce_bin = struct.pack("<I", nonce) # hash final 4b, the nonce value hash1_o = static_hash.copy() hash1_o.update(nonce_bin) hash1 = hash1_o.digest() # sha256 hash of sha256 hash hash_o = hashlib.sha256() hash_o.update(hash1) hash = hash_o.digest() # quick test for winning solution: high 32 bits zero? if hash[-4:] != '\0\0\0\0': continue # convert binary hash to 256-bit Python long hash = bufreverse(hash) hash = wordreverse(hash) hash_str = hash.encode('hex') l = long(hash_str, 16) # proof-of-work test: hash < target if l < target: print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,) return (nonce + 1, nonce_bin) else: print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,) # return (nonce + 1, nonce_bin) return (nonce + 1, None) def submit_work(self, rpc, original_data, nonce_bin): nonce_bin = bufreverse(nonce_bin) nonce = nonce_bin.encode('hex') solution = original_data[:152] + nonce + original_data[160:256] param_arr = [ solution ] result = rpc.getwork(param_arr) print time.asctime(), "--> Upstream RPC result:", result def iterate(self, rpc): work = rpc.getwork() if work is None: time.sleep(ERR_SLEEP) return if 'data' not in work or 'target' not in work: time.sleep(ERR_SLEEP) return time_start = time.time() (hashes_done, nonce_bin) = self.work(work['data'], work['target']) time_end = time.time() time_diff = time_end - time_start self.max_nonce = long( (hashes_done * settings['scantime']) / time_diff) if self.max_nonce > 0xfffffffaL: self.max_nonce = 0xfffffffaL if settings['hashmeter']: print "HashMeter(%d): %d hashes, %.2f Khash/sec" % ( self.id, hashes_done, (hashes_done / 1000.0) / time_diff) if nonce_bin is not None: self.submit_work(rpc, work['data'], nonce_bin) def loop(self): rpc = BitcoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpass']) if rpc is None: return while True: self.iterate(rpc) def miner_thread(id): miner = Miner(id) miner.loop() if __name__ == '__main__': if len(sys.argv) != 2: print "Usage: pyminer.py CONFIG-FILE" sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() if 'host' not in settings: settings['host'] = '127.0.0.1' if 'port' not in settings: settings['port'] = 8332 if 'threads' not in settings: settings['threads'] = 1 if 'hashmeter' not in settings: settings['hashmeter'] = 0 if 'scantime' not in settings: settings['scantime'] = 30L if 'rpcuser' not in settings or 'rpcpass' not in settings: print "Missing username and/or password in cfg file" sys.exit(1) settings['port'] = int(settings['port']) settings['threads'] = int(settings['threads']) settings['hashmeter'] = int(settings['hashmeter']) settings['scantime'] = long(settings['scantime']) thr_list = [] for thr_id in range(settings['threads']): p = Process(target=miner_thread, args=(thr_id,)) p.start() thr_list.append(p) time.sleep(1) # stagger threads print settings['threads'], "mining threads started" print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port']) try: for thr_proc in thr_list: thr_proc.join() except KeyboardInterrupt: pass print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port'])
mit
ghchinoy/tensorflow
tensorflow/python/compiler/tensorrt/test/lru_cache_test.py
8
2883
# Copyright 2018 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. # ============================================================================== """Test LRUCache by running different input batch sizes on same network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.platform import test class LRUCacheTest(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, x): conv_filter = constant_op.constant( np.random.randn(3, 3, 2, 1), dtype=dtypes.float32) x = nn.conv2d( input=x, filter=conv_filter, strides=[1, 1, 1, 1], padding="SAME", name="conv") bias = constant_op.constant( np.random.randn(1, 10, 10, 1), dtype=dtypes.float32) x = math_ops.add(x, bias) x = nn.relu(x) return array_ops.identity(x, name="output") def GetParams(self): dtype = dtypes.float32 input_dims = [[[1, 10, 10, 2]], [[2, 10, 10, 2]], [[4, 10, 10, 2]], [[2, 10, 10, 2]]] expected_output_dims = [[[1, 10, 10, 1]], [[2, 10, 10, 1]], [[4, 10, 10, 1]], [[2, 10, 10, 1]]] return trt_test.TfTrtIntegrationTestParams( graph_fn=self.GraphFn, input_specs=[ tensor_spec.TensorSpec([None, 10, 10, 2], dtypes.float32, "input") ], output_specs=[ tensor_spec.TensorSpec([None, 10, 10, 1], dtypes.float32, "output") ], input_dims=input_dims, expected_output_dims=expected_output_dims) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return ["TRTEngineOp_0"] def ShouldRunTest(self, run_params): return (run_params.dynamic_engine and not trt_test.IsQuantizationMode(run_params.precision_mode)) if __name__ == "__main__": test.main()
apache-2.0
twbarber/pygooglevoice
docs/conf.py
39
6454
# -*- coding: utf-8 -*- # # PyGoogleVoice documentation build configuration file, created by # sphinx-quickstart on Sun Nov 29 23:06:36 2009. # # 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.append(os.path.abspath('.')) sys.path.insert(0, '..') # -- General configuration ----------------------------------------------------- # 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.doctest'] # Add any paths that contain templates here, relative to this directory. templates_path = ['templates'] # The suffix of source filenames. source_suffix = '.txt' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'PyGoogleVoice' copyright = u'2009, Justin Quick <justquick@gmail.com>' # 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 = '0.5' # The full version, including alpha/beta/rc tags. release = '0.5' # 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 documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['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 = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. 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_use_modindex = 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, 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 = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'PyGoogleVoicedoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'PyGoogleVoice.tex', u'PyGoogleVoice Documentation', u'Justin Quick \\textless{}justquick@gmail.com\\textgreater{}', '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 # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
bsd-3-clause
EricssonResearch/cerbero
cerbero/packages/packagesstore.py
5
7907
# 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 imp from collections import defaultdict from cerbero.build.cookbook import CookBook from cerbero.config import Platform, Architecture, Distro, DistroVersion,\ License from cerbero.packages import package, PackageType from cerbero.errors import FatalError, PackageNotFoundError from cerbero.utils import _, shell, remove_list_duplicates from cerbero.utils import messages as m class PackagesStore (object): ''' Stores a list of L{cerbero.packages.package.Package} ''' PKG_EXT = '.package' def __init__(self, config, load=True): self._config = config self._packages = {} # package_name -> package self.cookbook = CookBook(config, load) # used in tests to skip loading a dir with packages definitions if not load: return if not os.path.exists(config.packages_dir): raise FatalError(_("Packages dir %s not found") % config.packages_dir) self._load_packages() def get_packages_list(self): ''' Gets the list of packages @return: list of packages @rtype: list ''' packages = self._packages.values() packages.sort(key=lambda x: x.name) return packages def get_package(self, name): ''' Gets a recipe from its name @param name: name of the package @type name: str @return: the package instance @rtype: L{cerbero.packages.package.Package} ''' if name not in self._packages: raise PackageNotFoundError(name) return self._packages[name] def get_package_deps(self, pkg, recursive=False): ''' Gets the dependencies of a package @param package: name of the package or package instance @type package: L{cerbero.packages.package.Package} @return: a list with the package dependencies @rtype: list ''' if isinstance(pkg, str): pkg = self.get_package(pkg) if isinstance(pkg, package.MetaPackage): ret = self._list_metapackage_deps(pkg) else: ret = [self.get_package(x) for x in pkg.deps] # get deps recursively if recursive: for p in ret: ret.extend(self.get_package_deps(p, recursive)) return remove_list_duplicates(ret) def get_package_files_list(self, name): ''' Gets the list of files provided by a package @param name: name of the package @type name: str @return: the package instance @rtype: L{cerbero.packages.package.PackageBase} ''' p = self.get_package(name) if isinstance(p, package.MetaPackage): return sorted(self._list_metapackage_files(p)) else: return sorted(p.files_list()) def add_package(self, package): ''' Adds a new package to the store @param package: the package to add @type package: L{cerbero.packages.package.PackageBase} ''' self._packages[package.name] = package def get_package_recipes_deps(self, package_name): ''' Gets the list of recipes needed to create this package @param name: name of the package @type name: str @return: a list with the recipes required to build this package @rtype: list ''' deps = self.get_package_deps(package_name) return [self.cookbok.get_recipe(x) for x in deps] def _list_metapackage_deps(self, metapackage): def get_package_deps(package_name, visited=[], depslist=[]): if package_name in visited: return visited.append(package_name) p = self.get_package(package_name) depslist.append(p) for p_name in p.deps: get_package_deps(p_name, visited, depslist) return depslist deps = [] for p in metapackage.list_packages(): deps.extend(get_package_deps(p, [], [])) return remove_list_duplicates(deps) def _list_metapackage_files(self, metapackage): l = [] for p in self._list_metapackage_deps(metapackage): l.extend(p.files_list()) # remove duplicates and sort return sorted(list(set(l))) def _load_packages(self): self._packages = {} packages = defaultdict(dict) repos = self._config.get_packages_repos() for reponame, (repodir, priority) in repos.iteritems(): packages[int(priority)].update( self._load_packages_from_dir(repodir)) # Add recipes by asceding pripority for key in sorted(packages.keys()): self._packages.update(packages[key]) def _load_packages_from_dir(self, repo): packages_dict = {} packages = shell.find_files('*%s' % self.PKG_EXT, repo) packages.extend(shell.find_files('*/*%s' % self.PKG_EXT, repo)) try: custom = None m_path = os.path.join(repo, 'custom.py') if os.path.exists(m_path): custom = imp.load_source('custom', m_path) except Exception, ex: # import traceback # traceback.print_exc() # m.warning("Error loading package %s" % ex) custom = None for f in packages: p = self._load_package_from_file(f, custom) if p is None: m.warning(_("Could not found a valid package in %s") % f) continue p.__file__ = os.path.abspath(f) packages_dict[p.name] = p return packages_dict def _load_package_from_file(self, filepath, custom=None): mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1]) try: d = {'Platform': Platform, 'Architecture': Architecture, 'Distro': Distro, 'DistroVersion': DistroVersion, 'License': License, 'package': package, 'PackageType': PackageType, 'custom': custom} execfile(filepath, d) if 'Package' in d: p = d['Package'](self._config, self, self.cookbook) elif 'SDKPackage' in d: p = d['SDKPackage'](self._config, self) elif 'InstallerPackage' in d: p = d['InstallerPackage'](self._config, self) elif 'App' in d: p = d['App'](self._config, self, self.cookbook) else: raise Exception('Package, SDKPackage, InstallerPackage or App ' 'class not found') p.prepare() # reload files from package now that we called prepare that # may have changed it p.load_files() return p except Exception, ex: import traceback traceback.print_exc() m.warning("Error loading package %s" % ex) return None
lgpl-2.1
CyanideL/android_kernel_oneplus_msm8974
tools/perf/scripts/python/check-perf-trace.py
11214
2503
# perf script event handlers, generated by perf script -g python # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # This script tests basic functionality such as flag and symbol # strings, common_xxx() calls back into perf, begin, end, unhandled # events, etc. Basically, if this script runs successfully and # displays expected results, Python scripting support should be ok. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from Core import * from perf_trace_context import * unhandled = autodict() def trace_begin(): print "trace_begin" pass def trace_end(): print_unhandled() def irq__softirq_entry(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, vec): print_header(event_name, common_cpu, common_secs, common_nsecs, common_pid, common_comm) print_uncommon(context) print "vec=%s\n" % \ (symbol_str("irq__softirq_entry", "vec", vec)), def kmem__kmalloc(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, call_site, ptr, bytes_req, bytes_alloc, gfp_flags): print_header(event_name, common_cpu, common_secs, common_nsecs, common_pid, common_comm) print_uncommon(context) print "call_site=%u, ptr=%u, bytes_req=%u, " \ "bytes_alloc=%u, gfp_flags=%s\n" % \ (call_site, ptr, bytes_req, bytes_alloc, flag_str("kmem__kmalloc", "gfp_flags", gfp_flags)), def trace_unhandled(event_name, context, event_fields_dict): try: unhandled[event_name] += 1 except TypeError: unhandled[event_name] = 1 def print_header(event_name, cpu, secs, nsecs, pid, comm): print "%-20s %5u %05u.%09u %8u %-20s " % \ (event_name, cpu, secs, nsecs, pid, comm), # print trace fields not included in handler args def print_uncommon(context): print "common_preempt_count=%d, common_flags=%s, common_lock_depth=%d, " \ % (common_pc(context), trace_flag_str(common_flags(context)), \ common_lock_depth(context)) def print_unhandled(): keys = unhandled.keys() if not keys: return print "\nunhandled events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "-----------"), for event_name in keys: print "%-40s %10d\n" % (event_name, unhandled[event_name])
gpl-2.0
gengue/django
django/core/serializers/base.py
41
6746
""" Module for abstract serializer/unserializer base classes. """ from django.db import models from django.utils import six class SerializerDoesNotExist(KeyError): """The requested serializer was not found.""" pass class SerializationError(Exception): """Something bad happened during serialization.""" pass class DeserializationError(Exception): """Something bad happened during deserialization.""" @classmethod def WithData(cls, original_exc, model, fk, field_value): """ Factory method for creating a deserialization error which has a more explanatory messsage. """ return cls("%s: (%s:pk=%s) field_value was '%s'" % (original_exc, model, fk, field_value)) class Serializer(object): """ Abstract serializer base class. """ # Indicates if the implemented serializer is only available for # internal Django use. internal_use_only = False def serialize(self, queryset, **options): """ Serialize a queryset. """ self.options = options self.stream = options.pop("stream", six.StringIO()) self.selected_fields = options.pop("fields", None) self.use_natural_foreign_keys = options.pop('use_natural_foreign_keys', False) self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False) self.start_serialization() self.first = True for obj in queryset: self.start_object(obj) # Use the concrete parent class' _meta instead of the object's _meta # This is to avoid local_fields problems for proxy models. Refs #17717. concrete_model = obj._meta.concrete_model for field in concrete_model._meta.local_fields: if field.serialize: if field.remote_field is None: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_field(obj, field) else: if self.selected_fields is None or field.attname[:-3] in self.selected_fields: self.handle_fk_field(obj, field) for field in concrete_model._meta.many_to_many: if field.serialize: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_m2m_field(obj, field) self.end_object(obj) if self.first: self.first = False self.end_serialization() return self.getvalue() def start_serialization(self): """ Called when serializing of the queryset starts. """ raise NotImplementedError('subclasses of Serializer must provide a start_serialization() method') def end_serialization(self): """ Called when serializing of the queryset ends. """ pass def start_object(self, obj): """ Called when serializing of an object starts. """ raise NotImplementedError('subclasses of Serializer must provide a start_object() method') def end_object(self, obj): """ Called when serializing of an object ends. """ pass def handle_field(self, obj, field): """ Called to handle each individual (non-relational) field on an object. """ raise NotImplementedError('subclasses of Serializer must provide an handle_field() method') def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey field. """ raise NotImplementedError('subclasses of Serializer must provide an handle_fk_field() method') def handle_m2m_field(self, obj, field): """ Called to handle a ManyToManyField. """ raise NotImplementedError('subclasses of Serializer must provide an handle_m2m_field() method') def getvalue(self): """ Return the fully serialized queryset (or None if the output stream is not seekable). """ if callable(getattr(self.stream, 'getvalue', None)): return self.stream.getvalue() class Deserializer(six.Iterator): """ Abstract base deserializer class. """ def __init__(self, stream_or_string, **options): """ Init this serializer given a stream or a string """ self.options = options if isinstance(stream_or_string, six.string_types): self.stream = six.StringIO(stream_or_string) else: self.stream = stream_or_string def __iter__(self): return self def __next__(self): """Iteration iterface -- return the next item in the stream""" raise NotImplementedError('subclasses of Deserializer must provide a __next__() method') class DeserializedObject(object): """ A deserialized model. Basically a container for holding the pre-saved deserialized data along with the many-to-many data saved with the object. Call ``save()`` to save the object (with the many-to-many data) to the database; call ``save(save_m2m=False)`` to save just the object fields (and not touch the many-to-many stuff.) """ def __init__(self, obj, m2m_data=None): self.object = obj self.m2m_data = m2m_data def __repr__(self): return "<DeserializedObject: %s(pk=%s)>" % ( self.object._meta.label, self.object.pk) def save(self, save_m2m=True, using=None, **kwargs): # Call save on the Model baseclass directly. This bypasses any # model-defined save. The save is also forced to be raw. # raw=True is passed to any pre/post_save signals. models.Model.save_base(self.object, using=using, raw=True, **kwargs) if self.m2m_data and save_m2m: for accessor_name, object_list in self.m2m_data.items(): setattr(self.object, accessor_name, object_list) # prevent a second (possibly accidental) call to save() from saving # the m2m data twice. self.m2m_data = None def build_instance(Model, data, db): """ Build a model instance. If the model instance doesn't have a primary key and the model supports natural keys, try to retrieve it from the database. """ obj = Model(**data) if (obj.pk is None and hasattr(Model, 'natural_key') and hasattr(Model._default_manager, 'get_by_natural_key')): natural_key = obj.natural_key() try: obj.pk = Model._default_manager.db_manager(db).get_by_natural_key(*natural_key).pk except Model.DoesNotExist: pass return obj
bsd-3-clause
toenuff/treadmill
lib/python/treadmill/ldap3kerberos.py
1
3106
""" Replaces the use of python-gssapi with pykerberos in ldap3. """ from __future__ import absolute_import import socket import base64 import kerberos from ldap3.core.exceptions import LDAPCommunicationError from ldap3.protocol.sasl.sasl import send_sasl_negotiation from ldap3.protocol.sasl.sasl import abort_sasl_negotiation NO_SECURITY_LAYER = 1 INTEGRITY_PROTECTION = 2 CONFIDENTIALITY_PROTECTION = 4 def sasl_gssapi(connection, controls): """ Performs a bind using the Kerberos v5 ("GSSAPI") SASL mechanism from RFC 4752. Does not support any security layers, only authentication! sasl_credentials can be empty or a 1-element tuple with the requested target_name or the True value to request the target_name from DNS """ if connection.sasl_credentials and len(connection.sasl_credentials) == 1 \ and connection.sasl_credentials[0]: if connection.sasl_credentials[0] is True: hostname = \ socket.gethostbyaddr(connection.socket.getpeername()[0])[0] target_name = 'ldap@' + hostname else: target_name = connection.sasl_credentials[0] else: target_name = 'ldap@' + connection.server.host gssflags = ( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG | kerberos.GSS_C_INTEG_FLAG | kerberos.GSS_C_CONF_FLAG ) _, ctx = kerberos.authGSSClientInit(target_name, gssflags=gssflags) try: in_token = '' while True: status = kerberos.authGSSClientStep(ctx, base64.b64encode(in_token)) out_token = kerberos.authGSSClientResponse(ctx) or '' result = send_sasl_negotiation(connection, controls, base64.b64decode(out_token)) in_token = result['saslCreds'] or '' if status == kerberos.AUTH_GSS_COMPLETE: break kerberos.authGSSClientUnwrap(ctx, base64.b64encode(in_token)) unwrapped_token = base64.b64decode( kerberos.authGSSClientResponse(ctx) or '') if len(unwrapped_token) != 4: raise LDAPCommunicationError("Incorrect response from server") server_security_layers = unwrapped_token[0] if not isinstance(server_security_layers, int): server_security_layers = ord(server_security_layers) if not server_security_layers & NO_SECURITY_LAYER: raise LDAPCommunicationError( "Server requires a security layer, but this is not implemented" ) client_security_layers = bytearray([NO_SECURITY_LAYER, 0, 0, 0]) kerberos.authGSSClientWrap(ctx, base64.b64encode( bytes(client_security_layers))) out_token = kerberos.authGSSClientResponse(ctx) or '' return send_sasl_negotiation(connection, controls, base64.b64decode(out_token)) except (kerberos.GSSError, LDAPCommunicationError): abort_sasl_negotiation(connection, controls) raise
apache-2.0
raviflipsyde/servo
tests/wpt/css-tests/tools/html5lib/html5lib/treewalkers/lxmletree.py
618
6033
from __future__ import absolute_import, division, unicode_literals from six import text_type from lxml import etree from ..treebuilders.etree import tag_regexp from gettext import gettext _ = gettext from . import _base from .. import ihatexml def ensure_str(s): if s is None: return None elif isinstance(s, text_type): return s else: return s.decode("utf-8", "strict") class Root(object): def __init__(self, et): self.elementtree = et self.children = [] if et.docinfo.internalDTD: self.children.append(Doctype(self, ensure_str(et.docinfo.root_name), ensure_str(et.docinfo.public_id), ensure_str(et.docinfo.system_url))) root = et.getroot() node = root while node.getprevious() is not None: node = node.getprevious() while node is not None: self.children.append(node) node = node.getnext() self.text = None self.tail = None def __getitem__(self, key): return self.children[key] def getnext(self): return None def __len__(self): return 1 class Doctype(object): def __init__(self, root_node, name, public_id, system_id): self.root_node = root_node self.name = name self.public_id = public_id self.system_id = system_id self.text = None self.tail = None def getnext(self): return self.root_node.children[1] class FragmentRoot(Root): def __init__(self, children): self.children = [FragmentWrapper(self, child) for child in children] self.text = self.tail = None def getnext(self): return None class FragmentWrapper(object): def __init__(self, fragment_root, obj): self.root_node = fragment_root self.obj = obj if hasattr(self.obj, 'text'): self.text = ensure_str(self.obj.text) else: self.text = None if hasattr(self.obj, 'tail'): self.tail = ensure_str(self.obj.tail) else: self.tail = None def __getattr__(self, name): return getattr(self.obj, name) def getnext(self): siblings = self.root_node.children idx = siblings.index(self) if idx < len(siblings) - 1: return siblings[idx + 1] else: return None def __getitem__(self, key): return self.obj[key] def __bool__(self): return bool(self.obj) def getparent(self): return None def __str__(self): return str(self.obj) def __unicode__(self): return str(self.obj) def __len__(self): return len(self.obj) class TreeWalker(_base.NonRecursiveTreeWalker): def __init__(self, tree): if hasattr(tree, "getroot"): tree = Root(tree) elif isinstance(tree, list): tree = FragmentRoot(tree) _base.NonRecursiveTreeWalker.__init__(self, tree) self.filter = ihatexml.InfosetFilter() def getNodeDetails(self, node): if isinstance(node, tuple): # Text node node, key = node assert key in ("text", "tail"), _("Text nodes are text or tail, found %s") % key return _base.TEXT, ensure_str(getattr(node, key)) elif isinstance(node, Root): return (_base.DOCUMENT,) elif isinstance(node, Doctype): return _base.DOCTYPE, node.name, node.public_id, node.system_id elif isinstance(node, FragmentWrapper) and not hasattr(node, "tag"): return _base.TEXT, node.obj elif node.tag == etree.Comment: return _base.COMMENT, ensure_str(node.text) elif node.tag == etree.Entity: return _base.ENTITY, ensure_str(node.text)[1:-1] # strip &; else: # This is assumed to be an ordinary element match = tag_regexp.match(ensure_str(node.tag)) if match: namespace, tag = match.groups() else: namespace = None tag = ensure_str(node.tag) attrs = {} for name, value in list(node.attrib.items()): name = ensure_str(name) value = ensure_str(value) match = tag_regexp.match(name) if match: attrs[(match.group(1), match.group(2))] = value else: attrs[(None, name)] = value return (_base.ELEMENT, namespace, self.filter.fromXmlName(tag), attrs, len(node) > 0 or node.text) def getFirstChild(self, node): assert not isinstance(node, tuple), _("Text nodes have no children") assert len(node) or node.text, "Node has no children" if node.text: return (node, "text") else: return node[0] def getNextSibling(self, node): if isinstance(node, tuple): # Text node node, key = node assert key in ("text", "tail"), _("Text nodes are text or tail, found %s") % key if key == "text": # XXX: we cannot use a "bool(node) and node[0] or None" construct here # because node[0] might evaluate to False if it has no child element if len(node): return node[0] else: return None else: # tail return node.getnext() return (node, "tail") if node.tail else node.getnext() def getParentNode(self, node): if isinstance(node, tuple): # Text node node, key = node assert key in ("text", "tail"), _("Text nodes are text or tail, found %s") % key if key == "text": return node # else: fallback to "normal" processing return node.getparent()
mpl-2.0
bpgc-cte/python2017
Week 7/django/lib/python3.6/site-packages/django/conf/locale/id/formats.py
504
2135
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j N Y' DATETIME_FORMAT = "j N Y, G.i" TIME_FORMAT = 'G.i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y G.i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d-%m-%y', '%d/%m/%y', # '25-10-09', 25/10/09' '%d-%m-%Y', '%d/%m/%Y', # '25-10-2009', 25/10/2009' '%d %b %Y', # '25 Oct 2006', '%d %B %Y', # '25 October 2006' ] TIME_INPUT_FORMATS = [ '%H.%M.%S', # '14.30.59' '%H.%M', # '14.30' ] DATETIME_INPUT_FORMATS = [ '%d-%m-%Y %H.%M.%S', # '25-10-2009 14.30.59' '%d-%m-%Y %H.%M.%S.%f', # '25-10-2009 14.30.59.000200' '%d-%m-%Y %H.%M', # '25-10-2009 14.30' '%d-%m-%Y', # '25-10-2009' '%d-%m-%y %H.%M.%S', # '25-10-09' 14.30.59' '%d-%m-%y %H.%M.%S.%f', # '25-10-09' 14.30.59.000200' '%d-%m-%y %H.%M', # '25-10-09' 14.30' '%d-%m-%y', # '25-10-09'' '%m/%d/%y %H.%M.%S', # '10/25/06 14.30.59' '%m/%d/%y %H.%M.%S.%f', # '10/25/06 14.30.59.000200' '%m/%d/%y %H.%M', # '10/25/06 14.30' '%m/%d/%y', # '10/25/06' '%m/%d/%Y %H.%M.%S', # '25/10/2009 14.30.59' '%m/%d/%Y %H.%M.%S.%f', # '25/10/2009 14.30.59.000200' '%m/%d/%Y %H.%M', # '25/10/2009 14.30' '%m/%d/%Y', # '10/25/2009' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
mit
therealjumbo/python_summer
pipeg/MeterMT.py
2
5671
#!/usr/bin/env python3 # Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module 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. It is provided for # educational purposes and 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 collections import hashlib import random import sys import threading random.seed(917) # Predictable random numbers for regression testing Reading = collections.namedtuple("Reading", "when reading reason username") class Error(Exception): pass class ThreadSafeDict: def __init__(self, *args, **kwargs): self._dict = dict(*args, **kwargs) self._lock = threading.Lock() def copy(self): with self._lock: return self.__class__(**self._dict) def get(self, key, default=None): with self._lock: return self._dict.get(key, default) def __len__(self): with self._lock: return len(self._dict) def __getitem__(self, key): with self._lock: return self._dict[key] def __setitem__(self, key, value): with self._lock: self._dict[key] = value def __delitem__(self, key): with self._lock: del self._dict[key] def __contains__(self, key): with self._lock: return key in self._dict class _MeterDict(ThreadSafeDict): def insert_if_missing(self, key, value=None): with self._lock: if key not in self._dict: self._dict[key] = value return True return False def status(self, username): count = total = 0 with self._lock: for reading in self._dict.values(): if reading is not None: total += 1 if reading.username == username: count += 1 return count, total class Manager: SessionId = 0 SessionIdLock = threading.Lock() UsernameForSessionId = ThreadSafeDict() ReadingForMeter = _MeterDict() def login(self, username, password): name = name_for_credentials(username, password) if name is None: raise Error("Invalid username or password") with Manager.SessionIdLock: Manager.SessionId += 1 sessionId = Manager.SessionId Manager.UsernameForSessionId[sessionId] = username return sessionId, name def get_status(self, sessionId): username = self._username_for_sessionid(sessionId) return Manager.ReadingForMeter.status(username) def get_job(self, sessionId): self._username_for_sessionid(sessionId) while True: # Create fake meter kind = random.choice("GE") meter = "{}{}".format(kind, random.randint(40000, 99999 if kind == "G" else 999999)) if Manager.ReadingForMeter.insert_if_missing(meter): return meter def _username_for_sessionid(self, sessionId): try: return Manager.UsernameForSessionId[sessionId] except KeyError: raise Error("Invalid session ID") def submit_reading(self, sessionId, meter, when, reading, reason=""): if (not isinstance(reading, int) or reading < 0) and not reason: raise Error("Invalid reading") if meter not in Manager.ReadingForMeter: raise Error("Invalid meter ID") username = self._username_for_sessionid(sessionId) reading = Reading(when, reading, reason, username) Manager.ReadingForMeter[meter] = reading @staticmethod def _dump(file=sys.stdout): ReadingForMeter = Manager.ReadingForMeter.copy() for meter, reading in sorted(ReadingForMeter.items()): if reading is not None: print("{}={}@{}[{}]{}".format(meter, reading.reading, reading.when.isoformat()[:16], reading.reason, reading.username), file=file) _User = collections.namedtuple("User", "username sha256") def name_for_credentials(username, password): sha = hashlib.sha256() sha.update(password.encode("utf-8")) user = _User(username, sha.hexdigest()) return _Users.get(user) # No locks for read-only data. Returns None for invalid username or password # Passwords are stored as SHA256 hex digests, e.g., # sha = hashlib.sha256() # sha.update(b"pear") # "pear" is the password # digest = sha.hexdigest() # digest is what's stored as the sha256 _Users = { _User("adam", # Password: adam "f7f376a1fcd0d0e11a10ed1b6577c99784d3a6bbe669b1d13fae43eb64634f6e"): "Adam Best", _User("carol", # Password: carol "4c26d9074c27d89ede59270c0ac14b71e071b15239519f75474b2f3ba63481f5"): "Carol Dent", _User("eric", # Password: eric "6f9edcd3408cbda14a837e6a44fc5b7f64ccc9a2477c1498fcb13c777ffb9605"): "Eric Fawn", _User("gwenda", # Password: gwenda "b0d0c7e0a2c7251768699b85e2ac9cdee23521ac6b1645fafec35eb93ca8870a"): "Gwenda Harris" } if __name__ == "__main__": print("Loaded OK")
gpl-3.0
getstackd/stackd
vendor/boost-context/tools/build/v2/test/make_rule.py
44
1323
#!/usr/bin/python # Copyright 2003 Dave Abrahams # Copyright 2003, 2006 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # Test the 'make' rule. import BoostBuild import string t = BoostBuild.Tester(pass_toolset=1) t.write("jamroot.jam", """\ import feature ; feature.feature test_feature : : free ; import toolset ; toolset.flags creator STRING : <test_feature> ; actions creator { echo $(STRING) > $(<) } make foo.bar : : creator : <test_feature>12345678 ; """) t.run_build_system() t.expect_addition("bin/$toolset/debug/foo.bar") t.fail_test(string.find(t.read("bin/$toolset/debug/foo.bar"), "12345678") == -1) # Regression test. Make sure that if a main target is requested two times, and # build requests differ only in incidental properties, the main target is # created only once. The bug was discovered by Kirill Lapshin. t.write("jamroot.jam", """\ exe a : dir//hello1.cpp ; exe b : dir//hello1.cpp/<hardcode-dll-paths>true ; """) t.write("dir/jamfile.jam", """\ import common ; make hello1.cpp : hello.cpp : common.copy ; """) t.write("dir/hello.cpp", "int main() {}\n") # Show only action names. t.run_build_system(["-d1", "-n"]) t.fail_test(t.stdout().count("copy") != 1) t.cleanup()
mit
dzan/xenOnArm
tools/xm-test/lib/XmTestLib/block_utils.py
26
1410
#!/usr/bin/python # Copyright (c) 2006 XenSource Inc. # Author: Ewan Mellor <ewan@xensource.com> import time from XmTestLib import * import xen.util.blkif __all__ = [ "block_attach", "block_detach" ] def get_state(domain, devname): (path, number) = xen.util.blkif.blkdev_name_to_number(devname) s, o = traceCommand("xm block-list %s | awk '/^%d/ {print $4}'" % (domain.getName(), number)) if s != 0: FAIL("block-list failed") if o == "": return 0 else: return int(o) def block_attach(domain, phy, virt): status, output = traceCommand("xm block-attach %s %s %s w" % (domain.getName(), phy, virt)) if status != 0: FAIL("xm block-attach returned invalid %i != 0" % status) for i in range(10): if get_state(domain, virt) == 4: break time.sleep(1) else: FAIL("block-attach failed: device did not switch to Connected state") def block_detach(domain, virt): status, output = traceCommand("xm block-detach %s %s" % (domain.getName(), virt)) if status != 0: FAIL("xm block-detach returned invalid %i != 0" % status) for i in range(10): if get_state(domain, virt) == 0: break time.sleep(1) else: FAIL("block-detach failed: device did not disappear")
gpl-2.0
brev/nupic
src/nupic/database/ClientJobsDAO.py
21
136129
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- # Add Context Manager (with ...) support for Jython/Python 2.5.x ( # ClientJobManager used to use Jython); it's a noop in newer Python versions. from __future__ import with_statement import collections import logging from optparse import OptionParser import sys import traceback import uuid from nupic.support.decorators import logExceptions #, logEntryExit from nupic.database.Connection import ConnectionFactory from nupic.support.configuration import Configuration from nupic.support import pymysqlhelpers _MODULE_NAME = "nupic.database.ClientJobsDAO" class InvalidConnectionException(Exception): """ This exception is raised when a worker tries to update a model record that belongs to another worker. Ownership of a model is determined by the database connection id """ pass def _getLogger(): """ NOTE: this cannot be a global variable because the logging subsystem needs to be initialized by the host app, and that usually happens after imports """ return logging.getLogger( ".".join(['com.numenta', _MODULE_NAME, ClientJobsDAO.__name__])) # Create a decorator for retrying idempotent SQL operations upon transient MySQL # failures. # WARNING: do NOT indiscriminately decorate non-idempotent operations with this # decorator as it # may case undesirable side-effects, such as multiple row # insertions, etc. # NOTE: having this as a global permits us to switch parameters wholesale (e.g., # timeout) g_retrySQL = pymysqlhelpers.retrySQL(getLoggerCallback=_getLogger) def _abbreviate(text, threshold): """ Abbreviate the given text to threshold chars and append an ellipsis if its length exceeds threshold; used for logging; NOTE: the resulting text could be longer than threshold due to the ellipsis """ if text is not None and len(text) > threshold: text = text[:threshold] + "..." return text class ClientJobsDAO(object): """ This Data Access Object (DAO) is used for creating, managing, and updating the ClientJobs database. The ClientJobs database is a MySQL database shared by the UI, Stream Manager (StreamMgr), and the engine. The clients (UI and StreamMgr) make calls to this DAO to request new jobs (Hypersearch, stream jobs, model evaluations, etc.) and the engine queries and updates it to manage and keep track of the jobs and report progress and results back to the clients. This class is primarily a collection of static methods that work with the client jobs database. But, rather than taking the approach of declaring each method as static, we provide just one static class method that returns a reference to the (one) ClientJobsDAO instance allocated for the current process (and perhaps in the future, for the current thread). This approach gives us the flexibility in the future of perhaps allocating one instance per thread and makes the internal design a bit more compartmentalized (by enabling the use of instance variables). Note: This is generally referred to as the singleton pattern. A typical call is made in the following manner: ClientJobsDAO.get().jobInfo() If the caller desires, they have the option of caching the instance returned from ClientJobsDAO.get(), i.e.: cjDAO = ClientJobsDAO.get() cjDAO.jobInfo() cjDAO.jobSetStatus(...) There are two tables in this database, the jobs table and the models table, as described below. The jobs table keeps track of all jobs. The models table is filled in by hypersearch jobs with the results of each model that it evaluates. Jobs table. The field names are given as: internal mysql field name (public API field name) field description --------------------------------------------------------------------------- job_id (jobId): Generated by the database when a new job is inserted by a client. This is an auto-incrementing ID that is unique among all jobs. client (client): The name of the client (i.e. 'UI', 'StreamMgr', etc.). client_info (clientInfo): Arbitrary data specified by client. client_key (clientKey): Foreign key as defined by the client. cmd_line (cmdLine): Command line to be used to launch each worker process for the job. params (params): JSON encoded dict of job specific parameters that are useful to the worker processes for this job. This field is provided by the client when it inserts the job and can be fetched out of the database by worker processes (based on job_id) if needed. job_hash (jobHash): hash of the job, provided by the client, used for detecting identical jobs when they use the jobInsertUnique() call. Clients that don't care about whether jobs are unique or not do not have to generate or care about this field. status (status): The engine will periodically update the status field as the job runs. This is an enum. Possible values are: STATUS_NOTSTARTED client has just added this job to the table STATUS_STARTING: a CJM is in the process of launching this job in the engine STATUS_RUNNING: the engine is currently running this job STATUS_TESTMODE: the job is being run by the test framework outside the context of hadoop, should be ignored STATUS_COMPLETED: the job has completed. The completion_reason field describes the manner in which it completed completion_reason (completionReason): Why this job completed. Possible values are: CMPL_REASON_SUCCESS: job completed successfully CMPL_REASON_KILLED: job was killed by ClientJobManager CMPL_REASON_CANCELLED: job was cancelled by user CMPL_REASON_ERROR: job encountered an error. The completion_msg field contains a text description of the error completion_msg (completionMsg): Text description of error that occurred if job terminated with completion_reason of CMPL_REASON_ERROR or CMPL_REASON_KILLED worker_completion_msg (workerCompletionMsg): Why this job completed, according to the worker(s). cancel (cancel): Set by the clent if/when it wants to cancel a job. Periodically polled by the CJM and used as a signal to kill the job. TODO: the above claim doesn't match current reality: presently, Hypersearch and Production workers poll the cancel field. start_time (startTime): date and time of when this job started. end_time (endTime): date and time of when this job completed. results (results): A JSON encoded dict of the results of a hypersearch job. The dict contains the following fields. Note that this dict is NULL before any model has reportedits results: bestModel: The modelID of the best performing model so far bestValue: The value of the optimized metric for the best model _eng_last_update_time (engLastUpdateTime): Time stamp of last update. Used for detecting stalled jobs. _eng_cjm_conn_id (engCjmConnId): The database client connection ID of the CJM (Client Job Manager) starting up this job. Set and checked while the job is in the 'starting' phase. Used for detecting and dealing with stalled CJM's _eng_worker_state (engWorkerState): JSON encoded data structure for private use by the workers. _eng_status (engStatus): String used to send status messages from the engine to the UI. For informative purposes only. _eng_model_milestones (engModelMilestones): JSON encoded object with information about global model milestone results. minimum_workers (minimumWorkers): min number of desired workers at a time. If 0, no workers will be allocated in a crunch maximum_workers (maximumWorkers): max number of desired workers at a time. If 0, then use as many as practical given load on the cluster. priority (priority): job scheduling priority; 0 is the default priority ( ClientJobsDAO.DEFAULT_JOB_PRIORITY); positive values are higher priority (up to ClientJobsDAO.MAX_JOB_PRIORITY), and negative values are lower priority (down to ClientJobsDAO.MIN_JOB_PRIORITY) _eng_allocate_new_workers (engAllocateNewWorkers): Should the scheduling algorithm allocate new workers to this job? If a specialized worker willingly gives up control, we set this field to FALSE to avoid allocating new workers. _eng_untended_dead_workers (engUntendedDeadWorkers): If a specialized worker fails or is killed by the scheduler, we set this feild to TRUE to indicate that the worker is dead. num_failed_workers (numFailedWorkers): The number of failed specialized workers for this job. if the number of failures is greater than max.failed.attempts, we mark the job as failed last_failed_worker_error_msg (lastFailedWorkerErrorMsg): Error message of the most recent failed specialized worker Models table: field description --------------------------------------------------------------------------- model_id (modelId): Generated by the database when the engine inserts a new model. This is an auto-incrementing ID that is globally unique among all models of all jobs. job_id (jobId) : The job_id of the job in the Jobs Table that this model belongs to. params (params): JSON encoded dict of all the parameters used to generate this particular model. The dict contains the following properties: paramValues = modelParamValuesDict, paramLabels = modelParamValueLabelsDict, experimentName = expName status (status): Enumeration of the model's status. Possible values are: STATUS_NOTSTARTED: This model's parameters have been chosen, but no worker is evaluating it yet. STATUS_RUNNING: This model is currently being evaluated by a worker STATUS_COMPLETED: This model has finished running. The completion_reason field describes why it completed. completion_reason (completionReason) : Why this model completed. Possible values are: CMPL_REASON_EOF: model reached the end of the dataset CMPL_REASON_STOPPED: model stopped because it reached maturity and was not deemed the best model. CMPL_REASON_KILLED: model was killed by the terminator logic before maturing and before reaching EOF because it was doing so poorly CMPL_REASON_ERROR: model encountered an error. The completion_msg field contains a text description of the error completion_msg (completionMsg): Text description of error that occurred if model terminated with completion_reason of CMPL_REASON_ERROR or CMPL_REASON_KILLED results (results): JSON encoded structure containing the latest online metrics produced by the model. The engine periodically updates this as the model runs. optimized_metric(optimizedMetric): The value of the metric over which this model is being optimized. Stroring this separately in the database allows us to search through to find the best metric faster update_counter (updateCounter): Incremented by the UI whenever the engine updates the results field. This makes it easier and faster for the UI to determine which models have changed results. num_records (numRecords): Number of records (from the original dataset, before aggregation) that have been processed so far by this model. Periodically updated by the engine as the model is evaluated. start_time (startTime): Date and time of when this model started being evaluated. end_time (endTime): Date and time of when this model completed. cpu_time (cpuTime): How much actual CPU time was spent evaluating this model (in seconds). This excludes any time the process spent sleeping, or otherwise not executing code. model_checkpoint_id (modelCheckpointId): Checkpoint identifier for this model (after it has been saved) _eng_params_hash (engParamsHash): MD5 hash of the params. Used for detecting duplicate models. _eng_particle_hash (engParticleHash): MD5 hash of the model's particle (for particle swarm optimization algorithm). _eng_last_update_time (engLastUpdateTime): Time stamp of last update. Used for detecting stalled workers. _eng_task_tracker_id (engTaskTrackerId): ID of the Hadoop Task Tracker managing the worker _eng_worker_id (engWorkerId): ID of the Hadoop Map Task (worker) for this task _eng_attempt_id (engAttemptId): Hadoop attempt ID of this task attempt _eng_worker_conn_id (engWorkerConnId): database client connection ID of the hypersearch worker that is running this model _eng_milestones (engMilestones): JSON encoded list of metric values for the model at each milestone point. _eng_stop (engStop): One of the STOP_REASON_XXX enumerated value strings (or None). This gets set to STOP_REASON_KILLED if the terminator decides that the performance of this model is so poor that it should be terminated immediately. This gets set to STOP_REASON_STOPPED if Hypersearch decides that the search is over and this model doesn't have to run anymore. _eng_matured (engMatured): Set by the model maturity checker when it decides that this model has "matured". """ # Job priority range values. # # Higher-priority jobs will be scheduled to run at the expense of the # lower-priority jobs, and higher-priority job tasks will preempt those with # lower priority if there is inadequate supply of scheduling slots. Excess # lower priority job tasks will starve as long as slot demand exceeds supply. MIN_JOB_PRIORITY = -100 # Minimum job scheduling priority DEFAULT_JOB_PRIORITY = 0 # Default job scheduling priority MAX_JOB_PRIORITY = 100 # Maximum job scheduling priority # Equates for job and model status STATUS_NOTSTARTED = "notStarted" STATUS_STARTING = "starting" STATUS_RUNNING = "running" STATUS_TESTMODE = "testMode" STATUS_COMPLETED = "completed" # Equates for job and model completion_reason field CMPL_REASON_SUCCESS = "success" # jobs only - job completed successfully CMPL_REASON_CANCELLED = "cancel" # jobs only - canceled by user; # TODO: presently, no one seems to set the # CANCELLED reason CMPL_REASON_KILLED = "killed" # jobs or models - model killed by # terminator for poor results or job # killed by ClientJobManager CMPL_REASON_ERROR = "error" # jobs or models - Encountered an error # while running CMPL_REASON_EOF = "eof" # models only - model reached end of # data set CMPL_REASON_STOPPED = "stopped" # models only - model stopped running # because it matured and was not deemed # the best model. CMPL_REASON_ORPHAN = "orphan" # models only - model was detected as an # orphan because the worker running it # failed to update the last_update_time. # This model is considered dead and a new # one may be created to take its place. # Equates for the model _eng_stop field STOP_REASON_KILLED = "killed" # killed by model terminator for poor # results before it matured. STOP_REASON_STOPPED = "stopped" # stopped because it had matured and was # not deemed the best model # Equates for the cleaned field CLEAN_NOT_DONE = "notdone" # Cleaning for job is not done CLEAN_DONE = "done" # Cleaning for job is done # Equates for standard job classes JOB_TYPE_HS = "hypersearch" JOB_TYPE_PM = "production-model" JOB_TYPE_SM = "stream-manager" JOB_TYPE_TEST = "test" HASH_MAX_LEN = 16 """ max size, in bytes, of the hash used for model and job identification """ CLIENT_MAX_LEN = 8 """ max size, in bytes of the 'client' field's value """ class _TableInfoBase(object): """ Common table info fields; base class """ __slots__ = ("tableName", "dbFieldNames", "publicFieldNames", "pubToDBNameDict", "dbToPubNameDict",) def __init__(self): self.tableName = None """ Database-qualified table name (databasename.tablename) """ self.dbFieldNames = None """ Names of fields in schema """ self.publicFieldNames = None """ Public names of fields generated programmatically: e.g., word1_word2_word3 => word1Word2Word3 """ self.pubToDBNameDict = None self.dbToPubNameDict = None """ These dicts convert public field names to DB names and vice versa """ class _JobsTableInfo(_TableInfoBase): __slots__ = ("jobInfoNamedTuple",) # The namedtuple classes that we use to return information from various # functions jobDemandNamedTuple = collections.namedtuple( '_jobDemandNamedTuple', ['jobId', 'minimumWorkers', 'maximumWorkers', 'priority', 'engAllocateNewWorkers', 'engUntendedDeadWorkers', 'numFailedWorkers', 'engJobType']) def __init__(self): super(ClientJobsDAO._JobsTableInfo, self).__init__() # Generated dynamically after introspecting jobs table columns. Attributes # of this namedtuple are the public names of the jobs table columns. self.jobInfoNamedTuple = None class _ModelsTableInfo(_TableInfoBase): __slots__ = ("modelInfoNamedTuple",) # The namedtuple classes that we use to return information from various # functions getParamsNamedTuple = collections.namedtuple( '_modelsGetParamsNamedTuple', ['modelId', 'params', 'engParamsHash']) getResultAndStatusNamedTuple = collections.namedtuple( '_modelsGetResultAndStatusNamedTuple', ['modelId', 'results', 'status', 'updateCounter', 'numRecords', 'completionReason', 'completionMsg', 'engParamsHash', 'engMatured']) getUpdateCountersNamedTuple = collections.namedtuple( '_modelsGetUpdateCountersNamedTuple', ['modelId', 'updateCounter']) def __init__(self): super(ClientJobsDAO._ModelsTableInfo, self).__init__() # Generated dynamically after introspecting models columns. Attributes # of this namedtuple are the public names of the models table columns. self.modelInfoNamedTuple = None _SEQUENCE_TYPES = (list, set, tuple) """ Sequence types that we accept in args """ # There is one instance of the ClientJobsDAO per process. This class static # variable gets filled in the first time the process calls # ClientJobsDAO.get() _instance = None # The root name and version of the database. The actual database name is # something of the form "client_jobs_v2_suffix". _DB_ROOT_NAME = 'client_jobs' _DB_VERSION = 29 @classmethod def dbNamePrefix(cls): """ Get the beginning part of the database name for the current version of the database. This, concatenated with '_' + Configuration.get('nupic.cluster.database.nameSuffix') will produce the actual database name used. """ return cls.__getDBNamePrefixForVersion(cls._DB_VERSION) @classmethod def __getDBNamePrefixForVersion(cls, dbVersion): """ Get the beginning part of the database name for the given database version. This, concatenated with '_' + Configuration.get('nupic.cluster.database.nameSuffix') will produce the actual database name used. Parameters: ---------------------------------------------------------------- dbVersion: ClientJobs database version number retval: the ClientJobs database name prefix for the given DB version """ return '%s_v%d' % (cls._DB_ROOT_NAME, dbVersion) @classmethod def _getDBName(cls): """ Generates the ClientJobs database name for the current version of the database; "semi-private" class method for use by friends of the class. Parameters: ---------------------------------------------------------------- retval: the ClientJobs database name """ return cls.__getDBNameForVersion(cls._DB_VERSION) @classmethod def __getDBNameForVersion(cls, dbVersion): """ Generates the ClientJobs database name for the given version of the database Parameters: ---------------------------------------------------------------- dbVersion: ClientJobs database version number retval: the ClientJobs database name for the given DB version """ # DB Name prefix for the given version prefix = cls.__getDBNamePrefixForVersion(dbVersion) # DB Name suffix suffix = Configuration.get('nupic.cluster.database.nameSuffix') # Replace dash with underscore (dash will break SQL e.g. 'ec2-user') suffix = suffix.replace("-", "_") # Create the name of the database for the given DB version dbName = '%s_%s' % (prefix, suffix) return dbName @staticmethod @logExceptions(_getLogger) def get(): """ Get the instance of the ClientJobsDAO created for this process (or perhaps at some point in the future, for this thread). Parameters: ---------------------------------------------------------------- retval: instance of ClientJobsDAO """ # Instantiate if needed if ClientJobsDAO._instance is None: cjDAO = ClientJobsDAO() cjDAO.connect() ClientJobsDAO._instance = cjDAO # Return the instance to the caller return ClientJobsDAO._instance @logExceptions(_getLogger) def __init__(self): """ Instantiate a ClientJobsDAO instance. Parameters: ---------------------------------------------------------------- """ self._logger = _getLogger() # Usage error to instantiate more than 1 instance per process assert (ClientJobsDAO._instance is None) # Create the name of the current version database self.dbName = self._getDBName() # NOTE: we set the table names here; the rest of the table info is set when # the tables are initialized during connect() self._jobs = self._JobsTableInfo() self._jobs.tableName = '%s.jobs' % (self.dbName) self._models = self._ModelsTableInfo() self._models.tableName = '%s.models' % (self.dbName) # Our connection ID, filled in during connect() self._connectionID = None @property def jobsTableName(self): return self._jobs.tableName @property def modelsTableName(self): return self._models.tableName def _columnNameDBToPublic(self, dbName): """ Convert a database internal column name to a public name. This takes something of the form word1_word2_word3 and converts it to: word1Word2Word3. If the db field name starts with '_', it is stripped out so that the name is compatible with collections.namedtuple. for example: _word1_word2_word3 => word1Word2Word3 Parameters: -------------------------------------------------------------- dbName: database internal field name retval: public name """ words = dbName.split('_') if dbName.startswith('_'): words = words[1:] pubWords = [words[0]] for word in words[1:]: pubWords.append(word[0].upper() + word[1:]) return ''.join(pubWords) @logExceptions(_getLogger) @g_retrySQL def connect(self, deleteOldVersions=False, recreate=False): """ Locate the current version of the jobs DB or create a new one, and optionally delete old versions laying around. If desired, this method can be called at any time to re-create the tables from scratch, delete old versions of the database, etc. Parameters: ---------------------------------------------------------------- deleteOldVersions: if true, delete any old versions of the DB left on the server recreate: if true, recreate the database from scratch even if it already exists. """ # Initialize tables, if needed with ConnectionFactory.get() as conn: # Initialize tables self._initTables(cursor=conn.cursor, deleteOldVersions=deleteOldVersions, recreate=recreate) # Save our connection id conn.cursor.execute('SELECT CONNECTION_ID()') self._connectionID = conn.cursor.fetchall()[0][0] self._logger.info("clientJobsConnectionID=%r", self._connectionID) return @logExceptions(_getLogger) def _initTables(self, cursor, deleteOldVersions, recreate): """ Initialize tables, if needed Parameters: ---------------------------------------------------------------- cursor: SQL cursor deleteOldVersions: if true, delete any old versions of the DB left on the server recreate: if true, recreate the database from scratch even if it already exists. """ # Delete old versions if they exist if deleteOldVersions: self._logger.info( "Dropping old versions of client_jobs DB; called from: %r", traceback.format_stack()) for i in range(self._DB_VERSION): cursor.execute('DROP DATABASE IF EXISTS %s' % (self.__getDBNameForVersion(i),)) # Create the database if necessary if recreate: self._logger.info( "Dropping client_jobs DB %r; called from: %r", self.dbName, traceback.format_stack()) cursor.execute('DROP DATABASE IF EXISTS %s' % (self.dbName)) cursor.execute('CREATE DATABASE IF NOT EXISTS %s' % (self.dbName)) # Get the list of tables cursor.execute('SHOW TABLES IN %s' % (self.dbName)) output = cursor.fetchall() tableNames = [x[0] for x in output] # ------------------------------------------------------------------------ # Create the jobs table if it doesn't exist # Fields that start with '_eng' are intended for private use by the engine # and should not be used by the UI if 'jobs' not in tableNames: self._logger.info("Creating table %r", self.jobsTableName) fields = [ 'job_id INT UNSIGNED NOT NULL AUTO_INCREMENT', # unique jobID 'client CHAR(%d)' % (self.CLIENT_MAX_LEN), # name of client (UI, StrmMgr, etc.) 'client_info LONGTEXT', # Arbitrary data defined by the client 'client_key varchar(255)', # Foreign key as defined by the client. 'cmd_line LONGTEXT', # command line to use to launch each worker process 'params LONGTEXT', # JSON encoded params for the job, for use by the worker processes 'job_hash BINARY(%d) DEFAULT NULL' % (self.HASH_MAX_LEN), # unique hash of the job, provided by the client. Used for detecting # identical job requests from the same client when they use the # jobInsertUnique() method. 'status VARCHAR(16) DEFAULT "notStarted"', # One of the STATUS_XXX enumerated value strings 'completion_reason VARCHAR(16)', # One of the CMPL_REASON_XXX enumerated value strings. # NOTE: This is the job completion reason according to the hadoop # job-tracker. A success here does not necessarily mean the # workers were "happy" with the job. To see if the workers # failed, check the worker_completion_reason 'completion_msg LONGTEXT', # Why this job completed, according to job-tracker 'worker_completion_reason VARCHAR(16) DEFAULT "%s"' % \ self.CMPL_REASON_SUCCESS, # One of the CMPL_REASON_XXX enumerated value strings. This is # may be changed to CMPL_REASON_ERROR if any workers encounter # an error while running the job. 'worker_completion_msg LONGTEXT', # Why this job completed, according to workers. If # worker_completion_reason is set to CMPL_REASON_ERROR, this will # contain the error information. 'cancel BOOLEAN DEFAULT FALSE', # set by UI, polled by engine 'start_time DATETIME DEFAULT 0', # When job started 'end_time DATETIME DEFAULT 0', # When job ended 'results LONGTEXT', # JSON dict with general information about the results of the job, # including the ID and value of the best model # TODO: different semantics for results field of ProductionJob '_eng_job_type VARCHAR(32)', # String used to specify the type of job that this is. Current # choices are hypersearch, production worker, or stream worker 'minimum_workers INT UNSIGNED DEFAULT 0', # min number of desired workers at a time. If 0, no workers will be # allocated in a crunch 'maximum_workers INT UNSIGNED DEFAULT 0', # max number of desired workers at a time. If 0, then use as many # as practical given load on the cluster. 'priority INT DEFAULT %d' % self.DEFAULT_JOB_PRIORITY, # job scheduling priority; 0 is the default priority ( # ClientJobsDAO.DEFAULT_JOB_PRIORITY); positive values are higher # priority (up to ClientJobsDAO.MAX_JOB_PRIORITY), and negative # values are lower priority (down to ClientJobsDAO.MIN_JOB_PRIORITY) '_eng_allocate_new_workers BOOLEAN DEFAULT TRUE', # Should the scheduling algorithm allocate new workers to this job? # If a specialized worker willingly gives up control, we set this # field to FALSE to avoid allocating new workers. '_eng_untended_dead_workers BOOLEAN DEFAULT FALSE', # If a specialized worker fails or is killed by the scheduler, we # set this feild to TRUE to indicate that the worker is dead 'num_failed_workers INT UNSIGNED DEFAULT 0', # The number of failed specialized workers for this job. If the # number of failures is >= max.failed.attempts, we mark the job # as failed 'last_failed_worker_error_msg LONGTEXT', # Error message of the most recent specialized failed worker '_eng_cleaning_status VARCHAR(16) DEFAULT "%s"' % \ self.CLEAN_NOT_DONE, # Has the job been garbage collected, this includes removing # unneeded # model output caches, s3 checkpoints. 'gen_base_description LONGTEXT', # The contents of the generated description.py file from hypersearch # requests. This is generated by the Hypersearch workers and stored # here for reference, debugging, and development purposes. 'gen_permutations LONGTEXT', # The contents of the generated permutations.py file from # hypersearch requests. This is generated by the Hypersearch workers # and stored here for reference, debugging, and development # purposes. '_eng_last_update_time DATETIME DEFAULT 0', # time stamp of last update, used for detecting stalled jobs '_eng_cjm_conn_id INT UNSIGNED', # ID of the CJM starting up this job '_eng_worker_state LONGTEXT', # JSON encoded state of the hypersearch in progress, for private # use by the Hypersearch workers '_eng_status LONGTEXT', # String used for status messages sent from the engine for # informative purposes only. Usually printed periodically by # clients watching a job progress. '_eng_model_milestones LONGTEXT', # JSon encoded object with information about global model milestone # results 'PRIMARY KEY (job_id)', 'UNIQUE INDEX (client, job_hash)', 'INDEX (status)', 'INDEX (client_key)' ] options = [ 'AUTO_INCREMENT=1000', ] query = 'CREATE TABLE IF NOT EXISTS %s (%s) %s' % \ (self.jobsTableName, ','.join(fields), ','.join(options)) cursor.execute(query) # ------------------------------------------------------------------------ # Create the models table if it doesn't exist # Fields that start with '_eng' are intended for private use by the engine # and should not be used by the UI if 'models' not in tableNames: self._logger.info("Creating table %r", self.modelsTableName) fields = [ 'model_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT', # globally unique model ID 'job_id INT UNSIGNED NOT NULL', # jobID 'params LONGTEXT NOT NULL', # JSON encoded params for the model 'status VARCHAR(16) DEFAULT "notStarted"', # One of the STATUS_XXX enumerated value strings 'completion_reason VARCHAR(16)', # One of the CMPL_REASON_XXX enumerated value strings 'completion_msg LONGTEXT', # Why this job completed 'results LONGTEXT DEFAULT NULL', # JSON encoded structure containing metrics produced by the model 'optimized_metric FLOAT ', #Value of the particular metric we are optimizing in hypersearch 'update_counter INT UNSIGNED DEFAULT 0', # incremented by engine every time the results is updated 'num_records INT UNSIGNED DEFAULT 0', # number of records processed so far 'start_time DATETIME DEFAULT 0', # When this model started being evaluated 'end_time DATETIME DEFAULT 0', # When this model completed 'cpu_time FLOAT DEFAULT 0', # How much actual CPU time was spent on this model, in seconds. This # excludes time the process spent sleeping, or otherwise not # actually executing code. 'model_checkpoint_id LONGTEXT', # Checkpoint identifier for this model (after it has been saved) 'gen_description LONGTEXT', # The contents of the generated description.py file from hypersearch # requests. This is generated by the Hypersearch workers and stored # here for reference, debugging, and development purposes. '_eng_params_hash BINARY(%d) DEFAULT NULL' % (self.HASH_MAX_LEN), # MD5 hash of the params '_eng_particle_hash BINARY(%d) DEFAULT NULL' % (self.HASH_MAX_LEN), # MD5 hash of the particle info for PSO algorithm '_eng_last_update_time DATETIME DEFAULT 0', # time stamp of last update, used for detecting stalled workers '_eng_task_tracker_id TINYBLOB', # Hadoop Task Tracker ID '_eng_worker_id TINYBLOB', # Hadoop Map Task ID '_eng_attempt_id TINYBLOB', # Hadoop Map task attempt ID '_eng_worker_conn_id INT DEFAULT 0', # database client connection ID of the worker that is running this # model '_eng_milestones LONGTEXT', # A JSON encoded list of metric values for the model at each # milestone point '_eng_stop VARCHAR(16) DEFAULT NULL', # One of the STOP_REASON_XXX enumerated value strings. Set either by # the swarm terminator of either the current, or another # Hypersearch worker. '_eng_matured BOOLEAN DEFAULT FALSE', # Set by the model maturity-checker when it decides that this model # has "matured". This means that it has reached the point of # not getting better results with more data. 'PRIMARY KEY (model_id)', 'UNIQUE INDEX (job_id, _eng_params_hash)', 'UNIQUE INDEX (job_id, _eng_particle_hash)', ] options = [ 'AUTO_INCREMENT=1000', ] query = 'CREATE TABLE IF NOT EXISTS %s (%s) %s' % \ (self.modelsTableName, ','.join(fields), ','.join(options)) cursor.execute(query) # --------------------------------------------------------------------- # Get the field names for each table cursor.execute('DESCRIBE %s' % (self.jobsTableName)) fields = cursor.fetchall() self._jobs.dbFieldNames = [str(field[0]) for field in fields] cursor.execute('DESCRIBE %s' % (self.modelsTableName)) fields = cursor.fetchall() self._models.dbFieldNames = [str(field[0]) for field in fields] # --------------------------------------------------------------------- # Generate the public names self._jobs.publicFieldNames = [self._columnNameDBToPublic(x) for x in self._jobs.dbFieldNames] self._models.publicFieldNames = [self._columnNameDBToPublic(x) for x in self._models.dbFieldNames] # --------------------------------------------------------------------- # Generate the name conversion dicts self._jobs.pubToDBNameDict = dict( zip(self._jobs.publicFieldNames, self._jobs.dbFieldNames)) self._jobs.dbToPubNameDict = dict( zip(self._jobs.dbFieldNames, self._jobs.publicFieldNames)) self._models.pubToDBNameDict = dict( zip(self._models.publicFieldNames, self._models.dbFieldNames)) self._models.dbToPubNameDict = dict( zip(self._models.dbFieldNames, self._models.publicFieldNames)) # --------------------------------------------------------------------- # Generate the dynamic namedtuple classes we use self._models.modelInfoNamedTuple = collections.namedtuple( '_modelInfoNamedTuple', self._models.publicFieldNames) self._jobs.jobInfoNamedTuple = collections.namedtuple( '_jobInfoNamedTuple', self._jobs.publicFieldNames) return def _getMatchingRowsNoRetries(self, tableInfo, conn, fieldsToMatch, selectFieldNames, maxRows=None): """ Return a sequence of matching rows with the requested field values from a table or empty sequence if nothing matched. tableInfo: Table information: a ClientJobsDAO._TableInfoBase instance conn: Owned connection acquired from ConnectionFactory.get() fieldsToMatch: Dictionary of internal fieldName/value mappings that identify the desired rows. If a value is an instance of ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the operator 'IN' will be used in the corresponding SQL predicate; if the value is bool: "IS TRUE/FALSE"; if the value is None: "IS NULL"; '=' will be used for all other cases. selectFieldNames: list of fields to return, using internal field names maxRows: maximum number of rows to return; unlimited if maxRows is None retval: A sequence of matching rows, each row consisting of field values in the order of the requested field names. Empty sequence is returned when not match exists. """ assert fieldsToMatch, repr(fieldsToMatch) assert all(k in tableInfo.dbFieldNames for k in fieldsToMatch.iterkeys()), repr(fieldsToMatch) assert selectFieldNames, repr(selectFieldNames) assert all(f in tableInfo.dbFieldNames for f in selectFieldNames), repr( selectFieldNames) # NOTE: make sure match expressions and values are in the same order matchPairs = fieldsToMatch.items() matchExpressionGen = ( p[0] + (' IS ' + {True:'TRUE', False:'FALSE'}[p[1]] if isinstance(p[1], bool) else ' IS NULL' if p[1] is None else ' IN %s' if isinstance(p[1], self._SEQUENCE_TYPES) else '=%s') for p in matchPairs) matchFieldValues = [p[1] for p in matchPairs if (not isinstance(p[1], (bool)) and p[1] is not None)] query = 'SELECT %s FROM %s WHERE (%s)' % ( ','.join(selectFieldNames), tableInfo.tableName, ' AND '.join(matchExpressionGen)) sqlParams = matchFieldValues if maxRows is not None: query += ' LIMIT %s' sqlParams.append(maxRows) conn.cursor.execute(query, sqlParams) rows = conn.cursor.fetchall() if rows: assert maxRows is None or len(rows) <= maxRows, "%d !<= %d" % ( len(rows), maxRows) assert len(rows[0]) == len(selectFieldNames), "%d != %d" % ( len(rows[0]), len(selectFieldNames)) else: rows = tuple() return rows @g_retrySQL def _getMatchingRowsWithRetries(self, tableInfo, fieldsToMatch, selectFieldNames, maxRows=None): """ Like _getMatchingRowsNoRetries(), but with retries on transient MySQL failures """ with ConnectionFactory.get() as conn: return self._getMatchingRowsNoRetries(tableInfo, conn, fieldsToMatch, selectFieldNames, maxRows) def _getOneMatchingRowNoRetries(self, tableInfo, conn, fieldsToMatch, selectFieldNames): """ Return a single matching row with the requested field values from the the requested table or None if nothing matched. tableInfo: Table information: a ClientJobsDAO._TableInfoBase instance conn: Owned connection acquired from ConnectionFactory.get() fieldsToMatch: Dictionary of internal fieldName/value mappings that identify the desired rows. If a value is an instance of ClientJobsDAO._SEQUENCE_TYPES (list/set/tuple), then the operator 'IN' will be used in the corresponding SQL predicate; if the value is bool: "IS TRUE/FALSE"; if the value is None: "IS NULL"; '=' will be used for all other cases. selectFieldNames: list of fields to return, using internal field names retval: A sequence of field values of the matching row in the order of the given field names; or None if there was no match. """ rows = self._getMatchingRowsNoRetries(tableInfo, conn, fieldsToMatch, selectFieldNames, maxRows=1) if rows: assert len(rows) == 1, repr(len(rows)) result = rows[0] else: result = None return result @g_retrySQL def _getOneMatchingRowWithRetries(self, tableInfo, fieldsToMatch, selectFieldNames): """ Like _getOneMatchingRowNoRetries(), but with retries on transient MySQL failures """ with ConnectionFactory.get() as conn: return self._getOneMatchingRowNoRetries(tableInfo, conn, fieldsToMatch, selectFieldNames) @classmethod def _normalizeHash(cls, hashValue): hashLen = len(hashValue) if hashLen < cls.HASH_MAX_LEN: hashValue += '\0' * (cls.HASH_MAX_LEN - hashLen) else: assert hashLen <= cls.HASH_MAX_LEN, ( "Hash is too long: hashLen=%r; hashValue=%r") % (hashLen, hashValue) return hashValue def _insertOrGetUniqueJobNoRetries( self, conn, client, cmdLine, jobHash, clientInfo, clientKey, params, minimumWorkers, maximumWorkers, jobType, priority, alreadyRunning): """ Attempt to insert a row with the given parameters into the jobs table. Return jobID of the inserted row, or of an existing row with matching client/jobHash key. The combination of client and jobHash are expected to be unique (enforced by a unique index on the two columns). NOTE: It's possibe that this or another process (on this or another machine) already inserted a row with matching client/jobHash key (e.g., StreamMgr). This may also happen undetected by this function due to a partially-successful insert operation (e.g., row inserted, but then connection was lost while reading response) followed by retries either of this function or in SteadyDB module. Parameters: ---------------------------------------------------------------- conn: Owned connection acquired from ConnectionFactory.get() client: Name of the client submitting the job cmdLine: Command line to use to launch each worker process; must be a non-empty string jobHash: unique hash of this job. The caller must insure that this, together with client, uniquely identifies this job request for the purposes of detecting duplicates. clientInfo: JSON encoded dict of client specific information. clientKey: Foreign key. params: JSON encoded dict of the parameters for the job. This can be fetched out of the database by the worker processes based on the jobID. minimumWorkers: minimum number of workers design at a time. maximumWorkers: maximum number of workers desired at a time. priority: Job scheduling priority; 0 is the default priority ( ClientJobsDAO.DEFAULT_JOB_PRIORITY); positive values are higher priority (up to ClientJobsDAO.MAX_JOB_PRIORITY), and negative values are lower priority (down to ClientJobsDAO.MIN_JOB_PRIORITY). Higher-priority jobs will be scheduled to run at the expense of the lower-priority jobs, and higher-priority job tasks will preempt those with lower priority if there is inadequate supply of scheduling slots. Excess lower priority job tasks will starve as long as slot demand exceeds supply. Most jobs should be scheduled with DEFAULT_JOB_PRIORITY. System jobs that must run at all cost, such as Multi-Model-Master, should be scheduled with MAX_JOB_PRIORITY. alreadyRunning: Used for unit test purposes only. This inserts the job in the running state. It is used when running a worker in standalone mode without hadoop- it gives it a job record to work with. retval: jobID of the inserted jobs row, or of an existing jobs row with matching client/jobHash key """ assert len(client) <= self.CLIENT_MAX_LEN, "client too long:" + repr(client) assert cmdLine, "Unexpected empty or None command-line: " + repr(cmdLine) assert len(jobHash) == self.HASH_MAX_LEN, "wrong hash len=%d" % len(jobHash) # Initial status if alreadyRunning: # STATUS_TESTMODE, so that scheduler won't pick it up (for in-proc tests) initStatus = self.STATUS_TESTMODE else: initStatus = self.STATUS_NOTSTARTED # Create a new job entry query = 'INSERT IGNORE INTO %s (status, client, client_info, client_key,' \ 'cmd_line, params, job_hash, _eng_last_update_time, ' \ 'minimum_workers, maximum_workers, priority, _eng_job_type) ' \ ' VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s, ' \ ' UTC_TIMESTAMP(), %%s, %%s, %%s, %%s) ' \ % (self.jobsTableName,) sqlParams = (initStatus, client, clientInfo, clientKey, cmdLine, params, jobHash, minimumWorkers, maximumWorkers, priority, jobType) numRowsInserted = conn.cursor.execute(query, sqlParams) jobID = 0 if numRowsInserted == 1: # Get the chosen job id # NOTE: LAST_INSERT_ID() returns 0 after intermittent connection failure conn.cursor.execute('SELECT LAST_INSERT_ID()') jobID = conn.cursor.fetchall()[0][0] if jobID == 0: self._logger.warn( '_insertOrGetUniqueJobNoRetries: SELECT LAST_INSERT_ID() returned 0; ' 'likely due to reconnection in SteadyDB following INSERT. ' 'jobType=%r; client=%r; clientInfo=%r; clientKey=%s; jobHash=%r; ' 'cmdLine=%r', jobType, client, _abbreviate(clientInfo, 32), clientKey, jobHash, cmdLine) else: # Assumption: nothing was inserted because this is a retry and the row # with this client/hash already exists from our prior # partially-successful attempt; or row with matching client/jobHash was # inserted already by some process on some machine. assert numRowsInserted == 0, repr(numRowsInserted) if jobID == 0: # Recover from intermittent failure in a partially-successful attempt; # or row with matching client/jobHash was already in table row = self._getOneMatchingRowNoRetries( self._jobs, conn, dict(client=client, job_hash=jobHash), ['job_id']) assert row is not None assert len(row) == 1, 'Unexpected num fields: ' + repr(len(row)) jobID = row[0] # --------------------------------------------------------------------- # If asked to enter the job in the running state, set the connection id # and start time as well if alreadyRunning: query = 'UPDATE %s SET _eng_cjm_conn_id=%%s, ' \ ' start_time=UTC_TIMESTAMP(), ' \ ' _eng_last_update_time=UTC_TIMESTAMP() ' \ ' WHERE job_id=%%s' \ % (self.jobsTableName,) conn.cursor.execute(query, (self._connectionID, jobID)) return jobID def _resumeJobNoRetries(self, conn, jobID, alreadyRunning): """ Resumes processing of an existing job that is presently in the STATUS_COMPLETED state. NOTE: this is primarily for resuming suspended Production and Stream Jobs; DO NOT use it on Hypersearch jobs. This prepares an existing job entry to resume processing. The CJM is always periodically sweeping the jobs table and when it finds a job that is ready to run, it will proceed to start it up on Hadoop. Parameters: ---------------------------------------------------------------- conn: Owned connection acquired from ConnectionFactory.get() jobID: jobID of the job to resume alreadyRunning: Used for unit test purposes only. This inserts the job in the running state. It is used when running a worker in standalone mode without hadoop. raises: Throws a RuntimeError if no rows are affected. This could either be because: 1) Because there was not matching jobID 2) or if the status of the job was not STATUS_COMPLETED. retval: nothing """ # Initial status if alreadyRunning: # Use STATUS_TESTMODE so scheduler will leave our row alone initStatus = self.STATUS_TESTMODE else: initStatus = self.STATUS_NOTSTARTED # NOTE: some of our clients (e.g., StreamMgr) may call us (directly or # indirectly) for the same job from different processes (even different # machines), so we should be prepared for the update to fail; same holds # if the UPDATE succeeds, but connection fails while reading result assignments = [ 'status=%s', 'completion_reason=DEFAULT', 'completion_msg=DEFAULT', 'worker_completion_reason=DEFAULT', 'worker_completion_msg=DEFAULT', 'end_time=DEFAULT', 'cancel=DEFAULT', '_eng_last_update_time=UTC_TIMESTAMP()', '_eng_allocate_new_workers=DEFAULT', '_eng_untended_dead_workers=DEFAULT', 'num_failed_workers=DEFAULT', 'last_failed_worker_error_msg=DEFAULT', '_eng_cleaning_status=DEFAULT', ] assignmentValues = [initStatus] if alreadyRunning: assignments += ['_eng_cjm_conn_id=%s', 'start_time=UTC_TIMESTAMP()', '_eng_last_update_time=UTC_TIMESTAMP()'] assignmentValues.append(self._connectionID) else: assignments += ['_eng_cjm_conn_id=DEFAULT', 'start_time=DEFAULT'] assignments = ', '.join(assignments) query = 'UPDATE %s SET %s ' \ ' WHERE job_id=%%s AND status=%%s' \ % (self.jobsTableName, assignments) sqlParams = assignmentValues + [jobID, self.STATUS_COMPLETED] numRowsAffected = conn.cursor.execute(query, sqlParams) assert numRowsAffected <= 1, repr(numRowsAffected) if numRowsAffected == 0: self._logger.info( "_resumeJobNoRetries: Redundant job-resume UPDATE: job was not " "suspended or was resumed by another process or operation was retried " "after connection failure; jobID=%s", jobID) return def getConnectionID(self): """ Return our connection ID. This can be used for worker identification purposes. NOTE: the actual MySQL connection ID used in queries may change from time to time if connection is re-acquired (e.g., upon MySQL server restart) or when more than one entry from the connection pool has been used (e.g., multi-threaded apps) """ return self._connectionID @logExceptions(_getLogger) def jobSuspend(self, jobID): """ Requests a job to be suspended NOTE: this is primarily for suspending Production Jobs; DO NOT use it on Hypersearch jobs. For canceling any job type, use jobCancel() instead! Parameters: ---------------------------------------------------------------- jobID: jobID of the job to resume retval: nothing """ # TODO: validate that the job is in the appropriate state for being # suspended: consider using a WHERE clause to make sure that # the job is not already in the "completed" state # TODO: when Nupic job control states get figured out, there may be a # different way to suspend jobs ("cancel" doesn't make sense for this) # NOTE: jobCancel() does retries on transient mysql failures self.jobCancel(jobID) return @logExceptions(_getLogger) def jobResume(self, jobID, alreadyRunning=False): """ Resumes processing of an existing job that is presently in the STATUS_COMPLETED state. NOTE: this is primarily for resuming suspended Production Jobs; DO NOT use it on Hypersearch jobs. NOTE: The job MUST be in the STATUS_COMPLETED state at the time of this call, otherwise an exception will be raised. This prepares an existing job entry to resume processing. The CJM is always periodically sweeping the jobs table and when it finds a job that is ready to run, will proceed to start it up on Hadoop. Parameters: ---------------------------------------------------------------- job: jobID of the job to resume alreadyRunning: Used for unit test purposes only. This inserts the job in the running state. It is used when running a worker in standalone mode without hadoop. raises: Throws a RuntimeError if no rows are affected. This could either be because: 1) Because there was not matching jobID 2) or if the status of the job was not STATUS_COMPLETED. retval: nothing """ row = self.jobGetFields(jobID, ['status']) (jobStatus,) = row if jobStatus != self.STATUS_COMPLETED: raise RuntimeError(("Failed to resume job: job was not suspended; " "jobID=%s; job status=%r") % (jobID, jobStatus)) # NOTE: on MySQL failures, we need to retry ConnectionFactory.get() as well # in order to recover from lost connections @g_retrySQL def resumeWithRetries(): with ConnectionFactory.get() as conn: self._resumeJobNoRetries(conn, jobID, alreadyRunning) resumeWithRetries() return @logExceptions(_getLogger) def jobInsert(self, client, cmdLine, clientInfo='', clientKey='', params='', alreadyRunning=False, minimumWorkers=0, maximumWorkers=0, jobType='', priority=DEFAULT_JOB_PRIORITY): """ Add an entry to the jobs table for a new job request. This is called by clients that wish to startup a new job, like a Hypersearch, stream job, or specific model evaluation from the engine. This puts a new entry into the jobs table. The CJM is always periodically sweeping the jobs table and when it finds a new job, will proceed to start it up on Hadoop. Parameters: ---------------------------------------------------------------- client: Name of the client submitting the job cmdLine: Command line to use to launch each worker process; must be a non-empty string clientInfo: JSON encoded dict of client specific information. clientKey: Foreign key. params: JSON encoded dict of the parameters for the job. This can be fetched out of the database by the worker processes based on the jobID. alreadyRunning: Used for unit test purposes only. This inserts the job in the running state. It is used when running a worker in standalone mode without hadoop - it gives it a job record to work with. minimumWorkers: minimum number of workers design at a time. maximumWorkers: maximum number of workers desired at a time. jobType: The type of job that this is. This should be one of the JOB_TYPE_XXXX enums. This is needed to allow a standard way of recognizing a job's function and capabilities. priority: Job scheduling priority; 0 is the default priority ( ClientJobsDAO.DEFAULT_JOB_PRIORITY); positive values are higher priority (up to ClientJobsDAO.MAX_JOB_PRIORITY), and negative values are lower priority (down to ClientJobsDAO.MIN_JOB_PRIORITY). Higher-priority jobs will be scheduled to run at the expense of the lower-priority jobs, and higher-priority job tasks will preempt those with lower priority if there is inadequate supply of scheduling slots. Excess lower priority job tasks will starve as long as slot demand exceeds supply. Most jobs should be scheduled with DEFAULT_JOB_PRIORITY. System jobs that must run at all cost, such as Multi-Model-Master, should be scheduled with MAX_JOB_PRIORITY. retval: jobID - unique ID assigned to this job """ jobHash = self._normalizeHash(uuid.uuid1().bytes) @g_retrySQL def insertWithRetries(): with ConnectionFactory.get() as conn: return self._insertOrGetUniqueJobNoRetries( conn, client=client, cmdLine=cmdLine, jobHash=jobHash, clientInfo=clientInfo, clientKey=clientKey, params=params, minimumWorkers=minimumWorkers, maximumWorkers=maximumWorkers, jobType=jobType, priority=priority, alreadyRunning=alreadyRunning) try: jobID = insertWithRetries() except: self._logger.exception( 'jobInsert FAILED: jobType=%r; client=%r; clientInfo=%r; clientKey=%r;' 'jobHash=%r; cmdLine=%r', jobType, client, _abbreviate(clientInfo, 48), clientKey, jobHash, cmdLine) raise else: self._logger.info( 'jobInsert: returning jobID=%s. jobType=%r; client=%r; clientInfo=%r; ' 'clientKey=%r; jobHash=%r; cmdLine=%r', jobID, jobType, client, _abbreviate(clientInfo, 48), clientKey, jobHash, cmdLine) return jobID @logExceptions(_getLogger) def jobInsertUnique(self, client, cmdLine, jobHash, clientInfo='', clientKey='', params='', minimumWorkers=0, maximumWorkers=0, jobType='', priority=DEFAULT_JOB_PRIORITY): """ Add an entry to the jobs table for a new job request, but only if the same job, by the same client is not already running. If the job is already running, or queued up to run, this call does nothing. If the job does not exist in the jobs table or has completed, it will be inserted and/or started up again. This method is called by clients, like StreamMgr, that wish to only start up a job if it hasn't already been started up. Parameters: ---------------------------------------------------------------- client: Name of the client submitting the job cmdLine: Command line to use to launch each worker process; must be a non-empty string jobHash: unique hash of this job. The client must insure that this uniquely identifies this job request for the purposes of detecting duplicates. clientInfo: JSON encoded dict of client specific information. clientKey: Foreign key. params: JSON encoded dict of the parameters for the job. This can be fetched out of the database by the worker processes based on the jobID. minimumWorkers: minimum number of workers design at a time. maximumWorkers: maximum number of workers desired at a time. jobType: The type of job that this is. This should be one of the JOB_TYPE_XXXX enums. This is needed to allow a standard way of recognizing a job's function and capabilities. priority: Job scheduling priority; 0 is the default priority ( ClientJobsDAO.DEFAULT_JOB_PRIORITY); positive values are higher priority (up to ClientJobsDAO.MAX_JOB_PRIORITY), and negative values are lower priority (down to ClientJobsDAO.MIN_JOB_PRIORITY). Higher-priority jobs will be scheduled to run at the expense of the lower-priority jobs, and higher-priority job tasks will preempt those with lower priority if there is inadequate supply of scheduling slots. Excess lower priority job tasks will starve as long as slot demand exceeds supply. Most jobs should be scheduled with DEFAULT_JOB_PRIORITY. System jobs that must run at all cost, such as Multi-Model-Master, should be scheduled with MAX_JOB_PRIORITY. retval: jobID of the newly inserted or existing job. """ assert cmdLine, "Unexpected empty or None command-line: " + repr(cmdLine) @g_retrySQL def insertUniqueWithRetries(): jobHashValue = self._normalizeHash(jobHash) jobID = None with ConnectionFactory.get() as conn: row = self._getOneMatchingRowNoRetries( self._jobs, conn, dict(client=client, job_hash=jobHashValue), ['job_id', 'status']) if row is not None: (jobID, status) = row if status == self.STATUS_COMPLETED: # Restart existing job that had completed query = 'UPDATE %s SET client_info=%%s, ' \ ' client_key=%%s, ' \ ' cmd_line=%%s, ' \ ' params=%%s, ' \ ' minimum_workers=%%s, ' \ ' maximum_workers=%%s, ' \ ' priority=%%s, '\ ' _eng_job_type=%%s ' \ ' WHERE (job_id=%%s AND status=%%s)' \ % (self.jobsTableName,) sqlParams = (clientInfo, clientKey, cmdLine, params, minimumWorkers, maximumWorkers, priority, jobType, jobID, self.STATUS_COMPLETED) numRowsUpdated = conn.cursor.execute(query, sqlParams) assert numRowsUpdated <= 1, repr(numRowsUpdated) if numRowsUpdated == 0: self._logger.info( "jobInsertUnique: Redundant job-reuse UPDATE: job restarted by " "another process, values were unchanged, or operation was " "retried after connection failure; jobID=%s", jobID) # Restart the job, unless another process beats us to it self._resumeJobNoRetries(conn, jobID, alreadyRunning=False) else: # There was no job row with matching client/jobHash, so insert one jobID = self._insertOrGetUniqueJobNoRetries( conn, client=client, cmdLine=cmdLine, jobHash=jobHashValue, clientInfo=clientInfo, clientKey=clientKey, params=params, minimumWorkers=minimumWorkers, maximumWorkers=maximumWorkers, jobType=jobType, priority=priority, alreadyRunning=False) return jobID try: jobID = insertUniqueWithRetries() except: self._logger.exception( 'jobInsertUnique FAILED: jobType=%r; client=%r; ' 'clientInfo=%r; clientKey=%r; jobHash=%r; cmdLine=%r', jobType, client, _abbreviate(clientInfo, 48), clientKey, jobHash, cmdLine) raise else: self._logger.info( 'jobInsertUnique: returning jobID=%s. jobType=%r; client=%r; ' 'clientInfo=%r; clientKey=%r; jobHash=%r; cmdLine=%r', jobID, jobType, client, _abbreviate(clientInfo, 48), clientKey, jobHash, cmdLine) return jobID @g_retrySQL def _startJobWithRetries(self, jobID): """ Place the given job in STATUS_RUNNING mode; the job is expected to be STATUS_NOTSTARTED. NOTE: this function was factored out of jobStartNext because it's also needed for testing (e.g., test_client_jobs_dao.py) """ with ConnectionFactory.get() as conn: query = 'UPDATE %s SET status=%%s, ' \ ' _eng_cjm_conn_id=%%s, ' \ ' start_time=UTC_TIMESTAMP(), ' \ ' _eng_last_update_time=UTC_TIMESTAMP() ' \ ' WHERE (job_id=%%s AND status=%%s)' \ % (self.jobsTableName,) sqlParams = [self.STATUS_RUNNING, self._connectionID, jobID, self.STATUS_NOTSTARTED] numRowsUpdated = conn.cursor.execute(query, sqlParams) if numRowsUpdated != 1: self._logger.warn('jobStartNext: numRowsUpdated=%r instead of 1; ' 'likely side-effect of transient connection ' 'failure', numRowsUpdated) return @logExceptions(_getLogger) def jobStartNext(self): """ For use only by Nupic Scheduler (also known as ClientJobManager) Look through the jobs table and see if any new job requests have been queued up. If so, pick one and mark it as starting up and create the model table to hold the results Parameters: ---------------------------------------------------------------- retval: jobID of the job we are starting up, if found; None if not found """ # NOTE: cursor.execute('SELECT @update_id') trick is unreliable: if a # connection loss occurs during cursor.execute, then the server-cached # information is lost, and we cannot get the updated job ID; so, we use # this select instead row = self._getOneMatchingRowWithRetries( self._jobs, dict(status=self.STATUS_NOTSTARTED), ['job_id']) if row is None: return None (jobID,) = row self._startJobWithRetries(jobID) return jobID @logExceptions(_getLogger) @g_retrySQL def jobReactivateRunningJobs(self): """ Look through the jobs table and reactivate all that are already in the running state by setting their _eng_allocate_new_workers fields to True; used by Nupic Scheduler as part of its failure-recovery procedure. """ # Get a database connection and cursor with ConnectionFactory.get() as conn: query = 'UPDATE %s SET _eng_cjm_conn_id=%%s, ' \ ' _eng_allocate_new_workers=TRUE ' \ ' WHERE status=%%s ' \ % (self.jobsTableName,) conn.cursor.execute(query, [self._connectionID, self.STATUS_RUNNING]) return @logExceptions(_getLogger) def jobGetDemand(self,): """ Look through the jobs table and get the demand - minimum and maximum number of workers requested, if new workers are to be allocated, if there are any untended dead workers, for all running jobs. Parameters: ---------------------------------------------------------------- retval: list of ClientJobsDAO._jobs.jobDemandNamedTuple nametuples containing the demand - min and max workers, allocate_new_workers, untended_dead_workers, num_failed_workers for each running (STATUS_RUNNING) job. Empty list when there isn't any demand. """ rows = self._getMatchingRowsWithRetries( self._jobs, dict(status=self.STATUS_RUNNING), [self._jobs.pubToDBNameDict[f] for f in self._jobs.jobDemandNamedTuple._fields]) return [self._jobs.jobDemandNamedTuple._make(r) for r in rows] @logExceptions(_getLogger) @g_retrySQL def jobCancelAllRunningJobs(self): """ Set cancel field of all currently-running jobs to true. """ # Get a database connection and cursor with ConnectionFactory.get() as conn: query = 'UPDATE %s SET cancel=TRUE WHERE status<>%%s ' \ % (self.jobsTableName,) conn.cursor.execute(query, [self.STATUS_COMPLETED]) return @logExceptions(_getLogger) @g_retrySQL def jobCountCancellingJobs(self,): """ Look through the jobs table and count the running jobs whose cancel field is true. Parameters: ---------------------------------------------------------------- retval: A count of running jobs with the cancel field set to true. """ with ConnectionFactory.get() as conn: query = 'SELECT COUNT(job_id) '\ 'FROM %s ' \ 'WHERE (status<>%%s AND cancel is TRUE)' \ % (self.jobsTableName,) conn.cursor.execute(query, [self.STATUS_COMPLETED]) rows = conn.cursor.fetchall() return rows[0][0] @logExceptions(_getLogger) @g_retrySQL def jobGetCancellingJobs(self,): """ Look through the jobs table and get the list of running jobs whose cancel field is true. Parameters: ---------------------------------------------------------------- retval: A (possibly empty) sequence of running job IDs with cancel field set to true """ with ConnectionFactory.get() as conn: query = 'SELECT job_id '\ 'FROM %s ' \ 'WHERE (status<>%%s AND cancel is TRUE)' \ % (self.jobsTableName,) conn.cursor.execute(query, [self.STATUS_COMPLETED]) rows = conn.cursor.fetchall() return tuple(r[0] for r in rows) @staticmethod @logExceptions(_getLogger) def partitionAtIntervals(data, intervals): """ Generator to allow iterating slices at dynamic intervals Parameters: ---------------------------------------------------------------- data: Any data structure that supports slicing (i.e. list or tuple) *intervals: Iterable of intervals. The sum of intervals should be less than, or equal to the length of data. """ assert sum(intervals) <= len(data) start = 0 for interval in intervals: end = start + interval yield data[start:end] start = end raise StopIteration @staticmethod @logExceptions(_getLogger) def _combineResults(result, *namedTuples): """ Return a list of namedtuples from the result of a join query. A single database result is partitioned at intervals corresponding to the fields in namedTuples. The return value is the result of applying namedtuple._make() to each of the partitions, for each of the namedTuples. Parameters: ---------------------------------------------------------------- result: Tuple representing a single result from a database query *namedTuples: List of named tuples. """ results = ClientJobsDAO.partitionAtIntervals( result, [len(nt._fields) for nt in namedTuples]) return [nt._make(result) for nt, result in zip(namedTuples, results)] @logExceptions(_getLogger) @g_retrySQL def jobInfoWithModels(self, jobID): """ Get all info about a job, with model details, if available. Parameters: ---------------------------------------------------------------- job: jobID of the job to query retval: A sequence of two-tuples if the jobID exists in the jobs table (exeption is raised if it doesn't exist). Each two-tuple contains an instance of jobInfoNamedTuple as the first element and an instance of modelInfoNamedTuple as the second element. NOTE: In the case where there are no matching model rows, a sequence of one two-tuple will still be returned, but the modelInfoNamedTuple fields will be None, and the jobInfoNamedTuple fields will be populated. """ # Get a database connection and cursor combinedResults = None with ConnectionFactory.get() as conn: # NOTE: Since we're using a LEFT JOIN on the models table, there need not # be a matching row in the models table, but the matching row from the # jobs table will still be returned (along with all fields from the models # table with values of None in case there were no matchings models) query = ' '.join([ 'SELECT %s.*, %s.*' % (self.jobsTableName, self.modelsTableName), 'FROM %s' % self.jobsTableName, 'LEFT JOIN %s USING(job_id)' % self.modelsTableName, 'WHERE job_id=%s']) conn.cursor.execute(query, (jobID,)) if conn.cursor.rowcount > 0: combinedResults = [ ClientJobsDAO._combineResults( result, self._jobs.jobInfoNamedTuple, self._models.modelInfoNamedTuple ) for result in conn.cursor.fetchall()] if combinedResults is not None: return combinedResults raise RuntimeError("jobID=%s not found within the jobs table" % (jobID)) @logExceptions(_getLogger) def jobInfo(self, jobID): """ Get all info about a job Parameters: ---------------------------------------------------------------- job: jobID of the job to query retval: namedtuple containing the job info. """ row = self._getOneMatchingRowWithRetries( self._jobs, dict(job_id=jobID), [self._jobs.pubToDBNameDict[n] for n in self._jobs.jobInfoNamedTuple._fields]) if row is None: raise RuntimeError("jobID=%s not found within the jobs table" % (jobID)) # Create a namedtuple with the names to values return self._jobs.jobInfoNamedTuple._make(row) @logExceptions(_getLogger) @g_retrySQL def jobSetStatus(self, jobID, status, useConnectionID=True,): """ Change the status on the given job Parameters: ---------------------------------------------------------------- job: jobID of the job to change status status: new status string (ClientJobsDAO.STATUS_xxxxx) useConnectionID: True if the connection id of the calling function must be the same as the connection that created the job. Set to False for hypersearch workers """ # Get a database connection and cursor with ConnectionFactory.get() as conn: query = 'UPDATE %s SET status=%%s, ' \ ' _eng_last_update_time=UTC_TIMESTAMP() ' \ ' WHERE job_id=%%s' \ % (self.jobsTableName,) sqlParams = [status, jobID] if useConnectionID: query += ' AND _eng_cjm_conn_id=%s' sqlParams.append(self._connectionID) result = conn.cursor.execute(query, sqlParams) if result != 1: raise RuntimeError("Tried to change the status of job %d to %s, but " "this job belongs to some other CJM" % ( jobID, status)) @logExceptions(_getLogger) @g_retrySQL def jobSetCompleted(self, jobID, completionReason, completionMsg, useConnectionID = True): """ Change the status on the given job to completed Parameters: ---------------------------------------------------------------- job: jobID of the job to mark as completed completionReason: completionReason string completionMsg: completionMsg string useConnectionID: True if the connection id of the calling function must be the same as the connection that created the job. Set to False for hypersearch workers """ # Get a database connection and cursor with ConnectionFactory.get() as conn: query = 'UPDATE %s SET status=%%s, ' \ ' completion_reason=%%s, ' \ ' completion_msg=%%s, ' \ ' end_time=UTC_TIMESTAMP(), ' \ ' _eng_last_update_time=UTC_TIMESTAMP() ' \ ' WHERE job_id=%%s' \ % (self.jobsTableName,) sqlParams = [self.STATUS_COMPLETED, completionReason, completionMsg, jobID] if useConnectionID: query += ' AND _eng_cjm_conn_id=%s' sqlParams.append(self._connectionID) result = conn.cursor.execute(query, sqlParams) if result != 1: raise RuntimeError("Tried to change the status of jobID=%s to " "completed, but this job could not be found or " "belongs to some other CJM" % (jobID)) @logExceptions(_getLogger) def jobCancel(self, jobID): """ Cancel the given job. This will update the cancel field in the jobs table and will result in the job being cancelled. Parameters: ---------------------------------------------------------------- jobID: jobID of the job to mark as completed to False for hypersearch workers """ self._logger.info('Canceling jobID=%s', jobID) # NOTE: jobSetFields does retries on transient mysql failures self.jobSetFields(jobID, {"cancel" : True}, useConnectionID=False) @logExceptions(_getLogger) def jobGetModelIDs(self, jobID): """Fetch all the modelIDs that correspond to a given jobID; empty sequence if none""" rows = self._getMatchingRowsWithRetries(self._models, dict(job_id=jobID), ['model_id']) return [r[0] for r in rows] @logExceptions(_getLogger) @g_retrySQL def getActiveJobCountForClientInfo(self, clientInfo): """ Return the number of jobs for the given clientInfo and a status that is not completed. """ with ConnectionFactory.get() as conn: query = 'SELECT count(job_id) ' \ 'FROM %s ' \ 'WHERE client_info = %%s ' \ ' AND status != %%s' % self.jobsTableName conn.cursor.execute(query, [clientInfo, self.STATUS_COMPLETED]) activeJobCount = conn.cursor.fetchone()[0] return activeJobCount @logExceptions(_getLogger) @g_retrySQL def getActiveJobCountForClientKey(self, clientKey): """ Return the number of jobs for the given clientKey and a status that is not completed. """ with ConnectionFactory.get() as conn: query = 'SELECT count(job_id) ' \ 'FROM %s ' \ 'WHERE client_key = %%s ' \ ' AND status != %%s' % self.jobsTableName conn.cursor.execute(query, [clientKey, self.STATUS_COMPLETED]) activeJobCount = conn.cursor.fetchone()[0] return activeJobCount @logExceptions(_getLogger) @g_retrySQL def getActiveJobsForClientInfo(self, clientInfo, fields=[]): """ Fetch jobIDs for jobs in the table with optional fields given a specific clientInfo """ # Form the sequence of field name strings that will go into the # request dbFields = [self._jobs.pubToDBNameDict[x] for x in fields] dbFieldsStr = ','.join(['job_id'] + dbFields) with ConnectionFactory.get() as conn: query = 'SELECT %s FROM %s ' \ 'WHERE client_info = %%s ' \ ' AND status != %%s' % (dbFieldsStr, self.jobsTableName) conn.cursor.execute(query, [clientInfo, self.STATUS_COMPLETED]) rows = conn.cursor.fetchall() return rows @logExceptions(_getLogger) @g_retrySQL def getActiveJobsForClientKey(self, clientKey, fields=[]): """ Fetch jobIDs for jobs in the table with optional fields given a specific clientKey """ # Form the sequence of field name strings that will go into the # request dbFields = [self._jobs.pubToDBNameDict[x] for x in fields] dbFieldsStr = ','.join(['job_id'] + dbFields) with ConnectionFactory.get() as conn: query = 'SELECT %s FROM %s ' \ 'WHERE client_key = %%s ' \ ' AND status != %%s' % (dbFieldsStr, self.jobsTableName) conn.cursor.execute(query, [clientKey, self.STATUS_COMPLETED]) rows = conn.cursor.fetchall() return rows @logExceptions(_getLogger) @g_retrySQL def getJobs(self, fields=[]): """ Fetch jobIDs for jobs in the table with optional fields """ # Form the sequence of field name strings that will go into the # request dbFields = [self._jobs.pubToDBNameDict[x] for x in fields] dbFieldsStr = ','.join(['job_id'] + dbFields) with ConnectionFactory.get() as conn: query = 'SELECT %s FROM %s' % (dbFieldsStr, self.jobsTableName) conn.cursor.execute(query) rows = conn.cursor.fetchall() return rows @logExceptions(_getLogger) @g_retrySQL def getFieldsForActiveJobsOfType(self, jobType, fields=[]): """ Helper function for querying the models table including relevant job info where the job type matches the specified jobType. Only records for which there is a matching jobId in both tables is returned, and only the requested fields are returned in each result, assuming that there is not a conflict. This function is useful, for example, in querying a cluster for a list of actively running production models (according to the state of the client jobs database). jobType must be one of the JOB_TYPE_XXXX enumerations. Parameters: ---------------------------------------------------------------- jobType: jobType enum fields: list of fields to return Returns: List of tuples containing the jobId and requested field values """ dbFields = [self._jobs.pubToDBNameDict[x] for x in fields] dbFieldsStr = ','.join(['job_id'] + dbFields) with ConnectionFactory.get() as conn: query = \ 'SELECT DISTINCT %s ' \ 'FROM %s j ' \ 'LEFT JOIN %s m USING(job_id) '\ 'WHERE j.status != %%s ' \ 'AND _eng_job_type = %%s' % (dbFieldsStr, self.jobsTableName, self.modelsTableName) conn.cursor.execute(query, [self.STATUS_COMPLETED, jobType]) return conn.cursor.fetchall() @logExceptions(_getLogger) def jobGetFields(self, jobID, fields): """ Fetch the values of 1 or more fields from a job record. Here, 'fields' is a list with the names of the fields to fetch. The names are the public names of the fields (camelBack, not the lower_case_only form as stored in the DB). Parameters: ---------------------------------------------------------------- jobID: jobID of the job record fields: list of fields to return Returns: A sequence of field values in the same order as the requested field list -> [field1, field2, ...] """ # NOTE: jobsGetFields retries on transient mysql failures return self.jobsGetFields([jobID], fields, requireAll=True)[0][1] @logExceptions(_getLogger) def jobsGetFields(self, jobIDs, fields, requireAll=True): """ Fetch the values of 1 or more fields from a sequence of job records. Here, 'fields' is a sequence (list or tuple) with the names of the fields to fetch. The names are the public names of the fields (camelBack, not the lower_case_only form as stored in the DB). WARNING!!!: The order of the results are NOT necessarily in the same order as the order of the job IDs passed in!!! Parameters: ---------------------------------------------------------------- jobIDs: A sequence of jobIDs fields: A list of fields to return for each jobID Returns: A list of tuples->(jobID, [field1, field2,...]) """ assert isinstance(jobIDs, self._SEQUENCE_TYPES) assert len(jobIDs) >=1 rows = self._getMatchingRowsWithRetries( self._jobs, dict(job_id=jobIDs), ['job_id'] + [self._jobs.pubToDBNameDict[x] for x in fields]) if requireAll and len(rows) < len(jobIDs): # NOTE: this will also trigger if the jobIDs list included duplicates raise RuntimeError("jobIDs %s not found within the jobs table" % ( (set(jobIDs) - set(r[0] for r in rows)),)) return [(r[0], list(r[1:])) for r in rows] @logExceptions(_getLogger) @g_retrySQL def jobSetFields(self, jobID, fields, useConnectionID=True, ignoreUnchanged=False): """ Change the values of 1 or more fields in a job. Here, 'fields' is a dict with the name/value pairs to change. The names are the public names of the fields (camelBack, not the lower_case_only form as stored in the DB). This method is for private use by the ClientJobManager only. Parameters: ---------------------------------------------------------------- jobID: jobID of the job record fields: dictionary of fields to change useConnectionID: True if the connection id of the calling function must be the same as the connection that created the job. Set to False for hypersearch workers ignoreUnchanged: The default behavior is to throw a RuntimeError if no rows are affected. This could either be because: 1) Because there was not matching jobID 2) or if the data to update matched the data in the DB exactly. Set this parameter to True if you expect case 2 and wish to supress the error. """ # Form the sequecce of key=value strings that will go into the # request assignmentExpressions = ','.join( ["%s=%%s" % (self._jobs.pubToDBNameDict[f],) for f in fields.iterkeys()]) assignmentValues = fields.values() query = 'UPDATE %s SET %s ' \ ' WHERE job_id=%%s' \ % (self.jobsTableName, assignmentExpressions,) sqlParams = assignmentValues + [jobID] if useConnectionID: query += ' AND _eng_cjm_conn_id=%s' sqlParams.append(self._connectionID) # Get a database connection and cursor with ConnectionFactory.get() as conn: result = conn.cursor.execute(query, sqlParams) if result != 1 and not ignoreUnchanged: raise RuntimeError( "Tried to change fields (%r) of jobID=%s conn_id=%r), but an error " \ "occurred. result=%r; query=%r" % ( assignmentExpressions, jobID, self._connectionID, result, query)) @logExceptions(_getLogger) @g_retrySQL def jobSetFieldIfEqual(self, jobID, fieldName, newValue, curValue): """ Change the value of 1 field in a job to 'newValue', but only if the current value matches 'curValue'. The 'fieldName' is the public name of the field (camelBack, not the lower_case_only form as stored in the DB). This method is used for example by HypersearcWorkers to update the engWorkerState field periodically. By qualifying on curValue, it insures that only 1 worker at a time is elected to perform the next scheduled periodic sweep of the models. Parameters: ---------------------------------------------------------------- jobID: jobID of the job record to modify fieldName: public field name of the field newValue: new value of the field to set curValue: current value to qualify against retval: True if we successfully modified the field False if curValue did not match """ # Get the private field name and string form of the value dbFieldName = self._jobs.pubToDBNameDict[fieldName] conditionValue = [] if isinstance(curValue, bool): conditionExpression = '%s IS %s' % ( dbFieldName, {True:'TRUE', False:'FALSE'}[curValue]) elif curValue is None: conditionExpression = '%s is NULL' % (dbFieldName,) else: conditionExpression = '%s=%%s' % (dbFieldName,) conditionValue.append(curValue) query = 'UPDATE %s SET _eng_last_update_time=UTC_TIMESTAMP(), %s=%%s ' \ ' WHERE job_id=%%s AND %s' \ % (self.jobsTableName, dbFieldName, conditionExpression) sqlParams = [newValue, jobID] + conditionValue with ConnectionFactory.get() as conn: result = conn.cursor.execute(query, sqlParams) return (result == 1) @logExceptions(_getLogger) @g_retrySQL def jobIncrementIntField(self, jobID, fieldName, increment=1, useConnectionID=False): """ Incremet the value of 1 field in a job by increment. The 'fieldName' is the public name of the field (camelBack, not the lower_case_only form as stored in the DB). This method is used for example by HypersearcWorkers to update the engWorkerState field periodically. By qualifying on curValue, it insures that only 1 worker at a time is elected to perform the next scheduled periodic sweep of the models. Parameters: ---------------------------------------------------------------- jobID: jobID of the job record to modify fieldName: public field name of the field increment: increment is added to the current value of the field """ # Get the private field name and string form of the value dbFieldName = self._jobs.pubToDBNameDict[fieldName] # Get a database connection and cursor with ConnectionFactory.get() as conn: query = 'UPDATE %s SET %s=%s+%%s ' \ ' WHERE job_id=%%s' \ % (self.jobsTableName, dbFieldName, dbFieldName) sqlParams = [increment, jobID] if useConnectionID: query += ' AND _eng_cjm_conn_id=%s' sqlParams.append(self._connectionID) result = conn.cursor.execute(query, sqlParams) if result != 1: raise RuntimeError( "Tried to increment the field (%r) of jobID=%s (conn_id=%r), but an " \ "error occurred. result=%r; query=%r" % ( dbFieldName, jobID, self._connectionID, result, query)) @logExceptions(_getLogger) @g_retrySQL def jobUpdateResults(self, jobID, results): """ Update the results string and last-update-time fields of a model. Parameters: ---------------------------------------------------------------- jobID: job ID of model to modify results: new results (json dict string) """ with ConnectionFactory.get() as conn: query = 'UPDATE %s SET _eng_last_update_time=UTC_TIMESTAMP(), ' \ ' results=%%s ' \ ' WHERE job_id=%%s' % (self.jobsTableName,) conn.cursor.execute(query, [results, jobID]) @logExceptions(_getLogger) @g_retrySQL def modelsClearAll(self): """ Delete all models from the models table Parameters: ---------------------------------------------------------------- """ self._logger.info('Deleting all rows from models table %r', self.modelsTableName) with ConnectionFactory.get() as conn: query = 'DELETE FROM %s' % (self.modelsTableName) conn.cursor.execute(query) @logExceptions(_getLogger) def modelInsertAndStart(self, jobID, params, paramsHash, particleHash=None): """ Insert a new unique model (based on params) into the model table in the "running" state. This will return two things: whether or not the model was actually inserted (i.e. that set of params isn't already in the table) and the modelID chosen for that set of params. Even if the model was not inserted by this call (it was already there) the modelID of the one already inserted is returned. Parameters: ---------------------------------------------------------------- jobID: jobID of the job to add models for params: params for this model paramsHash hash of the params, generated by the worker particleHash hash of the particle info (for PSO). If not provided, then paramsHash will be used. retval: (modelID, wasInserted) modelID: the model ID for this set of params wasInserted: True if this call ended up inserting the new model. False if this set of params was already in the model table. """ # Fill in default particleHash if particleHash is None: particleHash = paramsHash # Normalize hashes paramsHash = self._normalizeHash(paramsHash) particleHash = self._normalizeHash(particleHash) def findExactMatchNoRetries(conn): return self._getOneMatchingRowNoRetries( self._models, conn, {'job_id':jobID, '_eng_params_hash':paramsHash, '_eng_particle_hash':particleHash}, ['model_id', '_eng_worker_conn_id']) @g_retrySQL def findExactMatchWithRetries(): with ConnectionFactory.get() as conn: return findExactMatchNoRetries(conn) # Check if the model is already in the models table # # NOTE: with retries of mysql transient failures, we can't always tell # whether the row was already inserted (e.g., comms failure could occur # after insertion into table, but before arrival or response), so the # need to check before attempting to insert a new row # # TODO: if we could be assured that the caller already verified the # model's absence before calling us, we could skip this check here row = findExactMatchWithRetries() if row is not None: return (row[0], False) @g_retrySQL def insertModelWithRetries(): """ NOTE: it's possible that another process on some machine is attempting to insert the same model at the same time as the caller """ with ConnectionFactory.get() as conn: # Create a new job entry query = 'INSERT INTO %s (job_id, params, status, _eng_params_hash, ' \ ' _eng_particle_hash, start_time, _eng_last_update_time, ' \ ' _eng_worker_conn_id) ' \ ' VALUES (%%s, %%s, %%s, %%s, %%s, UTC_TIMESTAMP(), ' \ ' UTC_TIMESTAMP(), %%s) ' \ % (self.modelsTableName,) sqlParams = (jobID, params, self.STATUS_RUNNING, paramsHash, particleHash, self._connectionID) try: numRowsAffected = conn.cursor.execute(query, sqlParams) except Exception, e: # NOTE: We have seen instances where some package in the calling # chain tries to interpret the exception message using unicode. # Since the exception message contains binary data (the hashes), this # can in turn generate a Unicode translation exception. So, we catch # ALL exceptions here and look for the string "Duplicate entry" in # the exception args just in case this happens. For example, the # Unicode exception we might get is: # (<type 'exceptions.UnicodeDecodeError'>, UnicodeDecodeError('utf8', "Duplicate entry '1000-?.\x18\xb1\xd3\xe0CO\x05\x8b\xf80\xd7E5\xbb' for key 'job_id'", 25, 26, 'invalid start byte')) # # If it weren't for this possible Unicode translation error, we # could watch for only the exceptions we want, like this: # except pymysql.IntegrityError, e: # if e.args[0] != mysqlerrors.DUP_ENTRY: # raise if "Duplicate entry" not in str(e): raise # NOTE: duplicate entry scenario: however, we can't discern # whether it was inserted by another process or this one, because an # intermittent failure may have caused us to retry self._logger.info('Model insert attempt failed with DUP_ENTRY: ' 'jobID=%s; paramsHash=%s OR particleHash=%s; %r', jobID, paramsHash.encode('hex'), particleHash.encode('hex'), e) else: if numRowsAffected == 1: # NOTE: SELECT LAST_INSERT_ID() returns 0 after re-connection conn.cursor.execute('SELECT LAST_INSERT_ID()') modelID = conn.cursor.fetchall()[0][0] if modelID != 0: return (modelID, True) else: self._logger.warn( 'SELECT LAST_INSERT_ID for model returned 0, implying loss of ' 'connection: jobID=%s; paramsHash=%r; particleHash=%r', jobID, paramsHash, particleHash) else: self._logger.error( 'Attempt to insert model resulted in unexpected numRowsAffected: ' 'expected 1, but got %r; jobID=%s; paramsHash=%r; ' 'particleHash=%r', numRowsAffected, jobID, paramsHash, particleHash) # Look up the model and discern whether it is tagged with our conn id row = findExactMatchNoRetries(conn) if row is not None: (modelID, connectionID) = row return (modelID, connectionID == self._connectionID) # This set of params is already in the table, just get the modelID query = 'SELECT (model_id) FROM %s ' \ ' WHERE job_id=%%s AND ' \ ' (_eng_params_hash=%%s ' \ ' OR _eng_particle_hash=%%s) ' \ ' LIMIT 1 ' \ % (self.modelsTableName,) sqlParams = [jobID, paramsHash, particleHash] numRowsFound = conn.cursor.execute(query, sqlParams) assert numRowsFound == 1, ( 'Model not found: jobID=%s AND (paramsHash=%r OR particleHash=%r); ' 'numRowsFound=%r') % (jobID, paramsHash, particleHash, numRowsFound) (modelID,) = conn.cursor.fetchall()[0] return (modelID, False) return insertModelWithRetries() @logExceptions(_getLogger) def modelsInfo(self, modelIDs): """ Get ALL info for a set of models WARNING!!!: The order of the results are NOT necessarily in the same order as the order of the model IDs passed in!!! Parameters: ---------------------------------------------------------------- modelIDs: list of model IDs retval: list of nametuples containing all the fields stored for each model. """ assert isinstance(modelIDs, self._SEQUENCE_TYPES), ( "wrong modelIDs type: %s") % (type(modelIDs),) assert modelIDs, "modelIDs is empty" rows = self._getMatchingRowsWithRetries( self._models, dict(model_id=modelIDs), [self._models.pubToDBNameDict[f] for f in self._models.modelInfoNamedTuple._fields]) results = [self._models.modelInfoNamedTuple._make(r) for r in rows] # NOTE: assetion will also fail if modelIDs contains duplicates assert len(results) == len(modelIDs), "modelIDs not found: %s" % ( set(modelIDs) - set(r.modelId for r in results)) return results @logExceptions(_getLogger) def modelsGetFields(self, modelIDs, fields): """ Fetch the values of 1 or more fields from a sequence of model records. Here, 'fields' is a list with the names of the fields to fetch. The names are the public names of the fields (camelBack, not the lower_case_only form as stored in the DB). WARNING!!!: The order of the results are NOT necessarily in the same order as the order of the model IDs passed in!!! Parameters: ---------------------------------------------------------------- modelIDs: A single modelID or sequence of modelIDs fields: A list of fields to return Returns: If modelIDs is a sequence: a list of tuples->(modelID, [field1, field2,...]) If modelIDs is a single modelID: a list of field values->[field1, field2,...] """ assert len(fields) >= 1, 'fields is empty' # Form the sequence of field name strings that will go into the # request isSequence = isinstance(modelIDs, self._SEQUENCE_TYPES) if isSequence: assert len(modelIDs) >=1, 'modelIDs is empty' else: modelIDs = [modelIDs] rows = self._getMatchingRowsWithRetries( self._models, dict(model_id=modelIDs), ['model_id'] + [self._models.pubToDBNameDict[f] for f in fields]) if len(rows) < len(modelIDs): raise RuntimeError("modelIDs not found within the models table: %s" % ( (set(modelIDs) - set(r[0] for r in rows)),)) if not isSequence: return list(rows[0][1:]) return [(r[0], list(r[1:])) for r in rows] @logExceptions(_getLogger) @g_retrySQL def modelsGetFieldsForJob(self, jobID, fields, ignoreKilled=False): """ Gets the specified fields for all the models for a single job. This is similar to modelsGetFields Parameters: ---------------------------------------------------------------- jobID: jobID for the models to be searched fields: A list of fields to return ignoreKilled: (True/False). If True, this will ignore models that have been killed Returns: a (possibly empty) list of tuples as follows [ (model_id1, [field1, ..., fieldn]), (model_id2, [field1, ..., fieldn]), (model_id3, [field1, ..., fieldn]) ... ] NOTE: since there is a window of time between a job getting inserted into jobs table and the job's worker(s) starting up and creating models, an empty-list result is one of the normal outcomes. """ assert len(fields) >= 1, 'fields is empty' # Form the sequence of field name strings that will go into the # request dbFields = [self._models.pubToDBNameDict[x] for x in fields] dbFieldsStr = ','.join(dbFields) query = 'SELECT model_id, %s FROM %s ' \ ' WHERE job_id=%%s ' \ % (dbFieldsStr, self.modelsTableName) sqlParams = [jobID] if ignoreKilled: query += ' AND (completion_reason IS NULL OR completion_reason != %s)' sqlParams.append(self.CMPL_REASON_KILLED) # Get a database connection and cursor with ConnectionFactory.get() as conn: conn.cursor.execute(query, sqlParams) rows = conn.cursor.fetchall() if rows is None: # fetchall is defined to return a (possibly-empty) sequence of # sequences; however, we occasionally see None returned and don't know # why... self._logger.error("Unexpected None result from cursor.fetchall; " "query=%r; Traceback=%r", query, traceback.format_exc()) return [(r[0], list(r[1:])) for r in rows] @logExceptions(_getLogger) @g_retrySQL def modelsGetFieldsForCheckpointed(self, jobID, fields): """ Gets fields from all models in a job that have been checkpointed. This is used to figure out whether or not a new model should be checkpointed. Parameters: ----------------------------------------------------------------------- jobID: The jobID for the models to be searched fields: A list of fields to return Returns: a (possibly-empty) list of tuples as follows [ (model_id1, [field1, ..., fieldn]), (model_id2, [field1, ..., fieldn]), (model_id3, [field1, ..., fieldn]) ... ] """ assert len(fields) >= 1, "fields is empty" # Get a database connection and cursor with ConnectionFactory.get() as conn: dbFields = [self._models.pubToDBNameDict[f] for f in fields] dbFieldStr = ", ".join(dbFields) query = 'SELECT model_id, {fields} from {models}' \ ' WHERE job_id=%s AND model_checkpoint_id IS NOT NULL'.format( fields=dbFieldStr, models=self.modelsTableName) conn.cursor.execute(query, [jobID]) rows = conn.cursor.fetchall() return [(r[0], list(r[1:])) for r in rows] @logExceptions(_getLogger) @g_retrySQL def modelSetFields(self, modelID, fields, ignoreUnchanged = False): """ Change the values of 1 or more fields in a model. Here, 'fields' is a dict with the name/value pairs to change. The names are the public names of the fields (camelBack, not the lower_case_only form as stored in the DB). Parameters: ---------------------------------------------------------------- jobID: jobID of the job record fields: dictionary of fields to change ignoreUnchanged: The default behavior is to throw a RuntimeError if no rows are affected. This could either be because: 1) Because there was no matching modelID 2) or if the data to update matched the data in the DB exactly. Set this parameter to True if you expect case 2 and wish to supress the error. """ # Form the sequence of key=value strings that will go into the # request assignmentExpressions = ','.join( '%s=%%s' % (self._models.pubToDBNameDict[f],) for f in fields.iterkeys()) assignmentValues = fields.values() query = 'UPDATE %s SET %s, update_counter = update_counter+1 ' \ ' WHERE model_id=%%s' \ % (self.modelsTableName, assignmentExpressions) sqlParams = assignmentValues + [modelID] # Get a database connection and cursor with ConnectionFactory.get() as conn: numAffectedRows = conn.cursor.execute(query, sqlParams) self._logger.debug("Executed: numAffectedRows=%r, query=%r, sqlParams=%r", numAffectedRows, query, sqlParams) if numAffectedRows != 1 and not ignoreUnchanged: raise RuntimeError( ("Tried to change fields (%r) of model %r (conn_id=%r), but an error " "occurred. numAffectedRows=%r; query=%r; sqlParams=%r") % ( fields, modelID, self._connectionID, numAffectedRows, query, sqlParams,)) @logExceptions(_getLogger) def modelsGetParams(self, modelIDs): """ Get the params and paramsHash for a set of models. WARNING!!!: The order of the results are NOT necessarily in the same order as the order of the model IDs passed in!!! Parameters: ---------------------------------------------------------------- modelIDs: list of model IDs retval: list of result namedtuples defined in ClientJobsDAO._models.getParamsNamedTuple. Each tuple contains: (modelId, params, engParamsHash) """ assert isinstance(modelIDs, self._SEQUENCE_TYPES), ( "Wrong modelIDs type: %r") % (type(modelIDs),) assert len(modelIDs) >= 1, "modelIDs is empty" rows = self._getMatchingRowsWithRetries( self._models, {'model_id' : modelIDs}, [self._models.pubToDBNameDict[f] for f in self._models.getParamsNamedTuple._fields]) # NOTE: assertion will also fail when modelIDs contains duplicates assert len(rows) == len(modelIDs), "Didn't find modelIDs: %r" % ( (set(modelIDs) - set(r[0] for r in rows)),) # Return the params and params hashes as a namedtuple return [self._models.getParamsNamedTuple._make(r) for r in rows] @logExceptions(_getLogger) def modelsGetResultAndStatus(self, modelIDs): """ Get the results string and other status fields for a set of models. WARNING!!!: The order of the results are NOT necessarily in the same order as the order of the model IDs passed in!!! For each model, this returns a tuple containing: (modelID, results, status, updateCounter, numRecords, completionReason, completionMsg, engParamsHash Parameters: ---------------------------------------------------------------- modelIDs: list of model IDs retval: list of result tuples. Each tuple contains: (modelID, results, status, updateCounter, numRecords, completionReason, completionMsg, engParamsHash) """ assert isinstance(modelIDs, self._SEQUENCE_TYPES), ( "Wrong modelIDs type: %r") % type(modelIDs) assert len(modelIDs) >= 1, "modelIDs is empty" rows = self._getMatchingRowsWithRetries( self._models, {'model_id' : modelIDs}, [self._models.pubToDBNameDict[f] for f in self._models.getResultAndStatusNamedTuple._fields]) # NOTE: assertion will also fail when modelIDs contains duplicates assert len(rows) == len(modelIDs), "Didn't find modelIDs: %r" % ( (set(modelIDs) - set(r[0] for r in rows)),) # Return the results as a list of namedtuples return [self._models.getResultAndStatusNamedTuple._make(r) for r in rows] @logExceptions(_getLogger) def modelsGetUpdateCounters(self, jobID): """ Return info on all of the models that are in already in the models table for a given job. For each model, this returns a tuple containing: (modelID, updateCounter). Note that we don't return the results for all models, since the results string could be quite large. The information we are returning is just 2 integer fields. Parameters: ---------------------------------------------------------------- jobID: jobID to query retval: (possibly empty) list of tuples. Each tuple contains: (modelID, updateCounter) """ rows = self._getMatchingRowsWithRetries( self._models, {'job_id' : jobID}, [self._models.pubToDBNameDict[f] for f in self._models.getUpdateCountersNamedTuple._fields]) # Return the results as a list of namedtuples return [self._models.getUpdateCountersNamedTuple._make(r) for r in rows] @logExceptions(_getLogger) @g_retrySQL def modelUpdateResults(self, modelID, results=None, metricValue =None, numRecords=None): """ Update the results string, and/or num_records fields of a model. This will fail if the model does not currently belong to this client (connection_id doesn't match). Parameters: ---------------------------------------------------------------- modelID: model ID of model to modify results: new results, or None to ignore metricValue: the value of the metric being optimized, or None to ignore numRecords: new numRecords, or None to ignore """ assignmentExpressions = ['_eng_last_update_time=UTC_TIMESTAMP()', 'update_counter=update_counter+1'] assignmentValues = [] if results is not None: assignmentExpressions.append('results=%s') assignmentValues.append(results) if numRecords is not None: assignmentExpressions.append('num_records=%s') assignmentValues.append(numRecords) # NOTE1: (metricValue==metricValue) tests for Nan # NOTE2: metricValue is being passed as numpy.float64 if metricValue is not None and (metricValue==metricValue): assignmentExpressions.append('optimized_metric=%s') assignmentValues.append(float(metricValue)) query = 'UPDATE %s SET %s ' \ ' WHERE model_id=%%s and _eng_worker_conn_id=%%s' \ % (self.modelsTableName, ','.join(assignmentExpressions)) sqlParams = assignmentValues + [modelID, self._connectionID] # Get a database connection and cursor with ConnectionFactory.get() as conn: numRowsAffected = conn.cursor.execute(query, sqlParams) if numRowsAffected != 1: raise InvalidConnectionException( ("Tried to update the info of modelID=%r using connectionID=%r, but " "this model belongs to some other worker or modelID not found; " "numRowsAffected=%r") % (modelID,self._connectionID, numRowsAffected,)) def modelUpdateTimestamp(self, modelID): self.modelUpdateResults(modelID) @logExceptions(_getLogger) @g_retrySQL def modelSetCompleted(self, modelID, completionReason, completionMsg, cpuTime=0, useConnectionID=True): """ Mark a model as completed, with the given completionReason and completionMsg. This will fail if the model does not currently belong to this client (connection_id doesn't match). Parameters: ---------------------------------------------------------------- modelID: model ID of model to modify completionReason: completionReason string completionMsg: completionMsg string cpuTime: amount of CPU time spent on this model useConnectionID: True if the connection id of the calling function must be the same as the connection that created the job. Set to True for hypersearch workers, which use this mechanism for orphaned model detection. """ if completionMsg is None: completionMsg = '' query = 'UPDATE %s SET status=%%s, ' \ ' completion_reason=%%s, ' \ ' completion_msg=%%s, ' \ ' end_time=UTC_TIMESTAMP(), ' \ ' cpu_time=%%s, ' \ ' _eng_last_update_time=UTC_TIMESTAMP(), ' \ ' update_counter=update_counter+1 ' \ ' WHERE model_id=%%s' \ % (self.modelsTableName,) sqlParams = [self.STATUS_COMPLETED, completionReason, completionMsg, cpuTime, modelID] if useConnectionID: query += " AND _eng_worker_conn_id=%s" sqlParams.append(self._connectionID) with ConnectionFactory.get() as conn: numRowsAffected = conn.cursor.execute(query, sqlParams) if numRowsAffected != 1: raise InvalidConnectionException( ("Tried to set modelID=%r using connectionID=%r, but this model " "belongs to some other worker or modelID not found; " "numRowsAffected=%r") % (modelID, self._connectionID, numRowsAffected)) @logExceptions(_getLogger) def modelAdoptNextOrphan(self, jobId, maxUpdateInterval): """ Look through the models table for an orphaned model, which is a model that is not completed yet, whose _eng_last_update_time is more than maxUpdateInterval seconds ago. If one is found, change its _eng_worker_conn_id to the current worker's and return the model id. Parameters: ---------------------------------------------------------------- retval: modelId of the model we adopted, or None if none found """ @g_retrySQL def findCandidateModelWithRetries(): modelID = None with ConnectionFactory.get() as conn: # TODO: may need a table index on job_id/status for speed query = 'SELECT model_id FROM %s ' \ ' WHERE status=%%s ' \ ' AND job_id=%%s ' \ ' AND TIMESTAMPDIFF(SECOND, ' \ ' _eng_last_update_time, ' \ ' UTC_TIMESTAMP()) > %%s ' \ ' LIMIT 1 ' \ % (self.modelsTableName,) sqlParams = [self.STATUS_RUNNING, jobId, maxUpdateInterval] numRows = conn.cursor.execute(query, sqlParams) rows = conn.cursor.fetchall() assert numRows <= 1, "Unexpected numRows: %r" % numRows if numRows == 1: (modelID,) = rows[0] return modelID @g_retrySQL def adoptModelWithRetries(modelID): adopted = False with ConnectionFactory.get() as conn: query = 'UPDATE %s SET _eng_worker_conn_id=%%s, ' \ ' _eng_last_update_time=UTC_TIMESTAMP() ' \ ' WHERE model_id=%%s ' \ ' AND status=%%s' \ ' AND TIMESTAMPDIFF(SECOND, ' \ ' _eng_last_update_time, ' \ ' UTC_TIMESTAMP()) > %%s ' \ ' LIMIT 1 ' \ % (self.modelsTableName,) sqlParams = [self._connectionID, modelID, self.STATUS_RUNNING, maxUpdateInterval] numRowsAffected = conn.cursor.execute(query, sqlParams) assert numRowsAffected <= 1, 'Unexpected numRowsAffected=%r' % ( numRowsAffected,) if numRowsAffected == 1: adopted = True else: # Discern between transient failure during update and someone else # claiming this model (status, connectionID) = self._getOneMatchingRowNoRetries( self._models, conn, {'model_id':modelID}, ['status', '_eng_worker_conn_id']) adopted = (status == self.STATUS_RUNNING and connectionID == self._connectionID) return adopted adoptedModelID = None while True: modelID = findCandidateModelWithRetries() if modelID is None: break if adoptModelWithRetries(modelID): adoptedModelID = modelID break return adoptedModelID #def testClientJobsDAO(): # # WARNING: these tests assume that Nupic Scheduler is not running, and bad # # things will happen if the test is executed while the Scheduler is running # # # TODO: This test code is out of date: e.g., at the time of this writing, # # jobStartNext() advances a job's status to STATUS_RUNNING instead of # # STATUS_STARTING; etc. # # import time # import hashlib # import pprint # # # Clear out the database # cjDAO = ClientJobsDAO.get() # cjDAO.connect(deleteOldVersions=True, recreate=True) # # # # -------------------------------------------------------------------- # # Test inserting a new job that doesn't have to be unique # jobID1 = cjDAO.jobInsert(client='test', cmdLine='echo hi', # clientInfo='client info', params='job params') # print "Inserted job %d" % (jobID1) # # jobID2 = cjDAO.jobInsert(client='test', cmdLine='echo hi', # clientInfo='client info', params='job params') # print "Inserted job %d" % (jobID2) # # # # -------------------------------------------------------------------- # # Test starting up those jobs # jobID = cjDAO.jobStartNext() # print "started job %d" % (jobID) # assert (jobID == jobID1) # info = cjDAO.jobInfo(jobID) # print "jobInfo:" # pprint.pprint(info) # assert (info.status == cjDAO.STATUS_STARTING) # # jobID = cjDAO.jobStartNext() # print "started job %d" % (jobID) # assert (jobID == jobID2) # info = cjDAO.jobInfo(jobID) # print "jobInfo:" # pprint.pprint(info) # assert (info.status == cjDAO.STATUS_STARTING) # # # # -------------------------------------------------------------------- # # Test inserting a unique job # jobHash = '01234' # (success, jobID3) = cjDAO.jobInsertUnique(client='testuniq', # cmdLine='echo hi', # jobHash=jobHash, clientInfo='client info', params='job params') # print "Inserted unique job %d" % (jobID3) # assert (success) # # # This should return the same jobID # (success, jobID4) = cjDAO.jobInsertUnique(client='testuniq', # cmdLine='echo hi', # jobHash=jobHash, clientInfo='client info', params='job params') # print "tried to insert again %d" % (jobID4) # assert (not success and jobID4 == jobID3) # # # # Mark it as completed # jobID = cjDAO.jobStartNext() # assert (jobID == jobID3) # cjDAO.jobSetStatus(jobID3, cjDAO.STATUS_COMPLETED) # # # # This should return success # (success, jobID4) = cjDAO.jobInsertUnique(client='testuniq', # cmdLine='echo hi', # jobHash=jobHash, clientInfo='client info', params='job params') # print "Inserted unique job %d" % (jobID4) # assert (success) # # # # -------------------------------------------------------------------- # # Test inserting a pre-started job # jobID5 = cjDAO.jobInsert(client='test', cmdLine='echo hi', # clientInfo='client info', params='job params', # alreadyRunning=True) # print "Inserted prestarted job %d" % (jobID5) # # info = cjDAO.jobInfo(jobID5) # print "jobInfo:" # pprint.pprint(info) # assert (info.status == cjDAO.STATUS_TESTMODE) # # # # # -------------------------------------------------------------------- # # Test the jobInfo and jobSetFields calls # jobInfo = cjDAO.jobInfo(jobID2) # print "job info:" # pprint.pprint(jobInfo) # newFields = dict(maximumWorkers=43) # cjDAO.jobSetFields(jobID2, newFields) # jobInfo = cjDAO.jobInfo(jobID2) # assert(jobInfo.maximumWorkers == newFields['maximumWorkers']) # # # # -------------------------------------------------------------------- # # Test the jobGetFields call # values = cjDAO.jobGetFields(jobID2, ['maximumWorkers']) # assert (values[0] == newFields['maximumWorkers']) # # # # -------------------------------------------------------------------- # # Test the jobSetFieldIfEqual call # values = cjDAO.jobGetFields(jobID2, ['engWorkerState']) # assert (values[0] == None) # # # Change from None to test # success = cjDAO.jobSetFieldIfEqual(jobID2, 'engWorkerState', # newValue='test', curValue=None) # assert (success) # values = cjDAO.jobGetFields(jobID2, ['engWorkerState']) # assert (values[0] == 'test') # # # Change from test1 to test2 (should fail) # success = cjDAO.jobSetFieldIfEqual(jobID2, 'engWorkerState', # newValue='test2', curValue='test1') # assert (not success) # values = cjDAO.jobGetFields(jobID2, ['engWorkerState']) # assert (values[0] == 'test') # # # Change from test to test2 # success = cjDAO.jobSetFieldIfEqual(jobID2, 'engWorkerState', # newValue='test2', curValue='test') # assert (success) # values = cjDAO.jobGetFields(jobID2, ['engWorkerState']) # assert (values[0] == 'test2') # # # Change from test2 to None # success = cjDAO.jobSetFieldIfEqual(jobID2, 'engWorkerState', # newValue=None, curValue='test2') # assert (success) # values = cjDAO.jobGetFields(jobID2, ['engWorkerState']) # assert (values[0] == None) # # # # -------------------------------------------------------------------- # # Test job demands # jobID6 = cjDAO.jobInsert(client='test', cmdLine='echo hi', # clientInfo='client info', params='job params', # minimumWorkers=1, maximumWorkers=1, # alreadyRunning=False) # jobID7 = cjDAO.jobInsert(client='test', cmdLine='echo hi', # clientInfo='client info', params='job params', # minimumWorkers=4, maximumWorkers=10, # alreadyRunning=False) # cjDAO.jobSetStatus(jobID6, ClientJobsDAO.STATUS_RUNNING, # useConnectionID=False,) # cjDAO.jobSetStatus(jobID7, ClientJobsDAO.STATUS_RUNNING, # useConnectionID=False,) # jobsDemand = cjDAO.jobGetDemand() # assert (jobsDemand[0].minimumWorkers==1 and jobsDemand[0].maximumWorkers==1) # assert (jobsDemand[1].minimumWorkers==4 and jobsDemand[1].maximumWorkers==10) # assert (jobsDemand[0].engAllocateNewWorkers == True and \ # jobsDemand[0].engUntendedDeadWorkers == False) # # # Test increment field # values = cjDAO.jobGetFields(jobID7, ['numFailedWorkers']) # assert (values[0] == 0) # cjDAO.jobIncrementIntField(jobID7, 'numFailedWorkers', 1) # values = cjDAO.jobGetFields(jobID7, ['numFailedWorkers']) # assert (values[0] == 1) # # # -------------------------------------------------------------------- # # Test inserting new models # # params = "params1" # hash1 = hashlib.md5(params).digest() # (modelID1, ours) = cjDAO.modelInsertAndStart(jobID, params, hash1) # print "insert %s,%s:" % (params, hash1.encode('hex')), modelID1, ours # assert (ours) # # params = "params2" # hash2 = hashlib.md5(params).digest() # (modelID2, ours) = cjDAO.modelInsertAndStart(jobID, params, hash2) # print "insert %s,%s:" % (params, hash2.encode('hex')), modelID2, ours # assert (ours) # # params = "params3" # hash3 = hashlib.md5(params).digest() # (modelID3, ours) = cjDAO.modelInsertAndStart(jobID, params, hash3) # print "insert %s,%s:" % (params, hash3.encode('hex')), modelID3, ours # assert (ours) # # params = "params4" # hash4 = hashlib.md5(params).digest() # (modelID4, ours) = cjDAO.modelInsertAndStart(jobID, params, hash4) # print "insert %s,%s:" % (params, hash4.encode('hex')), modelID4, ours # assert (ours) # # params = "params5" # hash5 = hashlib.md5(params).digest() # (modelID5, ours) = cjDAO.modelInsertAndStart(jobID, params, hash5) # print "insert %s,%s:" % (params, hash5.encode('hex')), modelID5, ours # assert (ours) # # # # Try to insert the same model again # params = "params2" # hash = hashlib.md5(params).digest() # (modelID, ours) = cjDAO.modelInsertAndStart(jobID, params, hash) # print "insert %s,%s:" % (params, hash.encode('hex')), modelID, ours # assert (not ours and modelID == modelID2) # # # # --------------------------------------------------------------- # # Test inserting models with unique particle hashes # params = "params6" # paramsHash = hashlib.md5(params).digest() # particle = "particle6" # particleHash = hashlib.md5(particle).digest() # (modelID6, ours) = cjDAO.modelInsertAndStart(jobID, params, paramsHash, # particleHash) # print "insert %s,%s,%s:" % (params, paramsHash.encode('hex'), # particleHash.encode('hex')), modelID6, ours # assert (ours) # # # Should fail if we insert with the same params hash # params = "params6" # paramsHash = hashlib.md5(params).digest() # particle = "particleUnique" # particleHash = hashlib.md5(particle).digest() # (modelID, ours) = cjDAO.modelInsertAndStart(jobID, params, paramsHash, # particleHash) # print "insert %s,%s,%s:" % (params, paramsHash.encode('hex'), # particleHash.encode('hex')), modelID6, ours # assert (not ours and modelID == modelID6) # # # Should fail if we insert with the same particle hash # params = "paramsUnique" # paramsHash = hashlib.md5(params).digest() # particle = "particle6" # particleHash = hashlib.md5(particle).digest() # (modelID, ours) = cjDAO.modelInsertAndStart(jobID, params, paramsHash, # particleHash) # print "insert %s,%s,%s:" % (params, paramsHash.encode('hex'), # particleHash.encode('hex')), modelID6, ours # assert (not ours and modelID == modelID6) # # # # # -------------------------------------------------------------------- # # Test getting params for a set of models # paramsAndHash = cjDAO.modelsGetParams([modelID1, modelID2]) # print "modelID, params, paramsHash of %s:" % ([modelID1, modelID2]) # for (modelID, params, hash) in paramsAndHash: # print " ", modelID, params, hash.encode('hex') # if modelID == modelID1: # assert (params == "params1" and hash == hash1) # elif modelID == modelID2: # assert (params == "params2" and hash == hash2) # else: # assert (false) # # # # Set some to notstarted # #cjDAO.modelUpdateStatus(modelID2, status=cjDAO.STATUS_NOTSTARTED) # #cjDAO.modelUpdateStatus(modelID3, status=cjDAO.STATUS_NOTSTARTED) # # # # -------------------------------------------------------------------- # # Test Update model info # cjDAO.modelUpdateResults(modelID2, results="hi there") # cjDAO.modelUpdateResults(modelID3, numRecords=100) # cjDAO.modelUpdateResults(modelID3, numRecords=110) # cjDAO.modelUpdateResults(modelID4, results="bye", numRecords=42) # cjDAO.modelUpdateResults(modelID5, results="hello", numRecords=4) # # # # Test setCompleted # cjDAO.modelSetCompleted(modelID5, completionReason=cjDAO.CMPL_REASON_EOF, # completionMsg="completion message") # # # -------------------------------------------------------------------------- # # Test the GetResultsAndStatus call # results = cjDAO.modelsGetResultAndStatus([modelID1, modelID2, modelID3, # modelID4, modelID5]) # assert (len(results) == 5) # for (modelID, results, status, updateCounter, numRecords, # completionReason, completionMsg, engParamsHash, # engMatured) in results: # if modelID == modelID1: # assert (status == cjDAO.STATUS_RUNNING) # assert (updateCounter == 0) # elif modelID == modelID2: # assert (results == 'hi there') # assert (updateCounter == 1) # elif modelID == modelID3: # assert (numRecords == 110) # assert (updateCounter == 2) # elif modelID == modelID4: # assert (updateCounter == 1) # assert (results == 'bye') # assert (numRecords == 42) # elif modelID == modelID5: # assert (updateCounter == 2) # assert (results == 'hello') # assert (numRecords == 4) # assert (status == cjDAO.STATUS_COMPLETED) # assert (completionReason == cjDAO.CMPL_REASON_EOF) # assert (completionMsg == "completion message") # else: # assert (False) # # # -------------------------------------------------------------------------- # # Test the ModelsInfo call # mInfos = cjDAO.modelsInfo([modelID1, modelID2, modelID3, # modelID4, modelID5]) # assert (len(results) == 5) # for info in mInfos: # modelID = info.modelId # if modelID == modelID1: # assert (info.status == cjDAO.STATUS_RUNNING) # assert (info.updateCounter == 0) # elif modelID == modelID2: # assert (info.results == 'hi there') # assert (info.updateCounter == 1) # elif modelID == modelID3: # assert (info.numRecords == 110) # assert (info.updateCounter == 2) # elif modelID == modelID4: # assert (info.updateCounter == 1) # assert (info.results == 'bye') # assert (info.numRecords == 42) # elif modelID == modelID5: # assert (info.updateCounter == 2) # assert (info.results == 'hello') # assert (info.numRecords == 4) # assert (info.status == cjDAO.STATUS_COMPLETED) # assert (info.completionReason == cjDAO.CMPL_REASON_EOF) # assert (info.completionMsg == "completion message") # else: # assert (False) # # # # Test the GetUpdateCounters call # results = cjDAO.modelsGetUpdateCounters(jobID) # print " all models update counters:", results # expResults = set(((modelID1, 0), (modelID2, 1), (modelID3, 2), # (modelID4, 1), (modelID5, 2), (modelID6, 0))) # diff = expResults.symmetric_difference(results) # assert (len(diff) == 0) # # # # ------------------------------------------------------------------- # # Test the model orphan logic # for modelID in [modelID1, modelID2, modelID3, modelID4, modelID5, modelID6]: # cjDAO.modelUpdateResults(modelID, results="hi there") # orphanedModel = cjDAO.modelAdoptNextOrphan(jobID, maxUpdateInterval=10.0) # if orphanedModel is not None: # print "Unexpected orphan: ", orphanedModel # assert (orphanedModel is None) # print "Waiting 2 seconds for model to expire..." # time.sleep(2) # orphanedModel = cjDAO.modelAdoptNextOrphan(jobID, maxUpdateInterval=1.0) # assert (orphanedModel is not None) # print "Adopted model", orphanedModel # # print "\nAll tests pass." helpString = \ """%prog [options] This script runs the ClientJobsDAO as a command line tool, for executing unit tests or for obtaining specific information about the ClientJobsDAO required for code written in languages other than python. """ if __name__ == "__main__": """ Launch the ClientJobsDAO from the command line. This can be done to obtain specific information about the ClientJobsDAO when languages other than python (i.e. Java) are used. """ # Parse command line options parser = OptionParser(helpString) parser.add_option("--getDBName", action="store_true", default=False, help="Print the name of the database that will be used to stdout " " [default: %default]") (options, args) = parser.parse_args(sys.argv[1:]) if len(args) > 0: parser.error("Didn't expect any arguments.") # Print DB name? if options.getDBName: cjDAO = ClientJobsDAO() print cjDAO.dbName
agpl-3.0
jgoclawski/django
tests/staticfiles_tests/test_views.py
279
1312
from __future__ import unicode_literals import posixpath from django.conf import settings from django.test import override_settings from .cases import StaticFilesTestCase, TestDefaults @override_settings(ROOT_URLCONF='staticfiles_tests.urls.default') class TestServeStatic(StaticFilesTestCase): """ Test static asset serving view. """ def _response(self, filepath): return self.client.get( posixpath.join(settings.STATIC_URL, filepath)) def assertFileContains(self, filepath, text): self.assertContains(self._response(filepath), text) def assertFileNotFound(self, filepath): self.assertEqual(self._response(filepath).status_code, 404) @override_settings(DEBUG=False) class TestServeDisabled(TestServeStatic): """ Test serving static files disabled when DEBUG is False. """ def test_disabled_serving(self): self.assertFileNotFound('test.txt') class TestServeStaticWithDefaultURL(TestServeStatic, TestDefaults): """ Test static asset serving view with manually configured URLconf. """ @override_settings(ROOT_URLCONF='staticfiles_tests.urls.helper') class TestServeStaticWithURLHelper(TestServeStatic, TestDefaults): """ Test static asset serving view with staticfiles_urlpatterns helper. """
bsd-3-clause
CookiesandCake/namebench
nb_third_party/dns/ipv4.py
250
1365
# Copyright (C) 2003-2007, 2009, 2010 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """IPv4 helper functions.""" import socket import sys if sys.hexversion < 0x02030000 or sys.platform == 'win32': # # Some versions of Python 2.2 have an inet_aton which rejects # the valid IP address '255.255.255.255'. It appears this # problem is still present on the Win32 platform even in 2.3. # We'll work around the problem. # def inet_aton(text): if text == '255.255.255.255': return '\xff' * 4 else: return socket.inet_aton(text) else: inet_aton = socket.inet_aton inet_ntoa = socket.inet_ntoa
apache-2.0