repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
mancoast/CPythonPyc_test
cpython/220_test_grammar.py
4
16767
# Python test set -- part 1, grammar. # This just tests whether the parser accepts them all. from test_support import * import sys print '1. Parser' print '1.1 Tokens' print '1.1.1 Backslashes' # Backslash means line continuation: x = 1 \ + 1 if x != 2: raise TestFailed, 'backslash for line continuation' # Backslash does not means continuation in comments :\ x = 0 if x != 0: raise TestFailed, 'backslash ending comment' print '1.1.2 Numeric literals' print '1.1.2.1 Plain integers' if 0xff != 255: raise TestFailed, 'hex int' if 0377 != 255: raise TestFailed, 'octal int' if 2147483647 != 017777777777: raise TestFailed, 'large positive int' try: from sys import maxint except ImportError: maxint = 2147483647 if maxint == 2147483647: if -2147483647-1 != 020000000000: raise TestFailed, 'max negative int' # XXX -2147483648 if 037777777777 != -1: raise TestFailed, 'oct -1' if 0xffffffff != -1: raise TestFailed, 'hex -1' for s in '2147483648', '040000000000', '0x100000000': try: x = eval(s) except OverflowError: print "OverflowError on huge integer literal " + `s` elif eval('maxint == 9223372036854775807'): if eval('-9223372036854775807-1 != 01000000000000000000000'): raise TestFailed, 'max negative int' if eval('01777777777777777777777') != -1: raise TestFailed, 'oct -1' if eval('0xffffffffffffffff') != -1: raise TestFailed, 'hex -1' for s in '9223372036854775808', '02000000000000000000000', \ '0x10000000000000000': try: x = eval(s) except OverflowError: print "OverflowError on huge integer literal " + `s` else: print 'Weird maxint value', maxint print '1.1.2.2 Long integers' x = 0L x = 0l x = 0xffffffffffffffffL x = 0xffffffffffffffffl x = 077777777777777777L x = 077777777777777777l x = 123456789012345678901234567890L x = 123456789012345678901234567890l print '1.1.2.3 Floating point' x = 3.14 x = 314. x = 0.314 # XXX x = 000.314 x = .314 x = 3e14 x = 3E14 x = 3e-14 x = 3e+14 x = 3.e14 x = .3e14 x = 3.1e4 print '1.1.3 String literals' x = ''; y = ""; verify(len(x) == 0 and x == y) x = '\''; y = "'"; verify(len(x) == 1 and x == y and ord(x) == 39) x = '"'; y = "\""; verify(len(x) == 1 and x == y and ord(x) == 34) x = "doesn't \"shrink\" does it" y = 'doesn\'t "shrink" does it' verify(len(x) == 24 and x == y) x = "does \"shrink\" doesn't it" y = 'does "shrink" doesn\'t it' verify(len(x) == 24 and x == y) x = """ The "quick" brown fox jumps over the 'lazy' dog. """ y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' verify(x == y) y = ''' The "quick" brown fox jumps over the 'lazy' dog. '''; verify(x == y) y = "\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the 'lazy' dog.\n\ "; verify(x == y) y = '\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the \'lazy\' dog.\n\ '; verify(x == y) print '1.2 Grammar' print 'single_input' # NEWLINE | simple_stmt | compound_stmt NEWLINE # XXX can't test in a script -- this rule is only used when interactive print 'file_input' # (NEWLINE | stmt)* ENDMARKER # Being tested as this very moment this very module print 'expr_input' # testlist NEWLINE # XXX Hard to test -- used only in calls to input() print 'eval_input' # testlist ENDMARKER x = eval('1, 0 or 1') print 'funcdef' ### 'def' NAME parameters ':' suite ### parameters: '(' [varargslist] ')' ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME] ### | ('**'|'*' '*') NAME) ### | fpdef ['=' test] (',' fpdef ['=' test])* [','] ### fpdef: NAME | '(' fplist ')' ### fplist: fpdef (',' fpdef)* [','] ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test) ### argument: [test '='] test # Really [keyword '='] test def f1(): pass f1() f1(*()) f1(*(), **{}) def f2(one_argument): pass def f3(two, arguments): pass def f4(two, (compound, (argument, list))): pass def f5((compound, first), two): pass verify(f2.func_code.co_varnames == ('one_argument',)) verify(f3.func_code.co_varnames == ('two', 'arguments')) if sys.platform.startswith('java'): verify(f4.func_code.co_varnames == ('two', '(compound, (argument, list))', 'compound', 'argument', 'list',)) verify(f5.func_code.co_varnames == ('(compound, first)', 'two', 'compound', 'first')) else: verify(f4.func_code.co_varnames == ('two', '.2', 'compound', 'argument', 'list')) verify(f5.func_code.co_varnames == ('.0', 'two', 'compound', 'first')) def a1(one_arg,): pass def a2(two, args,): pass def v0(*rest): pass def v1(a, *rest): pass def v2(a, b, *rest): pass def v3(a, (b, c), *rest): return a, b, c, rest if sys.platform.startswith('java'): verify(v3.func_code.co_varnames == ('a', '(b, c)', 'rest', 'b', 'c')) else: verify(v3.func_code.co_varnames == ('a', '.2', 'rest', 'b', 'c')) verify(v3(1, (2, 3), 4) == (1, 2, 3, (4,))) def d01(a=1): pass d01() d01(1) d01(*(1,)) d01(**{'a':2}) def d11(a, b=1): pass d11(1) d11(1, 2) d11(1, **{'b':2}) def d21(a, b, c=1): pass d21(1, 2) d21(1, 2, 3) d21(*(1, 2, 3)) d21(1, *(2, 3)) d21(1, 2, *(3,)) d21(1, 2, **{'c':3}) def d02(a=1, b=2): pass d02() d02(1) d02(1, 2) d02(*(1, 2)) d02(1, *(2,)) d02(1, **{'b':2}) d02(**{'a': 1, 'b': 2}) def d12(a, b=1, c=2): pass d12(1) d12(1, 2) d12(1, 2, 3) def d22(a, b, c=1, d=2): pass d22(1, 2) d22(1, 2, 3) d22(1, 2, 3, 4) def d01v(a=1, *rest): pass d01v() d01v(1) d01v(1, 2) d01v(*(1, 2, 3, 4)) d01v(*(1,)) d01v(**{'a':2}) def d11v(a, b=1, *rest): pass d11v(1) d11v(1, 2) d11v(1, 2, 3) def d21v(a, b, c=1, *rest): pass d21v(1, 2) d21v(1, 2, 3) d21v(1, 2, 3, 4) d21v(*(1, 2, 3, 4)) d21v(1, 2, **{'c': 3}) def d02v(a=1, b=2, *rest): pass d02v() d02v(1) d02v(1, 2) d02v(1, 2, 3) d02v(1, *(2, 3, 4)) d02v(**{'a': 1, 'b': 2}) def d12v(a, b=1, c=2, *rest): pass d12v(1) d12v(1, 2) d12v(1, 2, 3) d12v(1, 2, 3, 4) d12v(*(1, 2, 3, 4)) d12v(1, 2, *(3, 4, 5)) d12v(1, *(2,), **{'c': 3}) def d22v(a, b, c=1, d=2, *rest): pass d22v(1, 2) d22v(1, 2, 3) d22v(1, 2, 3, 4) d22v(1, 2, 3, 4, 5) d22v(*(1, 2, 3, 4)) d22v(1, 2, *(3, 4, 5)) d22v(1, *(2, 3), **{'d': 4}) ### lambdef: 'lambda' [varargslist] ':' test print 'lambdef' l1 = lambda : 0 verify(l1() == 0) l2 = lambda : a[d] # XXX just testing the expression l3 = lambda : [2 < x for x in [-1, 3, 0L]] verify(l3() == [0, 1, 0]) l4 = lambda x = lambda y = lambda z=1 : z : y() : x() verify(l4() == 1) l5 = lambda x, y, z=2: x + y + z verify(l5(1, 2) == 5) verify(l5(1, 2, 3) == 6) check_syntax("lambda x: x = 2") ### stmt: simple_stmt | compound_stmt # Tested below ### simple_stmt: small_stmt (';' small_stmt)* [';'] print 'simple_stmt' x = 1; pass; del x ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt # Tested below print 'expr_stmt' # (exprlist '=')* exprlist 1 1, 2, 3 x = 1 x = 1, 2, 3 x = y = z = 1, 2, 3 x, y, z = 1, 2, 3 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) # NB these variables are deleted below check_syntax("x + 1 = 1") check_syntax("a + 1 = b + 2") print 'print_stmt' # 'print' (test ',')* [test] print 1, 2, 3 print 1, 2, 3, print print 0 or 1, 0 or 1, print 0 or 1 print 'extended print_stmt' # 'print' '>>' test ',' import sys print >> sys.stdout, 1, 2, 3 print >> sys.stdout, 1, 2, 3, print >> sys.stdout print >> sys.stdout, 0 or 1, 0 or 1, print >> sys.stdout, 0 or 1 # test printing to an instance class Gulp: def write(self, msg): pass gulp = Gulp() print >> gulp, 1, 2, 3 print >> gulp, 1, 2, 3, print >> gulp print >> gulp, 0 or 1, 0 or 1, print >> gulp, 0 or 1 # test print >> None def driver(): oldstdout = sys.stdout sys.stdout = Gulp() try: tellme(Gulp()) tellme() finally: sys.stdout = oldstdout # we should see this once def tellme(file=sys.stdout): print >> file, 'hello world' driver() # we should not see this at all def tellme(file=None): print >> file, 'goodbye universe' driver() # syntax errors check_syntax('print ,') check_syntax('print >> x,') print 'del_stmt' # 'del' exprlist del abc del x, y, (z, xyz) print 'pass_stmt' # 'pass' pass print 'flow_stmt' # break_stmt | continue_stmt | return_stmt | raise_stmt # Tested below print 'break_stmt' # 'break' while 1: break print 'continue_stmt' # 'continue' i = 1 while i: i = 0; continue msg = "" while not msg: msg = "continue + try/except ok" try: continue msg = "continue failed to continue inside try" except: msg = "continue inside try called except block" print msg msg = "" while not msg: msg = "finally block not called" try: continue finally: msg = "continue + try/finally ok" print msg # This test warrants an explanation. It is a test specifically for SF bugs # #463359 and #462937. The bug is that a 'break' statement executed or # exception raised inside a try/except inside a loop, *after* a continue # statement has been executed in that loop, will cause the wrong number of # arguments to be popped off the stack and the instruction pointer reset to # a very small number (usually 0.) Because of this, the following test # *must* written as a function, and the tracking vars *must* be function # arguments with default values. Otherwise, the test will loop and loop. print "testing continue and break in try/except in loop" def test_break_continue_loop(extra_burning_oil = 1, count=0): big_hippo = 2 while big_hippo: count += 1 try: if extra_burning_oil and big_hippo == 1: extra_burning_oil -= 1 break big_hippo -= 1 continue except: raise if count > 2 or big_hippo <> 1: print "continue then break in try/except in loop broken!" test_break_continue_loop() print 'return_stmt' # 'return' [testlist] def g1(): return def g2(): return 1 g1() x = g2() print 'raise_stmt' # 'raise' test [',' test] try: raise RuntimeError, 'just testing' except RuntimeError: pass try: raise KeyboardInterrupt except KeyboardInterrupt: pass print 'import_stmt' # 'import' NAME (',' NAME)* | 'from' NAME 'import' ('*' | NAME (',' NAME)*) import sys import time, sys from time import time from sys import * from sys import path, argv print 'global_stmt' # 'global' NAME (',' NAME)* def f(): global a global a, b global one, two, three, four, five, six, seven, eight, nine, ten print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]] def f(): z = None del z exec 'z=1+1\n' if z != 2: raise TestFailed, 'exec \'z=1+1\'\\n' del z exec 'z=1+1' if z != 2: raise TestFailed, 'exec \'z=1+1\'' z = None del z import types if hasattr(types, "UnicodeType"): exec r"""if 1: exec u'z=1+1\n' if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n' del z exec u'z=1+1' if z != 2: raise TestFailed, 'exec u\'z=1+1\'' """ f() g = {} exec 'z = 1' in g if g.has_key('__builtins__'): del g['__builtins__'] if g != {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g' g = {} l = {} import warnings warnings.filterwarnings("ignore", "global statement", module="<string>") exec 'global a; a = 1; b = 2' in g, l if g.has_key('__builtins__'): del g['__builtins__'] if l.has_key('__builtins__'): del l['__builtins__'] if (g, l) != ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g (%s), l (%s)' %(g,l) print "assert_stmt" # assert_stmt: 'assert' test [',' test] assert 1 assert 1, 1 assert lambda x:x assert 1, lambda x:x+1 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef # Tested below print 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] if 1: pass if 1: pass else: pass if 0: pass elif 0: pass if 0: pass elif 0: pass elif 0: pass elif 0: pass else: pass print 'while_stmt' # 'while' test ':' suite ['else' ':' suite] while 0: pass while 0: pass else: pass print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] for i in 1, 2, 3: pass for i, j, k in (): pass else: pass class Squares: def __init__(self, max): self.max = max self.sofar = [] def __len__(self): return len(self.sofar) def __getitem__(self, i): if not 0 <= i < self.max: raise IndexError n = len(self.sofar) while n <= i: self.sofar.append(n*n) n = n+1 return self.sofar[i] n = 0 for x in Squares(10): n = n+x if n != 285: raise TestFailed, 'for over growing sequence' print 'try_stmt' ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] ### | 'try' ':' suite 'finally' ':' suite ### except_clause: 'except' [expr [',' expr]] try: 1/0 except ZeroDivisionError: pass else: pass try: 1/0 except EOFError: pass except TypeError, msg: pass except RuntimeError, msg: pass except: pass else: pass try: 1/0 except (EOFError, TypeError, ZeroDivisionError): pass try: 1/0 except (EOFError, TypeError, ZeroDivisionError), msg: pass try: pass finally: pass print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT if 1: pass if 1: pass if 1: # # # pass pass # pass # print 'test' ### and_test ('or' and_test)* ### and_test: not_test ('and' not_test)* ### not_test: 'not' not_test | comparison if not 1: pass if 1 and 1: pass if 1 or 1: pass if not not not 1: pass if not 1 and 1 and 1: pass if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass print 'comparison' ### comparison: expr (comp_op expr)* ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' if 1: pass x = (1 == 1) if 1 == 1: pass if 1 != 1: pass if 1 <> 1: pass if 1 < 1: pass if 1 > 1: pass if 1 <= 1: pass if 1 >= 1: pass if 1 is 1: pass if 1 is not 1: pass if 1 in (): pass if 1 not in (): pass if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass print 'binary mask ops' x = 1 & 1 x = 1 ^ 1 x = 1 | 1 print 'shift ops' x = 1 << 1 x = 1 >> 1 x = 1 << 1 >> 1 print 'additive ops' x = 1 x = 1 + 1 x = 1 - 1 - 1 x = 1 - 1 + 1 - 1 + 1 print 'multiplicative ops' x = 1 * 1 x = 1 / 1 x = 1 % 1 x = 1 / 1 * 1 % 1 print 'unary ops' x = +1 x = -1 x = ~1 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 x = -1*1/1 + 1*1 - ---1*1 print 'selectors' ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME ### subscript: expr | [expr] ':' [expr] f1() f2(1) f2(1,) f3(1, 2) f3(1, 2,) f4(1, (2, (3, 4))) v0() v0(1) v0(1,) v0(1,2) v0(1,2,3,4,5,6,7,8,9,0) v1(1) v1(1,) v1(1,2) v1(1,2,3) v1(1,2,3,4,5,6,7,8,9,0) v2(1,2) v2(1,2,3) v2(1,2,3,4) v2(1,2,3,4,5,6,7,8,9,0) v3(1,(2,3)) v3(1,(2,3),4) v3(1,(2,3),4,5,6,7,8,9,0) print import sys, time c = sys.path[0] x = time.time() x = sys.modules['time'].time() a = '01234' c = a[0] c = a[-1] s = a[0:5] s = a[:5] s = a[0:] s = a[:] s = a[-5:] s = a[:-1] s = a[-4:-3] print 'atoms' ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING ### dictmaker: test ':' test (',' test ':' test)* [','] x = (1) x = (1 or 2 or 3) x = (1 or 2 or 3, 2, 3) x = [] x = [1] x = [1 or 2 or 3] x = [1 or 2 or 3, 2, 3] x = [] x = {} x = {'one': 1} x = {'one': 1,} x = {'one' or 'two': 1 or 2} x = {'one': 1, 'two': 2} x = {'one': 1, 'two': 2,} x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} x = `x` x = `1 or 2 or 3` x = x x = 'x' x = 123 ### exprlist: expr (',' expr)* [','] ### testlist: test (',' test)* [','] # These have been exercised enough above print 'classdef' # 'class' NAME ['(' testlist ')'] ':' suite class B: pass class C1(B): pass class C2(B): pass class D(C1, C2, B): pass class C: def meth1(self): pass def meth2(self, arg): pass def meth3(self, a1, a2): pass # list comprehension tests nums = [1, 2, 3, 4, 5] strs = ["Apple", "Banana", "Coconut"] spcs = [" Apple", " Banana ", "Coco nut "] print [s.strip() for s in spcs] print [3 * x for x in nums] print [x for x in nums if x > 2] print [(i, s) for i in nums for s in strs] print [(i, s) for i in nums for s in [f for f in strs if "n" in f]] def test_in_func(l): return [None < x < 3 for x in l if x > 2] print test_in_func(nums) def test_nested_front(): print [[y for y in [x, x + 1]] for x in [1,3,5]] test_nested_front() check_syntax("[i, s for i in nums for s in strs]") check_syntax("[x if y]") suppliers = [ (1, "Boeing"), (2, "Ford"), (3, "Macdonalds") ] parts = [ (10, "Airliner"), (20, "Engine"), (30, "Cheeseburger") ] suppart = [ (1, 10), (1, 20), (2, 20), (3, 30) ] print [ (sname, pname) for (sno, sname) in suppliers for (pno, pname) in parts for (sp_sno, sp_pno) in suppart if sno == sp_sno and pno == sp_pno ]
gpl-3.0
kalahbrown/HueBigSQL
desktop/core/ext-py/kazoo-2.0/kazoo/protocol/states.py
50
6304
"""Kazoo State and Event objects""" from collections import namedtuple class KazooState(object): """High level connection state values States inspired by Netflix Curator. .. attribute:: SUSPENDED The connection has been lost but may be recovered. We should operate in a "safe mode" until then. When the connection is resumed, it may be discovered that the session expired. A client should not assume that locks are valid during this time. .. attribute:: CONNECTED The connection is alive and well. .. attribute:: LOST The connection has been confirmed dead. Any ephemeral nodes will need to be recreated upon re-establishing a connection. If locks were acquired or recipes using ephemeral nodes are in use, they can be considered lost as well. """ SUSPENDED = "SUSPENDED" CONNECTED = "CONNECTED" LOST = "LOST" class KeeperState(object): """Zookeeper State Represents the Zookeeper state. Watch functions will receive a :class:`KeeperState` attribute as their state argument. .. attribute:: AUTH_FAILED Authentication has failed, this is an unrecoverable error. .. attribute:: CONNECTED Zookeeper is connected. .. attribute:: CONNECTED_RO Zookeeper is connected in read-only state. .. attribute:: CONNECTING Zookeeper is currently attempting to establish a connection. .. attribute:: EXPIRED_SESSION The prior session was invalid, all prior ephemeral nodes are gone. """ AUTH_FAILED = 'AUTH_FAILED' CONNECTED = 'CONNECTED' CONNECTED_RO = 'CONNECTED_RO' CONNECTING = 'CONNECTING' CLOSED = 'CLOSED' EXPIRED_SESSION = 'EXPIRED_SESSION' class EventType(object): """Zookeeper Event Represents a Zookeeper event. Events trigger watch functions which will receive a :class:`EventType` attribute as their event argument. .. attribute:: CREATED A node has been created. .. attribute:: DELETED A node has been deleted. .. attribute:: CHANGED The data for a node has changed. .. attribute:: CHILD The children under a node have changed (a child was added or removed). This event does not indicate the data for a child node has changed, which must have its own watch established. """ CREATED = 'CREATED' DELETED = 'DELETED' CHANGED = 'CHANGED' CHILD = 'CHILD' EVENT_TYPE_MAP = { 1: EventType.CREATED, 2: EventType.DELETED, 3: EventType.CHANGED, 4: EventType.CHILD } class WatchedEvent(namedtuple('WatchedEvent', ('type', 'state', 'path'))): """A change on ZooKeeper that a Watcher is able to respond to. The :class:`WatchedEvent` includes exactly what happened, the current state of ZooKeeper, and the path of the node that was involved in the event. An instance of :class:`WatchedEvent` will be passed to registered watch functions. .. attribute:: type A :class:`EventType` attribute indicating the event type. .. attribute:: state A :class:`KeeperState` attribute indicating the Zookeeper state. .. attribute:: path The path of the node for the watch event. """ class Callback(namedtuple('Callback', ('type', 'func', 'args'))): """A callback that is handed to a handler for dispatch :param type: Type of the callback, currently is only 'watch' :param func: Callback function :param args: Argument list for the callback function """ class ZnodeStat(namedtuple('ZnodeStat', 'czxid mzxid ctime mtime version' ' cversion aversion ephemeralOwner dataLength' ' numChildren pzxid')): """A ZnodeStat structure with convenience properties When getting the value of a node from Zookeeper, the properties for the node known as a "Stat structure" will be retrieved. The :class:`ZnodeStat` object provides access to the standard Stat properties and additional properties that are more readable and use Python time semantics (seconds since epoch instead of ms). .. note:: The original Zookeeper Stat name is in parens next to the name when it differs from the convenience attribute. These are **not functions**, just attributes. .. attribute:: creation_transaction_id (czxid) The transaction id of the change that caused this znode to be created. .. attribute:: last_modified_transaction_id (mzxid) The transaction id of the change that last modified this znode. .. attribute:: created (ctime) The time in seconds from epoch when this node was created. (ctime is in milliseconds) .. attribute:: last_modified (mtime) The time in seconds from epoch when this znode was last modified. (mtime is in milliseconds) .. attribute:: version The number of changes to the data of this znode. .. attribute:: acl_version (aversion) The number of changes to the ACL of this znode. .. attribute:: owner_session_id (ephemeralOwner) The session id of the owner of this znode if the znode is an ephemeral node. If it is not an ephemeral node, it will be `None`. (ephemeralOwner will be 0 if it is not ephemeral) .. attribute:: data_length (dataLength) The length of the data field of this znode. .. attribute:: children_count (numChildren) The number of children of this znode. """ @property def acl_version(self): return self.aversion @property def children_version(self): return self.cversion @property def created(self): return self.ctime / 1000.0 @property def last_modified(self): return self.mtime / 1000.0 @property def owner_session_id(self): return self.ephemeralOwner or None @property def creation_transaction_id(self): return self.czxid @property def last_modified_transaction_id(self): return self.mzxid @property def data_length(self): return self.dataLength @property def children_count(self): return self.numChildren
apache-2.0
leorochael/odoo
addons/auth_oauth/res_config.py
23
3436
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## from openerp.osv import osv, fields import logging _logger = logging.getLogger(__name__) class base_config_settings(osv.TransientModel): _inherit = 'base.config.settings' _columns = { 'auth_oauth_google_enabled' : fields.boolean('Allow users to sign in with Google'), 'auth_oauth_google_client_id' : fields.char('Client ID'), 'auth_oauth_facebook_enabled' : fields.boolean('Allow users to sign in with Facebook'), 'auth_oauth_facebook_client_id' : fields.char('Client ID'), } def default_get(self, cr, uid, fields, context=None): res = super(base_config_settings, self).default_get(cr, uid, fields, context=context) res.update(self.get_oauth_providers(cr, uid, fields, context=context)) return res def get_oauth_providers(self, cr, uid, fields, context=None): google_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'auth_oauth', 'provider_google')[1] facebook_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'auth_oauth', 'provider_facebook')[1] rg = self.pool.get('auth.oauth.provider').read(cr, uid, [google_id], ['enabled','client_id'], context=context) rf = self.pool.get('auth.oauth.provider').read(cr, uid, [facebook_id], ['enabled','client_id'], context=context) return { 'auth_oauth_google_enabled': rg[0]['enabled'] if rg else False, 'auth_oauth_google_client_id': rg[0]['client_id'] if rg else False, 'auth_oauth_facebook_enabled': rf[0]['enabled'] if rf else False, 'auth_oauth_facebook_client_id': rf[0]['client_id'] if rf else False, } def set_oauth_providers(self, cr, uid, ids, context=None): google_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'auth_oauth', 'provider_google')[1] facebook_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'auth_oauth', 'provider_facebook')[1] config = self.browse(cr, uid, ids[0], context=context) rg = { 'enabled':config.auth_oauth_google_enabled, 'client_id':config.auth_oauth_google_client_id, } rf = { 'enabled':config.auth_oauth_facebook_enabled, 'client_id':config.auth_oauth_facebook_client_id, } self.pool.get('auth.oauth.provider').write(cr, uid, [google_id], rg) self.pool.get('auth.oauth.provider').write(cr, uid, [facebook_id], rf)
agpl-3.0
rekbun/browserscope
categories/reflow/test_set.py
9
8336
#!/usr/bin/python2.5 # -*- coding: utf-8 -*- # # Copyright 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the 'License') # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reflow Test Definitions.""" __author__ = 'elsigh@google.com (Lindsey Simon)' import logging from categories import test_set_base from categories import test_set_params _CATEGORY = 'reflow' class ReflowTest(test_set_base.TestBase): TESTS_URL_PATH = '/%s/test' % _CATEGORY def __init__(self, key, name, doc): test_set_base.TestBase.__init__( self, key=key, name=name, url='%s?t=%s' % (self.TESTS_URL_PATH, key), doc=doc, min_value=0, max_value=60000) _TESTS = ( # key, name, doc ReflowTest('testDisplay', 'Display Block', '''This test takes an element and sets its style.display="none". According to the folks at Mozilla this has the effect of taking an element out of the browser's "render tree" (the in-memory representation of all of results of geometry/positioning calculations for that particular element). Setting an element to display="none" has the additional effect of removing all of an element's children from the render tree as well. Next, the test resets the element's style.display="", which sets the element's display back to its original value. Our thinking was that this operation ought to approximate the max cost of reflowing an element on a page since the browser has to recalculate all positions and sizes for every child within the element as well as any changes to the overall document.'''), ReflowTest('testVisibility', 'Visiblility None', '''Much like the display test above, this test sets an element's style.visibility="hidden" and then resets it back to its default, which is "visible". This change should be less costly than changing display from "none" to the default since the browser should not be purging the element from the render tree.'''), ReflowTest('testNonMatchingClass', 'Non Matching Class', '''This test adds a class name to an element where that class name is not present in the document's CSS object model. This tests CSS selector match time, and more specifically against selectors with classnames.'''), ReflowTest('testFourClassReflows', 'Four Reflows by Class', '''This test adds a class name to an element that will match a previously added CSS declaration added to the CSSOM. This declaration is set with four property value pairs which should in and of themselves be capable of causing a 1x reflow time. For instance, "font-size: 20px; line-height: 10px; padding-left: 10px; margin-top: 7px;". This test aims to test whether reflow operations occur in a single queue flush or if they are performed one at a time when these changes are made via a CSS classname. This test is a sort of opposite to the Four Reflows By Script.'''), ReflowTest('testFourScriptReflows', 'Four Reflows by Script', '''Like the Four Reflows By Class test, but instead this test has four lines of Javascript, each of which alters the style object with a property/value that by itself could cause a 1x reflow time.'''), ReflowTest('testTwoScriptReflows', 'Two Reflows by Script', '''Like the Four Reflows By Script test, except with only two lines of Javascript.'''), ReflowTest('testPaddingPx', 'Padding px', '''This test sets style.padding="FOOpx", aka padding on all sides of the box model.'''), ReflowTest('testPaddingLeftPx', 'Padding Left px', '''This test sets style.paddingLeft="FOOpx", aka padding on only the left side of the box.'''), ReflowTest('testFontSizeEm', 'Font Size em', '''This test changes an element's style.fontSize to an em-based value.'''), ReflowTest('testWidthPercent', 'Width %', '''This test sets an element's style.width="FOO%"'''), ReflowTest('testBackground', 'Background Color', '''This test sets an element's style.background="#FOO", aka a hexadecimal color.'''), ReflowTest('testOverflowHidden', 'Overflow Hidden', '''This test sets an element's style.overflow="hidden" and then back again, timing the cost of an element returning to the default overflow which is "visible"'''), ReflowTest('testGetOffsetHeight', 'Do Nothing / OffsetHeight', '''This test does nothing other than the request for offsetHeight after already having done so. Theoretically, this test is something like a control for our test and should have a 0 or very low time.'''), ) BASELINE_TEST_NAME = 'testDisplay' class ReflowTestSet(test_set_base.TestSet): def AdjustResults(self, results): """Re-scores the actual value against a baseline score for reflow. Sets the 1x reflow time for this test run and compares other times against that. This is to try to account for issues around selection bias, processor speed, etc... We'll preserve the original millisecond time as an expando value in case we want to do some calculations with it later. Args: results: { test_key_1: {'raw_score': raw_score_1}, test_key_2: {'raw_score': raw_score_2}, ... } Returns: { test_key_1: {'raw_score': adjusted_raw_score_1, 'expando': score_1}, test_key_2: {'raw_score': adjusted_raw_score_2, 'expando': score_2}, ... } """ if BASELINE_TEST_NAME not in results: raise NameError('No baseline score found in the test results') baseline_score = float(results[BASELINE_TEST_NAME]['raw_score']) # Turn all values into some computed percentage of the baseline score. # This resets the score in the dict, but adds an expando to preserve the # original score's milliseconds value. for result in results.values(): result['expando'] = result['raw_score'] result['raw_score'] = int(100.0 * result['raw_score'] / baseline_score) return results def GetTestScoreAndDisplayValue(self, test_key, raw_scores): """Get a normalized score (0 to 100) and a value to output to the display. Args: test_key: a key for a test_set test. raw_scores: a dict of raw_scores indexed by test keys. Returns: score, display_value # score is from 0 to 100. # display_value is the text for the cell. """ raw_score = raw_scores.get(test_key, None) if raw_score in (None, ''): return 0, '' raw_score = int(raw_score) if raw_score <= 10: score, display = 100, '0X' elif raw_score <= 35: score, display = 97, '¼X' elif raw_score <= 65: score, display = 95, '½X' elif raw_score <= 85: score, display = 93, '¾X' elif raw_score <= 110: score, display = 90, '1X' elif raw_score <= 180: score, display = 80, '2X' else: score, display = 60, '3X' return score, display def GetRowScoreAndDisplayValue(self, results): """Get the overall score for this row of results data. Args: results: { 'test_key_1': {'score': score_1, 'raw_score': raw_score_1, ...}, 'test_key_2': {'score': score_2, 'raw_score': raw_score_2, ...}, ... } Returns: score, display_value # score is from 0 to 100. # display_value is the text for the cell. """ return 90, '' TEST_SET = ReflowTestSet( category=_CATEGORY, category_name='Reflow', summary_doc='Tests of reflow time for different CSS selectors.', tests=_TESTS, # default_params=Params( # 'nested_anchors', 'num_elements=400', 'num_nest=4', # 'css_selector=#g-content *', 'num_css_rules=1000', # 'css_text=border: 1px solid #0C0; padding: 8px;'), #default_params=test_set_params.Params('acid1', 'num_elements=300'), test_page='/%s/test_acid1' % _CATEGORY )
apache-2.0
mitar/django
django/contrib/gis/db/models/manager.py
505
3578
from django.db.models.manager import Manager from django.contrib.gis.db.models.query import GeoQuerySet class GeoManager(Manager): "Overrides Manager to return Geographic QuerySets." # This manager should be used for queries on related fields # so that geometry columns on Oracle and MySQL are selected # properly. use_for_related_fields = True def get_query_set(self): return GeoQuerySet(self.model, using=self._db) def area(self, *args, **kwargs): return self.get_query_set().area(*args, **kwargs) def centroid(self, *args, **kwargs): return self.get_query_set().centroid(*args, **kwargs) def collect(self, *args, **kwargs): return self.get_query_set().collect(*args, **kwargs) def difference(self, *args, **kwargs): return self.get_query_set().difference(*args, **kwargs) def distance(self, *args, **kwargs): return self.get_query_set().distance(*args, **kwargs) def envelope(self, *args, **kwargs): return self.get_query_set().envelope(*args, **kwargs) def extent(self, *args, **kwargs): return self.get_query_set().extent(*args, **kwargs) def extent3d(self, *args, **kwargs): return self.get_query_set().extent3d(*args, **kwargs) def force_rhr(self, *args, **kwargs): return self.get_query_set().force_rhr(*args, **kwargs) def geohash(self, *args, **kwargs): return self.get_query_set().geohash(*args, **kwargs) def geojson(self, *args, **kwargs): return self.get_query_set().geojson(*args, **kwargs) def gml(self, *args, **kwargs): return self.get_query_set().gml(*args, **kwargs) def intersection(self, *args, **kwargs): return self.get_query_set().intersection(*args, **kwargs) def kml(self, *args, **kwargs): return self.get_query_set().kml(*args, **kwargs) def length(self, *args, **kwargs): return self.get_query_set().length(*args, **kwargs) def make_line(self, *args, **kwargs): return self.get_query_set().make_line(*args, **kwargs) def mem_size(self, *args, **kwargs): return self.get_query_set().mem_size(*args, **kwargs) def num_geom(self, *args, **kwargs): return self.get_query_set().num_geom(*args, **kwargs) def num_points(self, *args, **kwargs): return self.get_query_set().num_points(*args, **kwargs) def perimeter(self, *args, **kwargs): return self.get_query_set().perimeter(*args, **kwargs) def point_on_surface(self, *args, **kwargs): return self.get_query_set().point_on_surface(*args, **kwargs) def reverse_geom(self, *args, **kwargs): return self.get_query_set().reverse_geom(*args, **kwargs) def scale(self, *args, **kwargs): return self.get_query_set().scale(*args, **kwargs) def snap_to_grid(self, *args, **kwargs): return self.get_query_set().snap_to_grid(*args, **kwargs) def svg(self, *args, **kwargs): return self.get_query_set().svg(*args, **kwargs) def sym_difference(self, *args, **kwargs): return self.get_query_set().sym_difference(*args, **kwargs) def transform(self, *args, **kwargs): return self.get_query_set().transform(*args, **kwargs) def translate(self, *args, **kwargs): return self.get_query_set().translate(*args, **kwargs) def union(self, *args, **kwargs): return self.get_query_set().union(*args, **kwargs) def unionagg(self, *args, **kwargs): return self.get_query_set().unionagg(*args, **kwargs)
bsd-3-clause
js0701/chromium-crosswalk
tools/telemetry/telemetry/internal/util/webpagereplay.py
8
11593
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Start and stop Web Page Replay.""" import atexit import logging import os import re import signal import subprocess import sys import tempfile import urllib from telemetry.core import exceptions from telemetry.core import util _REPLAY_DIR = os.path.join( util.GetTelemetryThirdPartyDir(), 'webpagereplay') class ReplayError(Exception): """Catch-all exception for the module.""" pass class ReplayNotFoundError(ReplayError): def __init__(self, label, path): super(ReplayNotFoundError, self).__init__() self.args = (label, path) def __str__(self): label, path = self.args return 'Path does not exist for %s: %s' % (label, path) class ReplayNotStartedError(ReplayError): pass class ReplayServer(object): """Start and Stop Web Page Replay. Web Page Replay is a proxy that can record and "replay" web pages with simulated network characteristics -- without having to edit the pages by hand. With WPR, tests can use "real" web content, and catch performance issues that may result from introducing network delays and bandwidth throttling. Example: with ReplayServer(archive_path): self.NavigateToURL(start_url) self.WaitUntil(...) """ def __init__(self, archive_path, replay_host, http_port, https_port, dns_port, replay_options): """Initialize ReplayServer. Args: archive_path: a path to a specific WPR archive (required). replay_host: the hostname to serve traffic. http_port: an integer port on which to serve HTTP traffic. May be zero to let the OS choose an available port. https_port: an integer port on which to serve HTTPS traffic. May be zero to let the OS choose an available port. dns_port: an integer port on which to serve DNS traffic. May be zero to let the OS choose an available port. If None DNS forwarding is disabled. replay_options: an iterable of options strings to forward to replay.py. """ self.archive_path = archive_path self._replay_host = replay_host self._use_dns_server = dns_port is not None self._started_ports = {} # a dict such as {'http': 80, 'https': 443} # A temporary path for storing stdout & stderr of the webpagereplay # subprocess. self._temp_log_file_path = None replay_py = os.path.join(_REPLAY_DIR, 'replay.py') self._cmd_line = self._GetCommandLine( replay_py, self._replay_host, http_port, https_port, dns_port, replay_options, archive_path) if '--record' in replay_options: self._CheckPath('archive directory', os.path.dirname(self.archive_path)) elif not os.path.exists(self.archive_path): self._CheckPath('archive file', self.archive_path) self._CheckPath('replay script', replay_py) self.replay_process = None @staticmethod def _GetCommandLine(replay_py, host_ip, http_port, https_port, dns_port, replay_options, archive_path): """Set WPR command-line options. Can be overridden if needed.""" cmd_line = [sys.executable, replay_py] cmd_line.extend([ '--host=%s' % host_ip, '--port=%s' % http_port, '--ssl_port=%s' % https_port ]) if dns_port is not None: # Note that if --host is not '127.0.0.1', Replay will override the local # DNS nameserver settings to point to the replay-started DNS server. cmd_line.append('--dns_port=%s' % dns_port) else: cmd_line.append('--no-dns_forwarding') cmd_line.extend([ '--use_closest_match', '--log_level=warning' ]) cmd_line.extend(replay_options) cmd_line.append(archive_path) return cmd_line def _CheckPath(self, label, path): if not os.path.exists(path): raise ReplayNotFoundError(label, path) def _OpenLogFile(self): """Opens the log file for writing.""" log_dir = os.path.dirname(self._temp_log_file_path) if not os.path.exists(log_dir): os.makedirs(log_dir) return open(self._temp_log_file_path, 'w') def _LogLines(self): """Yields the log lines.""" if not os.path.isfile(self._temp_log_file_path): return with open(self._temp_log_file_path) as f: for line in f: yield line def _IsStarted(self): """Returns true if the server is up and running.""" if self.replay_process.poll() is not None: # The process terminated. return False def HasIncompleteStartedPorts(): return ('http' not in self._started_ports or 'https' not in self._started_ports or (self._use_dns_server and 'dns' not in self._started_ports)) if HasIncompleteStartedPorts(): self._started_ports = self._ParseLogFilePorts(self._LogLines()) if HasIncompleteStartedPorts(): return False try: # HTTPS may require SNI (which urllib does not speak), so only check # that HTTP responds. return 200 == self._UrlOpen('web-page-replay-generate-200').getcode() except IOError: return False @staticmethod def _ParseLogFilePorts(log_lines): """Returns the ports on which replay listens as reported in its log file. Only matches HTTP, HTTPS, and DNS. One call may return only some of the ports depending on what has been written to the log file. Example log lines: 2014-09-03 17:04:27,978 WARNING HTTP server started on 127.0.0.1:51673 2014-09-03 17:04:27,978 WARNING HTTPS server started on 127.0.0.1:35270 Returns: a dict with ports available in log_lines. For example, {} # no ports found {'http': 1234, 'https': 2345, 'dns': 3456} """ ports = {} port_re = re.compile( r'.*?(?P<protocol>HTTP|HTTPS|DNS)' r' server started on ' r'(?P<host>[^:]*):' r'(?P<port>\d+)') for line in log_lines: m = port_re.match(line.strip()) if m: protocol = m.group('protocol').lower() ports[protocol] = int(m.group('port')) return ports def StartServer(self): """Start Web Page Replay and verify that it started. Returns: (HTTP_PORT, HTTPS_PORT, DNS_PORT) # DNS_PORT is None if unused. Raises: ReplayNotStartedError: if Replay start-up fails. """ is_posix = sys.platform.startswith('linux') or sys.platform == 'darwin' logging.debug('Starting Web-Page-Replay: %s', self._cmd_line) self._CreateTempLogFilePath() with self._OpenLogFile() as log_fh: self.replay_process = subprocess.Popen( self._cmd_line, stdout=log_fh, stderr=subprocess.STDOUT, preexec_fn=(_ResetInterruptHandler if is_posix else None)) try: util.WaitFor(self._IsStarted, 30) atexit.register(self.StopServer) return ( self._started_ports['http'], self._started_ports['https'], self._started_ports.get('dns'), # None if unused ) except exceptions.TimeoutException: raise ReplayNotStartedError( 'Web Page Replay failed to start. Log output:\n%s' % ''.join(self._LogLines())) def StopServer(self): """Stop Web Page Replay.""" if self._IsStarted(): try: self._StopReplayProcess() finally: # TODO(rnephew): Upload logs to google storage. crbug.com/525787 self._CleanUpTempLogFilePath() else: logging.warning('Attempting to stop WPR server that is not running.') def _StopReplayProcess(self): if not self.replay_process: return logging.debug('Trying to stop Web-Page-Replay gracefully') try: if self._started_ports: self._UrlOpen('web-page-replay-command-exit').close() except IOError: # IOError is possible because the server might exit without response. pass try: util.WaitFor(lambda: self.replay_process.poll() is not None, 10) except exceptions.TimeoutException: try: # Use a SIGINT so that it can do graceful cleanup. self.replay_process.send_signal(signal.SIGINT) except: # pylint: disable=bare-except # On Windows, we are left with no other option than terminate(). is_primary_nameserver_changed_by_replay = ( self._use_dns_server and self._replay_host == '127.0.0.1') if is_primary_nameserver_changed_by_replay: # Replay changes the DNS nameserver configuration so that DNS # requests are resolved by replay's own DNS server. It resolves # all DNS requests to it own IP address to it can server the # HTTP and HTTPS requests. # If the replay host is not '127.0.0.1', then replay skips the # nameserver change because it assumes a different mechanism # will be used to route DNS requests to replay's DNS server. logging.warning( 'Unable to stop Web-Page-Replay gracefully.\n' 'Replay changed the DNS nameserver configuration to make replay ' 'the primary nameserver. That might not be restored!') try: self.replay_process.terminate() except: # pylint: disable=bare-except pass self.replay_process.wait() def _CreateTempLogFilePath(self): assert self._temp_log_file_path is None handle, self._temp_log_file_path = tempfile.mkstemp() os.close(handle) def _CleanUpTempLogFilePath(self): assert self._temp_log_file_path if logging.getLogger('').isEnabledFor(logging.INFO): with open(self._temp_log_file_path, 'r') as f: wpr_log_content = '\n'.join([ '************************** WPR LOG *****************************', f.read(), '************************** END OF WPR LOG **********************']) logging.debug(wpr_log_content) os.remove(self._temp_log_file_path) self._temp_log_file_path = None def __enter__(self): """Add support for with-statement.""" self.StartServer() return self def __exit__(self, unused_exc_type, unused_exc_val, unused_exc_tb): """Add support for with-statement.""" self.StopServer() def _UrlOpen(self, url_path, protocol='http'): """Open a Replay URL. For matching requests in the archive, Replay relies on the "Host:" header. For Replay command URLs, the "Host:" header is not needed. Args: url_path: WPR server request path. protocol: 'http' or 'https' Returns: a file-like object from urllib.urlopen """ url = '%s://%s:%s/%s' % ( protocol, self._replay_host, self._started_ports[protocol], url_path) return urllib.urlopen(url, proxies={}) def _ResetInterruptHandler(): """Reset the interrupt handler back to the default. The replay process is stopped gracefully by making an HTTP request ('web-page-replay-command-exit'). The graceful exit is important for restoring the DNS configuration. If the HTTP request fails, the fallback is to send SIGINT to the process. On posix system, running this function before starting replay fixes a bug that shows up when Telemetry is run as a background command from a script. https://crbug.com/254572. Background: Signal masks on Linux are inherited from parent processes. If anything invoking us accidentally masks SIGINT (e.g. by putting a process in the background from a shell script), sending a SIGINT to the child will fail to terminate it. """ signal.signal(signal.SIGINT, signal.SIG_DFL)
bsd-3-clause
mark-rushakoff/FlackOverstow
grabber.py
1
1835
#!/usr/bin/env python __author__ = "Mark Rushakoff" __license__ = "MIT" import sys import urllib2 import re import StringIO import gzip try: import simplejson as json except ImportError: try: import json except ImportError: sys.stderr.write("simplejson or json required for operation. Aborting.\n") sys.exit() try: from BeautifulSoup import BeautifulStoneSoup as bss except ImportError: sys.stderr.write("BeautifulSoup required to format data") sys.stderr.write("Try `easy_install beautifulsoup`") sys.exit() stripHtmlTags = re.compile(r"<[^>]*>") compressWhiteSpace = re.compile(r"\s+") def format(text): return bss(compressWhiteSpace.sub(' ', stripHtmlTags.sub('', text)), convertEntities=bss.ALL_ENTITIES) class Grabber(object): """ Class to obtain JSON data from Stack API """ _api = '1.0' def __init__(self, site, user_id, api_key=None): self.site = site self.user_id = user_id self.api_key = api_key def _grab(self, users_arg): url = 'http://api.%s/%s/users/%s/%s?body=true&pagesize=100' % (self.site, self._api, self.user_id, users_arg) if self.api_key is not None: url += '&key=%s' % self.api_key content = StringIO.StringIO(urllib2.urlopen(url).read()) return gzip.GzipFile(fileobj=content).read() def minimal_text(self, users_arg): """ return a list of just the simple text of the `body`s of the users_arg section of the pulled json """ json_data = self._grab(users_arg) answers = [answer['body'] for answer in json.loads(json_data)[users_arg]] return [str(format(answer)) for answer in answers] if __name__ == "__main__": grabber = Grabber('stackoverflow.com', 126042) for g in grabber.minimal_text('answers'): print g
mit
imankulov/sentry
tests/sentry/api/serializers/test_tagvalue.py
5
1234
# -*- coding: utf-8 -*- from __future__ import absolute_import from sentry.api.serializers import serialize from sentry.models import EventUser, TagValue from sentry.testutils import TestCase class TagValueSerializerTest(TestCase): def test_with_user(self): user = self.create_user() project = self.create_project() euser = EventUser.objects.create( project=project, email='foo@example.com', ) tagvalue = TagValue.objects.create( project=project, key='sentry:user', value=euser.tag_value, ) result = serialize(tagvalue, user) assert result['key'] == 'user' assert result['value'] == tagvalue.value assert result['name'] == euser.get_label() def test_basic(self): user = self.create_user() project = self.create_project() tagvalue = TagValue.objects.create( project=project, key='sentry:user', value='email:foo@example.com', ) result = serialize(tagvalue, user) assert result['key'] == 'user' assert result['value'] == tagvalue.value assert result['name'] == tagvalue.get_label()
bsd-3-clause
dbravender/raven-python
raven/utils/json.py
17
2664
""" raven.utils.json ~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import codecs import datetime import uuid try: import simplejson as json except ImportError: import json try: JSONDecodeError = json.JSONDecodeError except AttributeError: JSONDecodeError = ValueError class BetterJSONEncoder(json.JSONEncoder): ENCODER_BY_TYPE = { uuid.UUID: lambda o: o.hex, datetime.datetime: lambda o: o.strftime('%Y-%m-%dT%H:%M:%SZ'), set: list, frozenset: list, bytes: lambda o: o.decode('utf-8', errors='replace') } def default(self, obj): try: encoder = self.ENCODER_BY_TYPE[type(obj)] except KeyError: try: return super(BetterJSONEncoder, self).default(obj) except TypeError: return repr(obj) return encoder(obj) def better_decoder(data): return data def dumps(value, **kwargs): try: return json.dumps(value, cls=BetterJSONEncoder, **kwargs) except Exception: kwargs['encoding'] = 'safe-utf-8' return json.dumps(value, cls=BetterJSONEncoder, **kwargs) def loads(value, **kwargs): return json.loads(value, object_hook=better_decoder) _utf8_encoder = codecs.getencoder('utf-8') def safe_encode(input, errors='backslashreplace'): return _utf8_encoder(input, errors) _utf8_decoder = codecs.getdecoder('utf-8') def safe_decode(input, errors='replace'): return _utf8_decoder(input, errors) class Codec(codecs.Codec): def encode(self, input, errors='backslashreplace'): return safe_encode(input, errors) def decode(self, input, errors='replace'): return safe_decode(input, errors) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return safe_encode(input, self.errors)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return safe_decode(input, self.errors)[0] class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamReader): pass def getregentry(name): if name != 'safe-utf-8': return None return codecs.CodecInfo( name='safe-utf-8', encode=safe_encode, decode=safe_decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) codecs.register(getregentry)
bsd-3-clause
ayushgoel/FixGoogleContacts
phonenumbers/data/region_SC.py
1
2109
"""Auto-generated file, do not edit by hand. SC metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_SC = PhoneMetadata(id='SC', country_code=248, international_prefix='0[0-2]', general_desc=PhoneNumberDesc(national_number_pattern='[24689]\\d{5,6}', possible_number_pattern='\\d{6,7}'), fixed_line=PhoneNumberDesc(national_number_pattern='4[2-46]\\d{5}', possible_number_pattern='\\d{7}', example_number='4217123'), mobile=PhoneNumberDesc(national_number_pattern='2[5-8]\\d{5}', possible_number_pattern='\\d{7}', example_number='2510123'), toll_free=PhoneNumberDesc(national_number_pattern='8000\\d{2}', possible_number_pattern='\\d{6}', example_number='800000'), premium_rate=PhoneNumberDesc(national_number_pattern='98\\d{4}', possible_number_pattern='\\d{6}', example_number='981234'), shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), personal_number=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), voip=PhoneNumberDesc(national_number_pattern='64\\d{5}', possible_number_pattern='\\d{7}', example_number='6412345'), pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), uan=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), emergency=PhoneNumberDesc(national_number_pattern='999', possible_number_pattern='\\d{3}', example_number='999'), voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), short_code=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), standard_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), preferred_international_prefix='00', number_format=[NumberFormat(pattern='(\\d{3})(\\d{3})', format='\\1 \\2', leading_digits_pattern=['[89]']), NumberFormat(pattern='(\\d)(\\d{3})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['[246]'])])
mit
sxlijin/tfs_updater
lib/urllib3/exceptions.py
374
3274
# urllib3/exceptions.py # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php ## Base Exceptions class HTTPError(Exception): "Base exception used by this module." pass class PoolError(HTTPError): "Base exception for errors caused within a pool." def __init__(self, pool, message): self.pool = pool HTTPError.__init__(self, "%s: %s" % (pool, message)) def __reduce__(self): # For pickling purposes. return self.__class__, (None, None) class RequestError(PoolError): "Base exception for PoolErrors that have associated URLs." def __init__(self, pool, url, message): self.url = url PoolError.__init__(self, pool, message) def __reduce__(self): # For pickling purposes. return self.__class__, (None, self.url, None) class SSLError(HTTPError): "Raised when SSL certificate fails in an HTTPS connection." pass class ProxyError(HTTPError): "Raised when the connection to a proxy fails." pass class DecodeError(HTTPError): "Raised when automatic decoding based on Content-Type fails." pass ## Leaf Exceptions class MaxRetryError(RequestError): "Raised when the maximum number of retries is exceeded." def __init__(self, pool, url, reason=None): self.reason = reason message = "Max retries exceeded with url: %s" % url if reason: message += " (Caused by %s: %s)" % (type(reason), reason) else: message += " (Caused by redirect)" RequestError.__init__(self, pool, url, message) class HostChangedError(RequestError): "Raised when an existing pool gets a request for a foreign host." def __init__(self, pool, url, retries=3): message = "Tried to open a foreign host with url: %s" % url RequestError.__init__(self, pool, url, message) self.retries = retries class TimeoutStateError(HTTPError): """ Raised when passing an invalid state to a timeout """ pass class TimeoutError(HTTPError): """ Raised when a socket timeout error occurs. Catching this error will catch both :exc:`ReadTimeoutErrors <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`. """ pass class ReadTimeoutError(TimeoutError, RequestError): "Raised when a socket timeout occurs while receiving data from a server" pass # This timeout error does not have a URL attached and needs to inherit from the # base HTTPError class ConnectTimeoutError(TimeoutError): "Raised when a socket timeout occurs while connecting to a server" pass class EmptyPoolError(PoolError): "Raised when a pool runs out of connections and no more are allowed." pass class ClosedPoolError(PoolError): "Raised when a request enters a pool after the pool has been closed." pass class LocationParseError(ValueError, HTTPError): "Raised when get_host or similar fails to parse the URL input." def __init__(self, location): message = "Failed to parse: %s" % location HTTPError.__init__(self, message) self.location = location
gpl-3.0
ddico/odoo
addons/l10n_hr/__manifest__.py
1
1748
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Author: Goran Kliska # mail: goran.kliska(AT)slobodni-programi.hr # Copyright (C) 2011- Slobodni programi d.o.o., Zagreb # Contributions: # Tomislav Bošnjaković, Storm Computers d.o.o. : # - account types { "name": "Croatia - Accounting (RRIF 2012)", "description": """ Croatian localisation. ====================== Author: Goran Kliska, Slobodni programi d.o.o., Zagreb https://www.slobodni-programi.hr Contributions: Tomislav Bošnjaković, Storm Computers: tipovi konta Ivan Vađić, Slobodni programi: tipovi konta Description: Croatian Chart of Accounts (RRIF ver.2012) RRIF-ov računski plan za poduzetnike za 2012. Vrste konta Kontni plan prema RRIF-u, dorađen u smislu kraćenja naziva i dodavanja analitika Porezne grupe prema poreznoj prijavi Porezi PDV obrasca Ostali porezi Osnovne fiskalne pozicije Izvori podataka: https://www.rrif.hr/dok/preuzimanje/rrif-rp2011.rar https://www.rrif.hr/dok/preuzimanje/rrif-rp2012.rar """, "version": "13.0", "author": "OpenERP Croatian Community", 'category': 'Accounting/Localizations', 'depends': [ 'account', ], 'data': [ 'data/l10n_hr_chart_data.xml', 'data/account.account.type.csv', 'data/account.account.template.csv', 'data/account_chart_tag_data.xml', 'data/account.tax.group.csv', 'data/account_tax_report_data.xml', 'data/account_tax_template_data.xml', 'data/account_tax_fiscal_position_data.xml', 'data/account_chart_template_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], "active": False, }
agpl-3.0
TyberiusPrime/nikola
nikola/data/themes/base/messages/messages_ar.py
6
1620
# -*- encoding:utf-8 -*- from __future__ import unicode_literals MESSAGES = { "%d min remaining to read": "", "(active)": "", "Also available in:": "أيضا متوفر في:", "Archive": "الأرشيف", "Authors": "", "Categories": "فئات", "Comments": "التّعليقات", "LANGUAGE": "العربيّة", "Languages:": "اللغات", "More posts about %s": "المزيد من المقالات حول %s", "Newer posts": "مقالات أحدث", "Next post": "المقالة التالية", "No posts found.": "لم يوجد مقالات.", "Nothing found.": "لم يوجد شيء.", "Older posts": "مقالات أقدم", "Original site": "الموقع الأصلي", "Posted:": "نشر:", "Posts about %s": "مقالات عن s%", "Posts by %s": "", "Posts for year %s": "مقالات سنة s%", "Posts for {month} {day}, {year}": "", "Posts for {month} {year}": "", "Previous post": "المقالة السابقة", "Publication date": "تاريخ النشر", "RSS feed": "", "Read in English": "اقرأ بالعربية", "Read more": "قراءة المزيد", "Skip to main content": "انتقل إلى المحتوى الرئيسي", "Source": "المصدر", "Subcategories:": "", "Tags and Categories": "تصنيفات و فئات", "Tags": "تصنيفات", "Uncategorized": "", "Updates": "", "Write your page here.": "", "Write your post here.": "", "old posts, page %d": "مقالات قديمة, صفحة d%", "page %d": "صفحة d%", }
mit
detiber/ansible
test/units/modules/cloud/openstack/test_os_server.py
55
6456
import mock import pytest import yaml import inspect import collections from ansible.modules.cloud.openstack import os_server class AnsibleFail(Exception): pass class AnsibleExit(Exception): pass def params_from_doc(func): '''This function extracts the docstring from the specified function, parses it as a YAML document, and returns parameters for the os_server module.''' doc = inspect.getdoc(func) cfg = yaml.load(doc) for task in cfg: for module, params in task.items(): for k, v in params.items(): if k in ['nics'] and type(v) == str: params[k] = [v] task[module] = collections.defaultdict(str, params) return cfg[0]['os_server'] class FakeCloud (object): ports = [ {'name': 'port1', 'id': '1234'}, {'name': 'port2', 'id': '4321'}, ] networks = [ {'name': 'network1', 'id': '5678'}, {'name': 'network2', 'id': '8765'}, ] images = [ {'name': 'cirros', 'id': '1'}, {'name': 'fedora', 'id': '2'}, ] flavors = [ {'name': 'm1.small', 'id': '1', 'flavor_ram': 1024}, {'name': 'm1.tiny', 'id': '2', 'flavor_ram': 512}, ] def _find(self, source, name): for item in source: if item['name'] == name or item['id'] == name: return item def get_image_id(self, name, exclude=None): image = self._find(self.images, name) if image: return image['id'] def get_flavor(self, name): return self._find(self.flavors, name) def get_flavor_by_ram(self, ram, include=None): for flavor in self.flavors: if flavor['ram'] >= ram and (include is None or include in flavor['name']): return flavor def get_port(self, name): return self._find(self.ports, name) def get_network(self, name): return self._find(self.networks, name) create_server = mock.MagicMock() class TestNetworkArgs(object): '''This class exercises the _network_args function of the os_server module. For each test, we parse the YAML document contained in the docstring to retrieve the module parameters for the test.''' def setup_method(self, method): self.cloud = FakeCloud() self.module = mock.MagicMock() self.module.params = params_from_doc(method) def test_nics_string_net_id(self): ''' - os_server: nics: net-id=1234 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '1234') def test_nics_string_net_id_list(self): ''' - os_server: nics: net-id=1234,net-id=4321 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '1234') assert(args[1]['net-id'] == '4321') def test_nics_string_port_id(self): ''' - os_server: nics: port-id=1234 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['port-id'] == '1234') def test_nics_string_net_name(self): ''' - os_server: nics: net-name=network1 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '5678') def test_nics_string_port_name(self): ''' - os_server: nics: port-name=port1 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['port-id'] == '1234') def test_nics_structured_net_id(self): ''' - os_server: nics: - net-id: '1234' ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '1234') def test_nics_structured_mixed(self): ''' - os_server: nics: - net-id: '1234' - port-name: port1 - 'net-name=network1,port-id=4321' ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '1234') assert(args[1]['port-id'] == '1234') assert(args[2]['net-id'] == '5678') assert(args[3]['port-id'] == '4321') class TestCreateServer(object): def setup_method(self, method): self.cloud = FakeCloud() self.module = mock.MagicMock() self.module.params = params_from_doc(method) self.module.fail_json.side_effect = AnsibleFail() self.module.exit_json.side_effect = AnsibleExit() self.meta = mock.MagicMock() self.meta.gett_hostvars_from_server.return_value = { 'id': '1234' } os_server.meta = self.meta def test_create_server(self): ''' - os_server: image: cirros flavor: m1.tiny nics: - net-name: network1 meta: - key: value ''' with pytest.raises(AnsibleExit): os_server._create_server(self.module, self.cloud) assert(self.cloud.create_server.call_count == 1) assert(self.cloud.create_server.call_args[1]['image'] == self.cloud.get_image_id('cirros')) assert(self.cloud.create_server.call_args[1]['flavor'] == self.cloud.get_flavor('m1.tiny')['id']) assert(self.cloud.create_server.call_args[1]['nics'][0]['net-id'] == self.cloud.get_network('network1')['id']) def test_create_server_bad_flavor(self): ''' - os_server: image: cirros flavor: missing_flavor nics: - net-name: network1 ''' with pytest.raises(AnsibleFail): os_server._create_server(self.module, self.cloud) assert('missing_flavor' in self.module.fail_json.call_args[1]['msg']) def test_create_server_bad_nic(self): ''' - os_server: image: cirros flavor: m1.tiny nics: - net-name: missing_network ''' with pytest.raises(AnsibleFail): os_server._create_server(self.module, self.cloud) assert('missing_network' in self.module.fail_json.call_args[1]['msg'])
gpl-3.0
amarzavery/AutoRest
src/generator/AutoRest.Python.Azure.Tests/Expected/AcceptanceTests/AzureSpecials/fixtures/acceptancetestsazurespecials/operations/subscription_in_credentials_operations.py
9
12318
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.pipeline import ClientRawResponse import uuid from .. import models class SubscriptionInCredentialsOperations(object): """SubscriptionInCredentialsOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. :ivar api_version: The api version, which appears in the query, the value is always '2015-07-01-preview'. Constant value: "2015-07-01-preview". """ def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2015-07-01-preview" self.config = config def post_method_global_valid( self, custom_headers=None, raw=False, **operation_config): """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to '1234-5678-9012-3456' to succeed. :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: None :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`ErrorException<fixtures.acceptancetestsazurespecials.models.ErrorException>` """ # Construct URL url = '/azurespecials/subscriptionId/method/string/none/path/global/1234-5678-9012-3456/{subscriptionId}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: raise models.ErrorException(self._deserialize, response) if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def post_method_global_null( self, custom_headers=None, raw=False, **operation_config): """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to null, and client-side validation should prevent you from making this call. :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: None :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`ErrorException<fixtures.acceptancetestsazurespecials.models.ErrorException>` """ # Construct URL url = '/azurespecials/subscriptionId/method/string/none/path/global/null/{subscriptionId}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: raise models.ErrorException(self._deserialize, response) if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def post_method_global_not_provided_valid( self, custom_headers=None, raw=False, **operation_config): """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to '1234-5678-9012-3456' to succeed. :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: None :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`ErrorException<fixtures.acceptancetestsazurespecials.models.ErrorException>` """ # Construct URL url = '/azurespecials/subscriptionId/method/string/none/path/globalNotProvided/1234-5678-9012-3456/{subscriptionId}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: raise models.ErrorException(self._deserialize, response) if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def post_path_global_valid( self, custom_headers=None, raw=False, **operation_config): """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to '1234-5678-9012-3456' to succeed. :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: None :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`ErrorException<fixtures.acceptancetestsazurespecials.models.ErrorException>` """ # Construct URL url = '/azurespecials/subscriptionId/path/string/none/path/global/1234-5678-9012-3456/{subscriptionId}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: raise models.ErrorException(self._deserialize, response) if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def post_swagger_global_valid( self, custom_headers=None, raw=False, **operation_config): """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to '1234-5678-9012-3456' to succeed. :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: None :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`ErrorException<fixtures.acceptancetestsazurespecials.models.ErrorException>` """ # Construct URL url = '/azurespecials/subscriptionId/swagger/string/none/path/global/1234-5678-9012-3456/{subscriptionId}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: raise models.ErrorException(self._deserialize, response) if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response
mit
dlazz/ansible
lib/ansible/modules/system/reboot.py
2
2704
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (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 ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = r''' module: reboot short_description: Reboot a machine description: - Reboot a machine, wait for it to go down, come back up, and respond to commands. version_added: "2.7" options: pre_reboot_delay: description: - Seconds for shutdown to wait before requesting reboot. - On Linux, macOS and OpenBSD, this is converted to minutes and rounded down. If less than 60, it will be set to 0. - On Solaris and FreeBSD, this will be seconds. default: 0 type: int post_reboot_delay: description: - Seconds to wait after the reboot was successful and the connection was re-established. - This is useful if you want wait for something to settle despite your connection already working. default: 0 type: int reboot_timeout: description: - Maximum seconds to wait for machine to reboot and respond to a test command. - This timeout is evaluated separately for both network connection and test command success so the maximum execution time for the module is twice this amount. default: 600 type: int connect_timeout: description: - Maximum seconds to wait for a successful connection to the managed hosts before trying again. - If unspecified, the default setting for the underlying connection plugin is used. type: int test_command: description: - Command to run on the rebooted host and expect success from to determine the machine is ready for further tasks. default: whoami type: str msg: description: - Message to display to users before reboot. default: Reboot initiated by Ansible type: str notes: - For Windows targets, use the M(win_reboot) module instead. seealso: - module: win_reboot author: - Matt Davis (@nitzmahone) - Sam Doran (@samdoran) ''' EXAMPLES = r''' - name: Unconditionally reboot the machine with all defaults reboot: - name: Reboot a slow machine that might have lots of updates to apply reboot: reboot_timeout: 3600 ''' RETURN = r''' rebooted: description: true if the machine was rebooted returned: always type: bool sample: true elapsed: description: The number of seconds that elapsed waiting for the system to be rebooted. returned: always type: int sample: 23 '''
gpl-3.0
Nuos/python-docx
tests/opc/test_coreprops.py
7
7910
# encoding: utf-8 """ Unit test suite for the docx.opc.coreprops module """ from __future__ import ( absolute_import, division, print_function, unicode_literals ) import pytest from datetime import datetime from docx.opc.coreprops import CoreProperties from docx.oxml import parse_xml class DescribeCoreProperties(object): def it_knows_the_string_property_values(self, text_prop_get_fixture): core_properties, prop_name, expected_value = text_prop_get_fixture actual_value = getattr(core_properties, prop_name) assert actual_value == expected_value def it_can_change_the_string_property_values(self, text_prop_set_fixture): core_properties, prop_name, value, expected_xml = text_prop_set_fixture setattr(core_properties, prop_name, value) assert core_properties._element.xml == expected_xml def it_knows_the_date_property_values(self, date_prop_get_fixture): core_properties, prop_name, expected_datetime = date_prop_get_fixture actual_datetime = getattr(core_properties, prop_name) assert actual_datetime == expected_datetime def it_can_change_the_date_property_values(self, date_prop_set_fixture): core_properties, prop_name, value, expected_xml = ( date_prop_set_fixture ) setattr(core_properties, prop_name, value) assert core_properties._element.xml == expected_xml def it_knows_the_revision_number(self, revision_get_fixture): core_properties, expected_revision = revision_get_fixture assert core_properties.revision == expected_revision def it_can_change_the_revision_number(self, revision_set_fixture): core_properties, revision, expected_xml = revision_set_fixture core_properties.revision = revision assert core_properties._element.xml == expected_xml # fixtures ------------------------------------------------------- @pytest.fixture(params=[ ('created', datetime(2012, 11, 17, 16, 37, 40)), ('last_printed', datetime(2014, 6, 4, 4, 28)), ('modified', None), ]) def date_prop_get_fixture(self, request, core_properties): prop_name, expected_datetime = request.param return core_properties, prop_name, expected_datetime @pytest.fixture(params=[ ('created', 'dcterms:created', datetime(2001, 2, 3, 4, 5), '2001-02-03T04:05:00Z', ' xsi:type="dcterms:W3CDTF"'), ('last_printed', 'cp:lastPrinted', datetime(2014, 6, 4, 4), '2014-06-04T04:00:00Z', ''), ('modified', 'dcterms:modified', datetime(2005, 4, 3, 2, 1), '2005-04-03T02:01:00Z', ' xsi:type="dcterms:W3CDTF"'), ]) def date_prop_set_fixture(self, request): prop_name, tagname, value, str_val, attrs = request.param coreProperties = self.coreProperties(None, None) core_properties = CoreProperties(parse_xml(coreProperties)) expected_xml = self.coreProperties(tagname, str_val, attrs) return core_properties, prop_name, value, expected_xml @pytest.fixture(params=[ ('42', 42), (None, 0), ('foobar', 0), ('-17', 0), ('32.7', 0) ]) def revision_get_fixture(self, request): str_val, expected_revision = request.param tagname = '' if str_val is None else 'cp:revision' coreProperties = self.coreProperties(tagname, str_val) core_properties = CoreProperties(parse_xml(coreProperties)) return core_properties, expected_revision @pytest.fixture(params=[ (42, '42'), ]) def revision_set_fixture(self, request): value, str_val = request.param coreProperties = self.coreProperties(None, None) core_properties = CoreProperties(parse_xml(coreProperties)) expected_xml = self.coreProperties('cp:revision', str_val) return core_properties, value, expected_xml @pytest.fixture(params=[ ('author', 'python-docx'), ('category', ''), ('comments', ''), ('content_status', 'DRAFT'), ('identifier', 'GXS 10.2.1ab'), ('keywords', 'foo bar baz'), ('language', 'US-EN'), ('last_modified_by', 'Steve Canny'), ('subject', 'Spam'), ('title', 'Word Document'), ('version', '1.2.88'), ]) def text_prop_get_fixture(self, request, core_properties): prop_name, expected_value = request.param return core_properties, prop_name, expected_value @pytest.fixture(params=[ ('author', 'dc:creator', 'scanny'), ('category', 'cp:category', 'silly stories'), ('comments', 'dc:description', 'Bar foo to you'), ('content_status', 'cp:contentStatus', 'FINAL'), ('identifier', 'dc:identifier', 'GT 5.2.xab'), ('keywords', 'cp:keywords', 'dog cat moo'), ('language', 'dc:language', 'GB-EN'), ('last_modified_by', 'cp:lastModifiedBy', 'Billy Bob'), ('subject', 'dc:subject', 'Eggs'), ('title', 'dc:title', 'Dissertation'), ('version', 'cp:version', '81.2.8'), ]) def text_prop_set_fixture(self, request): prop_name, tagname, value = request.param coreProperties = self.coreProperties(None, None) core_properties = CoreProperties(parse_xml(coreProperties)) expected_xml = self.coreProperties(tagname, value) return core_properties, prop_name, value, expected_xml # fixture components --------------------------------------------- def coreProperties(self, tagname, str_val, attrs=''): tmpl = ( '<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/' 'package/2006/metadata/core-properties" xmlns:dc="http://purl.or' 'g/dc/elements/1.1/" xmlns:dcmitype="http://purl.org/dc/dcmitype' '/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://' 'www.w3.org/2001/XMLSchema-instance">%s</cp:coreProperties>\n' ) if not tagname: child_element = '' elif not str_val: child_element = '\n <%s%s/>\n' % (tagname, attrs) else: child_element = ( '\n <%s%s>%s</%s>\n' % (tagname, attrs, str_val, tagname) ) return tmpl % child_element @pytest.fixture def core_properties(self): element = parse_xml( b'<?xml version=\'1.0\' encoding=\'UTF-8\' standalone=\'yes\'?>' b'\n<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.o' b'rg/package/2006/metadata/core-properties" xmlns:dc="http://pur' b'l.org/dc/elements/1.1/" xmlns:dcmitype="http://purl.org/dc/dcm' b'itype/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="h' b'ttp://www.w3.org/2001/XMLSchema-instance">\n' b' <cp:contentStatus>DRAFT</cp:contentStatus>\n' b' <dc:creator>python-docx</dc:creator>\n' b' <dcterms:created xsi:type="dcterms:W3CDTF">2012-11-17T11:07:' b'40-05:30</dcterms:created>\n' b' <dc:description/>\n' b' <dc:identifier>GXS 10.2.1ab</dc:identifier>\n' b' <dc:language>US-EN</dc:language>\n' b' <cp:lastPrinted>2014-06-04T04:28:00Z</cp:lastPrinted>\n' b' <cp:keywords>foo bar baz</cp:keywords>\n' b' <cp:lastModifiedBy>Steve Canny</cp:lastModifiedBy>\n' b' <cp:revision>4</cp:revision>\n' b' <dc:subject>Spam</dc:subject>\n' b' <dc:title>Word Document</dc:title>\n' b' <cp:version>1.2.88</cp:version>\n' b'</cp:coreProperties>\n' ) return CoreProperties(element)
mit
minlexx/pyevemon
esi_client/models/delete_fleets_fleet_id_squads_squad_id_forbidden.py
1
3083
# coding: utf-8 """ EVE Swagger Interface An OpenAPI for EVE Online OpenAPI spec version: 0.4.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class DeleteFleetsFleetIdSquadsSquadIdForbidden(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, error=None): """ DeleteFleetsFleetIdSquadsSquadIdForbidden - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'error': 'str' } self.attribute_map = { 'error': 'error' } self._error = error @property def error(self): """ Gets the error of this DeleteFleetsFleetIdSquadsSquadIdForbidden. Forbidden message :return: The error of this DeleteFleetsFleetIdSquadsSquadIdForbidden. :rtype: str """ return self._error @error.setter def error(self, error): """ Sets the error of this DeleteFleetsFleetIdSquadsSquadIdForbidden. Forbidden message :param error: The error of this DeleteFleetsFleetIdSquadsSquadIdForbidden. :type: str """ self._error = error def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, DeleteFleetsFleetIdSquadsSquadIdForbidden): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
gpl-3.0
deshipu/micropython
tests/wipy/time.py
67
2937
import time DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def is_leap(year): return (year % 4) == 0 def test(): seconds = 0 wday = 5 # Jan 1, 2000 was a Saturday for year in range(2000, 2049): print("Testing %d" % year) yday = 1 for month in range(1, 13): if month == 2 and is_leap(year): DAYS_PER_MONTH[2] = 29 else: DAYS_PER_MONTH[2] = 28 for day in range(1, DAYS_PER_MONTH[month] + 1): secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) if secs != seconds: print("mktime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) tuple = time.localtime(seconds) secs = time.mktime(tuple) if secs != seconds: print("localtime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) return seconds += 86400 if yday != tuple[7]: print("locatime for %d-%02d-%02d got yday %d, expecting %d" % (year, month, day, tuple[7], yday)) return if wday != tuple[6]: print("locatime for %d-%02d-%02d got wday %d, expecting %d" % (year, month, day, tuple[6], wday)) return yday += 1 wday = (wday + 1) % 7 def spot_test(seconds, expected_time): actual_time = time.localtime(seconds) for i in range(len(actual_time)): if actual_time[i] != expected_time[i]: print("time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time) return print("time.localtime(", seconds, ") returned", actual_time, "(pass)") test() spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1)) spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1)) spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1)) spot_test( 60, (2000, 1, 1, 0, 1, 0, 5, 1)) spot_test( 3599, (2000, 1, 1, 0, 59, 59, 5, 1)) spot_test( 3600, (2000, 1, 1, 1, 0, 0, 5, 1)) spot_test( -1, (1999, 12, 31, 23, 59, 59, 4, 365)) spot_test( 447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) t1 = time.time() time.sleep(2) t2 = time.time() print(abs(time.ticks_diff(t1, t2) -2) <= 1) t1 = time.ticks_ms() time.sleep_ms(50) t2 = time.ticks_ms() print(abs(time.ticks_diff(t1, t2)- 50) <= 1) t1 = time.ticks_us() time.sleep_us(1000) t2 = time.ticks_us() print(time.ticks_diff(t1, t2) < 1500) print(time.ticks_diff(time.ticks_cpu(), time.ticks_cpu()) < 16384)
mit
rohit21122012/DCASE2013
runs/2016/dnn2016verylarge/src/sound_event_detection.py
38
6092
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy def event_detection(feature_data, model_container, hop_length_seconds=0.01, smoothing_window_length_seconds=1.0, decision_threshold=0.0, minimum_event_length=0.1, minimum_event_gap=0.1): """Sound event detection Parameters ---------- feature_data : numpy.ndarray [shape=(n_features, t)] Feature matrix model_container : dict Sound event model pairs [positive and negative] in dict hop_length_seconds : float > 0.0 Feature hop length in seconds, used to convert feature index into time-stamp (Default value=0.01) smoothing_window_length_seconds : float > 0.0 Accumulation window (look-back) length, withing the window likelihoods are accumulated. (Default value=1.0) decision_threshold : float > 0.0 Likelihood ratio threshold for making the decision. (Default value=0.0) minimum_event_length : float > 0.0 Minimum event length in seconds, shorten than given are filtered out from the output. (Default value=0.1) minimum_event_gap : float > 0.0 Minimum allowed gap between events in seconds from same event label class. (Default value=0.1) Returns ------- results : list (event dicts) Detection result, event list """ smoothing_window = int(smoothing_window_length_seconds / hop_length_seconds) results = [] for event_label in model_container['models']: positive = model_container['models'][event_label]['positive'].score_samples(feature_data)[0] negative = model_container['models'][event_label]['negative'].score_samples(feature_data)[0] # Lets keep the system causal and use look-back while smoothing (accumulating) likelihoods for stop_id in range(0, feature_data.shape[0]): start_id = stop_id - smoothing_window if start_id < 0: start_id = 0 positive[start_id] = sum(positive[start_id:stop_id]) negative[start_id] = sum(negative[start_id:stop_id]) likelihood_ratio = positive - negative event_activity = likelihood_ratio > decision_threshold # Find contiguous segments and convert frame-ids into times event_segments = contiguous_regions(event_activity) * hop_length_seconds # Preprocess the event segments event_segments = postprocess_event_segments(event_segments=event_segments, minimum_event_length=minimum_event_length, minimum_event_gap=minimum_event_gap) for event in event_segments: results.append((event[0], event[1], event_label)) return results def contiguous_regions(activity_array): """Find contiguous regions from bool valued numpy.array. Transforms boolean values for each frame into pairs of onsets and offsets. Parameters ---------- activity_array : numpy.array [shape=(t)] Event activity array, bool values Returns ------- change_indices : numpy.ndarray [shape=(2, number of found changes)] Onset and offset indices pairs in matrix """ # Find the changes in the activity_array change_indices = numpy.diff(activity_array).nonzero()[0] # Shift change_index with one, focus on frame after the change. change_indices += 1 if activity_array[0]: # If the first element of activity_array is True add 0 at the beginning change_indices = numpy.r_[0, change_indices] if activity_array[-1]: # If the last element of activity_array is True, add the length of the array change_indices = numpy.r_[change_indices, activity_array.size] # Reshape the result into two columns return change_indices.reshape((-1, 2)) def postprocess_event_segments(event_segments, minimum_event_length=0.1, minimum_event_gap=0.1): """Post process event segment list. Makes sure that minimum event length and minimum event gap conditions are met. Parameters ---------- event_segments : numpy.ndarray [shape=(2, number of event)] Event segments, first column has the onset, second has the offset. minimum_event_length : float > 0.0 Minimum event length in seconds, shorten than given are filtered out from the output. (Default value=0.1) minimum_event_gap : float > 0.0 Minimum allowed gap between events in seconds from same event label class. (Default value=0.1) Returns ------- event_results : numpy.ndarray [shape=(2, number of event)] postprocessed event segments """ # 1. remove short events event_results_1 = [] for event in event_segments: if event[1]-event[0] >= minimum_event_length: event_results_1.append((event[0], event[1])) if len(event_results_1): # 2. remove small gaps between events event_results_2 = [] # Load first event into event buffer buffered_event_onset = event_results_1[0][0] buffered_event_offset = event_results_1[0][1] for i in range(1, len(event_results_1)): if event_results_1[i][0] - buffered_event_offset > minimum_event_gap: # The gap between current event and the buffered is bigger than minimum event gap, # store event, and replace buffered event event_results_2.append((buffered_event_onset, buffered_event_offset)) buffered_event_onset = event_results_1[i][0] buffered_event_offset = event_results_1[i][1] else: # The gap between current event and the buffered is smalle than minimum event gap, # extend the buffered event until the current offset buffered_event_offset = event_results_1[i][1] # Store last event from buffer event_results_2.append((buffered_event_onset, buffered_event_offset)) return event_results_2 else: return event_results_1
mit
PrzemyslawUrbanczyk/pu_zadanie1
fixture/contact.py
1
10214
import re from model.contact import Contact class ContactHelper: def __init__(self, app): self.app = app def return_to_home_page(self): wd = self.app.wd wd.find_element_by_link_text("home page").click() def create(self, contact): wd = self.app.wd # init contact creation wd.find_element_by_link_text("nowy wpis").click() # fill contact form self.fill_contact_form(contact) # submit contact creation wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click() self.contact_cache = None def fill_contact_form(self, contact): wd = self.app.wd self.change_field_value("firstname", contact.first_name) self.change_field_value("middlename", contact.middle_name) self.change_field_value("lastname", contact.last_name) self.change_field_value("nickname", contact.nickname) self.change_field_value("title", contact.title) self.change_field_value("company", contact.company) self.change_field_value("address", contact.address) self.change_field_value("home", contact.home_number) self.change_field_value("mobile", contact.mobile_number) self.change_field_value("work", contact.work_number) self.change_field_value("fax", contact.fax) self.change_field_value("email", contact.first_email) self.change_field_value("email2", contact.second_email) self.change_field_value("email3", contact.third_email) self.change_field_value("homepage", contact.wwwpage) if not wd.find_element_by_xpath("//div[@id='content']/form/select[1]//option[16]").is_selected(): wd.find_element_by_xpath("//div[@id='content']/form/select[1]//option[16]").click() if not wd.find_element_by_xpath("//div[@id='content']/form/select[2]//option[2]").is_selected(): wd.find_element_by_xpath("//div[@id='content']/form/select[2]//option[2]").click() self.change_field_value("byear", contact.birth_year) if not wd.find_element_by_xpath("//div[@id='content']/form/select[3]//option[17]").is_selected(): wd.find_element_by_xpath("//div[@id='content']/form/select[3]//option[17]").click() if not wd.find_element_by_xpath("//div[@id='content']/form/select[4]//option[6]").is_selected(): wd.find_element_by_xpath("//div[@id='content']/form/select[4]//option[6]").click() self.change_field_value("ayear", contact.anniversary_year) self.change_field_value("address2", contact.second_address) self.change_field_value("phone2", contact.second_private_number) self.change_field_value("notes", contact.notes) def change_field_value(self, field_name, text): wd = self.app.wd if text is not None: wd.find_element_by_name(field_name).click() wd.find_element_by_name(field_name).clear() wd.find_element_by_name(field_name).send_keys(text) def delete_first_contact(self): self.delete_contact_by_index(0) def delete_contact_by_index(self, index): wd = self.app.wd self.open_contacts_page() self.select_contact_by_index(index) # confirm deletion wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click() wd.switch_to_alert().accept() self.contact_cache = None def delete_contact_by_id(self, id): wd = self.app.wd self.app.open_home_page() # open deletion wd.find_element_by_css_selector("input[value='%s']" % id).click() # submit deletion wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click() wd.switch_to_alert().accept() self.app.open_home_page() self.group_cache = None def select_first_contact(self): self.select_contact_by_index(0) def modify_first_contact(self): self.modify_contact_by_index[0] def modify_contact_by_index(self, index, new_contact_data): wd = self.app.wd self.open_contacts_page() row = wd.find_elements_by_name("entry")[index] cells = row.find_elements_by_tag_name("td") cells[7].click() # modify contact form self.fill_contact_form(new_contact_data) # submit contact creation wd.find_element_by_xpath("//div[@id='content']/form[1]/input[22]").click() self.contact_cache = None def modify_contact_by_id(self, id, contact): wd = self.app.wd self.app.open_home_page() # open modification form checkbox = wd.find_element_by_css_selector("input[value='%s']" % id) row = checkbox.find_element_by_xpath("./../..") cells = row.find_elements_by_tag_name("td") cells[7].click() # fill group form self.fill_contact_form(contact) # submit changes wd.find_element_by_name("update").click() def select_contact_by_index(self, index): wd = self.app.wd wd.find_elements_by_name("selected[]")[index].click() def select_contact_by_id(self, id): wd = self.app.wd row = wd.find_element_by_css_selector("input[value='%s']" % id) return row def open_contacts_page(self): wd = self.app.wd if not (wd.current_url.endswith("index.php") and len(wd.find_elements_by_id("MassCB")) > 0): wd.find_element_by_link_text("strona główna").click() def count(self): wd = self.app.wd self.open_contacts_page() return len(wd.find_elements_by_name("selected[]")) contact_cache = None def get_contact_list(self): if self.contact_cache is None: wd = self.app.wd self.open_contacts_page() self.contact_cache = [] for row in wd.find_elements_by_name("entry"): cells = row.find_elements_by_tag_name("td") firstname = cells[2].text lastname = cells[1]. text id = row.find_element_by_name("selected[]").get_attribute("value") all_emails = cells[4].text all_phones = cells[5].text address = cells[3].text self.contact_cache.append(Contact(first_name=firstname, last_name=lastname, id=id, all_phones_from_home_page=all_phones, all_emails_from_home_page=all_emails, address=address)) return list(self.contact_cache) def open_contact_to_edit_by_index(self, index): wd = self.app.wd self.app.open_home_page() row = wd.find_elements_by_name("entry")[index] cells = row.find_elements_by_tag_name("td")[7] cells.find_element_by_tag_name("a").click() def open_contact_view_by_index(self, index): wd = self.app.wd self.open_contacts_page() row = wd.find_elements_by_name("entry")[index] cell = row.find_elements_by_tag_name("td")[6] cell.find_elements_by_tag_name("a").click() def get_contact_info_from_edit_page(self, index): wd = self.app.wd self.open_contact_to_edit_by_index(index) firstname = wd.find_element_by_name("firstname").get_attribute("value") lastname = wd.find_element_by_name("lastname").get_attribute("value") id = wd.find_element_by_name("id").get_attribute("value") homephone = wd.find_element_by_name("home").get_attribute("value") workphone = wd.find_element_by_name("work").get_attribute("value") mobilephone = wd.find_element_by_name("mobile").get_attribute("value") secondaryphone = wd.find_element_by_name("phone2").get_attribute("value") email = wd.find_element_by_name("email").get_attribute("value") email2 = wd.find_element_by_name("email2").get_attribute("value") email3 = wd.find_element_by_name("email3").get_attribute("value") address = wd.find_element_by_name("address").get_attribute("value") return Contact(first_name=firstname, last_name=lastname, id=id, home_number=homephone, mobile_number=mobilephone, work_number=workphone, second_private_number=secondaryphone, first_email=email, second_email=email2, third_email=email3, address=address) def get_contact_view_page(self, index): wd = self.app.wd self.open_contact_to_view_by_index(index) text = wd.find_element_by_id("content").text homephone = re.search("H: (.*)", text).group(1) workphone = re.search("W: (.*)", text).group(1) mobilephone = re.search("M: (.*)", text).group(1) secondaryphone = re.search("P: (.*)", text).group(1) def open_contact_to_view_by_index(self, index): wd = self.app.wd self.app.open_home_page() row = wd.find_elements_by_name("entry")[index] cells = row.find_elements_by_tag_name("td")[6] cells.find_element_by_tag_name("a").click() def add_contact_to_group_by_id(self, id, group): wd = self.app.wd if not len(wd.find_elements_by_name("searchstring")) > 0: self.app.open_home_page() # add mew contact wd.find_element_by_css_selector("input[value='%s']" % id).click() number=group.id wd.find_element_by_xpath("//select[@name='to_group']//option[@value='%s']"% number).click() wd.find_element_by_name("add").click() self.app.open_home_page() self.contact_cache = None def add_contact_to_group(self, Contact, group): wd = self.app.wd if not len(wd.find_elements_by_name("searchstring")) > 0: self.app.open_home_page() # add new contact wd.find_element_by_link_text("add new").click() self.fill_contact_form(Contact) number = group.id wd.find_element_by_xpath("//div[@id='content']/form/select[5]//option[@value='%s']" % number).click() # accept wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click() self.app.open_home_page() self.contact_cache = None
apache-2.0
Korkki/django
tests/model_fields/test_imagefield.py
181
16062
from __future__ import unicode_literals import os import shutil from unittest import skipIf from django.core.exceptions import ImproperlyConfigured from django.core.files import File from django.core.files.images import ImageFile from django.test import TestCase from django.utils._os import upath try: from .models import Image except ImproperlyConfigured: Image = None if Image: from .models import (Person, PersonWithHeight, PersonWithHeightAndWidth, PersonDimensionsFirst, PersonTwoImages, TestImageFieldFile) from .models import temp_storage_dir else: # Pillow not available, create dummy classes (tests will be skipped anyway) class Person(): pass PersonWithHeight = PersonWithHeightAndWidth = PersonDimensionsFirst = Person PersonTwoImages = Person class ImageFieldTestMixin(object): """ Mixin class to provide common functionality to ImageField test classes. """ # Person model to use for tests. PersonModel = PersonWithHeightAndWidth # File class to use for file instances. File = ImageFile def setUp(self): """ Creates a pristine temp directory (or deletes and recreates if it already exists) that the model uses as its storage directory. Sets up two ImageFile instances for use in tests. """ if os.path.exists(temp_storage_dir): shutil.rmtree(temp_storage_dir) os.mkdir(temp_storage_dir) file_path1 = os.path.join(os.path.dirname(upath(__file__)), "4x8.png") self.file1 = self.File(open(file_path1, 'rb')) file_path2 = os.path.join(os.path.dirname(upath(__file__)), "8x4.png") self.file2 = self.File(open(file_path2, 'rb')) def tearDown(self): """ Removes temp directory and all its contents. """ self.file1.close() self.file2.close() shutil.rmtree(temp_storage_dir) def check_dimensions(self, instance, width, height, field_name='mugshot'): """ Asserts that the given width and height values match both the field's height and width attributes and the height and width fields (if defined) the image field is caching to. Note, this method will check for dimension fields named by adding "_width" or "_height" to the name of the ImageField. So, the models used in these tests must have their fields named accordingly. By default, we check the field named "mugshot", but this can be specified by passing the field_name parameter. """ field = getattr(instance, field_name) # Check height/width attributes of field. if width is None and height is None: self.assertRaises(ValueError, getattr, field, 'width') self.assertRaises(ValueError, getattr, field, 'height') else: self.assertEqual(field.width, width) self.assertEqual(field.height, height) # Check height/width fields of model, if defined. width_field_name = field_name + '_width' if hasattr(instance, width_field_name): self.assertEqual(getattr(instance, width_field_name), width) height_field_name = field_name + '_height' if hasattr(instance, height_field_name): self.assertEqual(getattr(instance, height_field_name), height) @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldTests(ImageFieldTestMixin, TestCase): """ Tests for ImageField that don't need to be run with each of the different test model classes. """ def test_equal_notequal_hash(self): """ Bug #9786: Ensure '==' and '!=' work correctly. Bug #9508: make sure hash() works as expected (equal items must hash to the same value). """ # Create two Persons with different mugshots. p1 = self.PersonModel(name="Joe") p1.mugshot.save("mug", self.file1) p2 = self.PersonModel(name="Bob") p2.mugshot.save("mug", self.file2) self.assertEqual(p1.mugshot == p2.mugshot, False) self.assertEqual(p1.mugshot != p2.mugshot, True) # Test again with an instance fetched from the db. p1_db = self.PersonModel.objects.get(name="Joe") self.assertEqual(p1_db.mugshot == p2.mugshot, False) self.assertEqual(p1_db.mugshot != p2.mugshot, True) # Instance from db should match the local instance. self.assertEqual(p1_db.mugshot == p1.mugshot, True) self.assertEqual(hash(p1_db.mugshot), hash(p1.mugshot)) self.assertEqual(p1_db.mugshot != p1.mugshot, False) def test_instantiate_missing(self): """ If the underlying file is unavailable, still create instantiate the object without error. """ p = self.PersonModel(name="Joan") p.mugshot.save("shot", self.file1) p = self.PersonModel.objects.get(name="Joan") path = p.mugshot.path shutil.move(path, path + '.moved') self.PersonModel.objects.get(name="Joan") def test_delete_when_missing(self): """ Bug #8175: correctly delete an object where the file no longer exists on the file system. """ p = self.PersonModel(name="Fred") p.mugshot.save("shot", self.file1) os.remove(p.mugshot.path) p.delete() def test_size_method(self): """ Bug #8534: FileField.size should not leave the file open. """ p = self.PersonModel(name="Joan") p.mugshot.save("shot", self.file1) # Get a "clean" model instance p = self.PersonModel.objects.get(name="Joan") # It won't have an opened file. self.assertEqual(p.mugshot.closed, True) # After asking for the size, the file should still be closed. p.mugshot.size self.assertEqual(p.mugshot.closed, True) def test_pickle(self): """ Tests that ImageField can be pickled, unpickled, and that the image of the unpickled version is the same as the original. """ import pickle p = Person(name="Joe") p.mugshot.save("mug", self.file1) dump = pickle.dumps(p) p2 = Person(name="Bob") p2.mugshot = self.file1 loaded_p = pickle.loads(dump) self.assertEqual(p.mugshot, loaded_p.mugshot) @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase): """ Tests behavior of an ImageField and its dimensions fields. """ def test_constructor(self): """ Tests assigning an image field through the model's constructor. """ p = self.PersonModel(name='Joe', mugshot=self.file1) self.check_dimensions(p, 4, 8) p.save() self.check_dimensions(p, 4, 8) def test_image_after_constructor(self): """ Tests behavior when image is not passed in constructor. """ p = self.PersonModel(name='Joe') # TestImageField value will default to being an instance of its # attr_class, a TestImageFieldFile, with name == None, which will # cause it to evaluate as False. self.assertIsInstance(p.mugshot, TestImageFieldFile) self.assertEqual(bool(p.mugshot), False) # Test setting a fresh created model instance. p = self.PersonModel(name='Joe') p.mugshot = self.file1 self.check_dimensions(p, 4, 8) def test_create(self): """ Tests assigning an image in Manager.create(). """ p = self.PersonModel.objects.create(name='Joe', mugshot=self.file1) self.check_dimensions(p, 4, 8) def test_default_value(self): """ Tests that the default value for an ImageField is an instance of the field's attr_class (TestImageFieldFile in this case) with no name (name set to None). """ p = self.PersonModel() self.assertIsInstance(p.mugshot, TestImageFieldFile) self.assertEqual(bool(p.mugshot), False) def test_assignment_to_None(self): """ Tests that assigning ImageField to None clears dimensions. """ p = self.PersonModel(name='Joe', mugshot=self.file1) self.check_dimensions(p, 4, 8) # If image assigned to None, dimension fields should be cleared. p.mugshot = None self.check_dimensions(p, None, None) p.mugshot = self.file2 self.check_dimensions(p, 8, 4) def test_field_save_and_delete_methods(self): """ Tests assignment using the field's save method and deletion using the field's delete method. """ p = self.PersonModel(name='Joe') p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8) # A new file should update dimensions. p.mugshot.save("mug", self.file2) self.check_dimensions(p, 8, 4) # Field and dimensions should be cleared after a delete. p.mugshot.delete(save=False) self.assertEqual(p.mugshot, None) self.check_dimensions(p, None, None) def test_dimensions(self): """ Checks that dimensions are updated correctly in various situations. """ p = self.PersonModel(name='Joe') # Dimensions should get set if file is saved. p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8) # Test dimensions after fetching from database. p = self.PersonModel.objects.get(name='Joe') # Bug 11084: Dimensions should not get recalculated if file is # coming from the database. We test this by checking if the file # was opened. self.assertEqual(p.mugshot.was_opened, False) self.check_dimensions(p, 4, 8) # After checking dimensions on the image field, the file will have # opened. self.assertEqual(p.mugshot.was_opened, True) # Dimensions should now be cached, and if we reset was_opened and # check dimensions again, the file should not have opened. p.mugshot.was_opened = False self.check_dimensions(p, 4, 8) self.assertEqual(p.mugshot.was_opened, False) # If we assign a new image to the instance, the dimensions should # update. p.mugshot = self.file2 self.check_dimensions(p, 8, 4) # Dimensions were recalculated, and hence file should have opened. self.assertEqual(p.mugshot.was_opened, True) @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldNoDimensionsTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField with no dimension fields. """ PersonModel = Person @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldOneDimensionTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField with one dimensions field. """ PersonModel = PersonWithHeight @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldDimensionsFirstTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField where the dimensions fields are defined before the ImageField. """ PersonModel = PersonDimensionsFirst @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldUsingFileTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField when assigning it a File instance rather than an ImageFile instance. """ PersonModel = PersonDimensionsFirst File = File @skipIf(Image is None, "Pillow is required to test ImageField") class TwoImageFieldTests(ImageFieldTestMixin, TestCase): """ Tests a model with two ImageFields. """ PersonModel = PersonTwoImages def test_constructor(self): p = self.PersonModel(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') p.save() self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') def test_create(self): p = self.PersonModel.objects.create(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8) self.check_dimensions(p, 8, 4, 'headshot') def test_assignment(self): p = self.PersonModel() self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.mugshot = self.file1 self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.headshot = self.file2 self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # Clear the ImageFields one at a time. p.mugshot = None self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') p.headshot = None self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, None, None, 'headshot') def test_field_save_and_delete_methods(self): p = self.PersonModel(name='Joe') p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # We can use save=True when deleting the image field with null=True # dimension fields and the other field has an image. p.headshot.delete(save=True) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.mugshot.delete(save=False) self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, None, None, 'headshot') def test_dimensions(self): """ Checks that dimensions are updated correctly in various situations. """ p = self.PersonModel(name='Joe') # Dimensions should get set for the saved file. p.mugshot.save("mug", self.file1) p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # Test dimensions after fetching from database. p = self.PersonModel.objects.get(name='Joe') # Bug 11084: Dimensions should not get recalculated if file is # coming from the database. We test this by checking if the file # was opened. self.assertEqual(p.mugshot.was_opened, False) self.assertEqual(p.headshot.was_opened, False) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # After checking dimensions on the image fields, the files will # have been opened. self.assertEqual(p.mugshot.was_opened, True) self.assertEqual(p.headshot.was_opened, True) # Dimensions should now be cached, and if we reset was_opened and # check dimensions again, the file should not have opened. p.mugshot.was_opened = False p.headshot.was_opened = False self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') self.assertEqual(p.mugshot.was_opened, False) self.assertEqual(p.headshot.was_opened, False) # If we assign a new image to the instance, the dimensions should # update. p.mugshot = self.file2 p.headshot = self.file1 self.check_dimensions(p, 8, 4, 'mugshot') self.check_dimensions(p, 4, 8, 'headshot') # Dimensions were recalculated, and hence file should have opened. self.assertEqual(p.mugshot.was_opened, True) self.assertEqual(p.headshot.was_opened, True)
bsd-3-clause
shepdelacreme/ansible
lib/ansible/modules/database/proxysql/proxysql_mysql_users.py
16
16081
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: proxysql_mysql_users version_added: "2.3" author: "Ben Mildren (@bmildren)" short_description: Adds or removes mysql users from proxysql admin interface. description: - The M(proxysql_mysql_users) module adds or removes mysql users using the proxysql admin interface. options: username: description: - Name of the user connecting to the mysqld or ProxySQL instance. required: True password: description: - Password of the user connecting to the mysqld or ProxySQL instance. active: description: - A user with I(active) set to C(False) will be tracked in the database, but will be never loaded in the in-memory data structures. If omitted the proxysql database default for I(active) is C(True). use_ssl: description: - If I(use_ssl) is set to C(True), connections by this user will be made using SSL connections. If omitted the proxysql database default for I(use_ssl) is C(False). default_hostgroup: description: - If there is no matching rule for the queries sent by this user, the traffic it generates is sent to the specified hostgroup. If omitted the proxysql database default for I(use_ssl) is 0. default_schema: description: - The schema to which the connection should change to by default. transaction_persistent: description: - If this is set for the user with which the MySQL client is connecting to ProxySQL (thus a "frontend" user), transactions started within a hostgroup will remain within that hostgroup regardless of any other rules. If omitted the proxysql database default for I(transaction_persistent) is C(False). fast_forward: description: - If I(fast_forward) is set to C(True), I(fast_forward) will bypass the query processing layer (rewriting, caching) and pass through the query directly as is to the backend server. If omitted the proxysql database default for I(fast_forward) is C(False). backend: description: - If I(backend) is set to C(True), this (username, password) pair is used for authenticating to the ProxySQL instance. default: True frontend: description: - If I(frontend) is set to C(True), this (username, password) pair is used for authenticating to the mysqld servers against any hostgroup. default: True max_connections: description: - The maximum number of connections ProxySQL will open to the backend for this user. If omitted the proxysql database default for I(max_connections) is 10000. state: description: - When C(present) - adds the user, when C(absent) - removes the user. choices: [ "present", "absent" ] default: present extends_documentation_fragment: - proxysql.managing_config - proxysql.connectivity ''' EXAMPLES = ''' --- # This example adds a user, it saves the mysql user config to disk, but # avoids loading the mysql user config to runtime (this might be because # several users are being added and the user wants to push the config to # runtime in a single batch using the M(proxysql_manage_config) module). It # uses supplied credentials to connect to the proxysql admin interface. - proxysql_mysql_users: login_user: 'admin' login_password: 'admin' username: 'productiondba' state: present load_to_runtime: False # This example removes a user, saves the mysql user config to disk, and # dynamically loads the mysql user config to runtime. It uses credentials # in a supplied config file to connect to the proxysql admin interface. - proxysql_mysql_users: config_file: '~/proxysql.cnf' username: 'mysqlboy' state: absent ''' RETURN = ''' stdout: description: The mysql user modified or removed from proxysql returned: On create/update will return the newly modified user, on delete it will return the deleted record. type: dict sample: changed: true msg: Added user to mysql_users state: present user: active: 1 backend: 1 default_hostgroup: 1 default_schema: null fast_forward: 0 frontend: 1 max_connections: 10000 password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER schema_locked: 0 transaction_persistent: 0 use_ssl: 0 username: guest_ro username: guest_ro ''' ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.mysql import mysql_connect, mysql_driver, mysql_driver_fail_msg from ansible.module_utils.six import iteritems from ansible.module_utils._text import to_native # =========================================== # proxysql module specific support methods. # def perform_checks(module): if module.params["login_port"] < 0 \ or module.params["login_port"] > 65535: module.fail_json( msg="login_port must be a valid unix port number (0-65535)" ) if mysql_driver is None: module.fail_json(msg=mysql_driver_fail_msg) def save_config_to_disk(cursor): cursor.execute("SAVE MYSQL USERS TO DISK") return True def load_config_to_runtime(cursor): cursor.execute("LOAD MYSQL USERS TO RUNTIME") return True class ProxySQLUser(object): def __init__(self, module): self.state = module.params["state"] self.save_to_disk = module.params["save_to_disk"] self.load_to_runtime = module.params["load_to_runtime"] self.username = module.params["username"] self.backend = module.params["backend"] self.frontend = module.params["frontend"] config_data_keys = ["password", "active", "use_ssl", "default_hostgroup", "default_schema", "transaction_persistent", "fast_forward", "max_connections"] self.config_data = dict((k, module.params[k]) for k in config_data_keys) def check_user_config_exists(self, cursor): query_string = \ """SELECT count(*) AS `user_count` FROM mysql_users WHERE username = %s AND backend = %s AND frontend = %s""" query_data = \ [self.username, self.backend, self.frontend] cursor.execute(query_string, query_data) check_count = cursor.fetchone() return (int(check_count['user_count']) > 0) def check_user_privs(self, cursor): query_string = \ """SELECT count(*) AS `user_count` FROM mysql_users WHERE username = %s AND backend = %s AND frontend = %s""" query_data = \ [self.username, self.backend, self.frontend] for col, val in iteritems(self.config_data): if val is not None: query_data.append(val) query_string += "\n AND " + col + " = %s" cursor.execute(query_string, query_data) check_count = cursor.fetchone() return (int(check_count['user_count']) > 0) def get_user_config(self, cursor): query_string = \ """SELECT * FROM mysql_users WHERE username = %s AND backend = %s AND frontend = %s""" query_data = \ [self.username, self.backend, self.frontend] cursor.execute(query_string, query_data) user = cursor.fetchone() return user def create_user_config(self, cursor): query_string = \ """INSERT INTO mysql_users ( username, backend, frontend""" cols = 3 query_data = \ [self.username, self.backend, self.frontend] for col, val in iteritems(self.config_data): if val is not None: cols += 1 query_data.append(val) query_string += ",\n" + col query_string += \ (")\n" + "VALUES (" + "%s ," * cols) query_string = query_string[:-2] query_string += ")" cursor.execute(query_string, query_data) return True def update_user_config(self, cursor): query_string = """UPDATE mysql_users""" cols = 0 query_data = [] for col, val in iteritems(self.config_data): if val is not None: cols += 1 query_data.append(val) if cols == 1: query_string += "\nSET " + col + "= %s," else: query_string += "\n " + col + " = %s," query_string = query_string[:-1] query_string += ("\nWHERE username = %s\n AND backend = %s" + "\n AND frontend = %s") query_data.append(self.username) query_data.append(self.backend) query_data.append(self.frontend) cursor.execute(query_string, query_data) return True def delete_user_config(self, cursor): query_string = \ """DELETE FROM mysql_users WHERE username = %s AND backend = %s AND frontend = %s""" query_data = \ [self.username, self.backend, self.frontend] cursor.execute(query_string, query_data) return True def manage_config(self, cursor, state): if state: if self.save_to_disk: save_config_to_disk(cursor) if self.load_to_runtime: load_config_to_runtime(cursor) def create_user(self, check_mode, result, cursor): if not check_mode: result['changed'] = \ self.create_user_config(cursor) result['msg'] = "Added user to mysql_users" result['user'] = \ self.get_user_config(cursor) self.manage_config(cursor, result['changed']) else: result['changed'] = True result['msg'] = ("User would have been added to" + " mysql_users, however check_mode" + " is enabled.") def update_user(self, check_mode, result, cursor): if not check_mode: result['changed'] = \ self.update_user_config(cursor) result['msg'] = "Updated user in mysql_users" result['user'] = \ self.get_user_config(cursor) self.manage_config(cursor, result['changed']) else: result['changed'] = True result['msg'] = ("User would have been updated in" + " mysql_users, however check_mode" + " is enabled.") def delete_user(self, check_mode, result, cursor): if not check_mode: result['user'] = \ self.get_user_config(cursor) result['changed'] = \ self.delete_user_config(cursor) result['msg'] = "Deleted user from mysql_users" self.manage_config(cursor, result['changed']) else: result['changed'] = True result['msg'] = ("User would have been deleted from" + " mysql_users, however check_mode is" + " enabled.") # =========================================== # Module execution. # def main(): module = AnsibleModule( argument_spec=dict( login_user=dict(default=None, type='str'), login_password=dict(default=None, no_log=True, type='str'), login_host=dict(default="127.0.0.1"), login_unix_socket=dict(default=None), login_port=dict(default=6032, type='int'), config_file=dict(default='', type='path'), username=dict(required=True, type='str'), password=dict(no_log=True, type='str'), active=dict(type='bool'), use_ssl=dict(type='bool'), default_hostgroup=dict(type='int'), default_schema=dict(type='str'), transaction_persistent=dict(type='bool'), fast_forward=dict(type='bool'), backend=dict(default=True, type='bool'), frontend=dict(default=True, type='bool'), max_connections=dict(type='int'), state=dict(default='present', choices=['present', 'absent']), save_to_disk=dict(default=True, type='bool'), load_to_runtime=dict(default=True, type='bool') ), supports_check_mode=True ) perform_checks(module) login_user = module.params["login_user"] login_password = module.params["login_password"] config_file = module.params["config_file"] cursor = None try: cursor = mysql_connect(module, login_user, login_password, config_file, cursor_class=mysql_driver.cursors.DictCursor) except mysql_driver.Error as e: module.fail_json( msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e) ) proxysql_user = ProxySQLUser(module) result = {} result['state'] = proxysql_user.state if proxysql_user.username: result['username'] = proxysql_user.username if proxysql_user.state == "present": try: if not proxysql_user.check_user_privs(cursor): if not proxysql_user.check_user_config_exists(cursor): proxysql_user.create_user(module.check_mode, result, cursor) else: proxysql_user.update_user(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The user already exists in mysql_users" + " and doesn't need to be updated.") result['user'] = \ proxysql_user.get_user_config(cursor) except mysql_driver.Error as e: module.fail_json( msg="unable to modify user.. %s" % to_native(e) ) elif proxysql_user.state == "absent": try: if proxysql_user.check_user_config_exists(cursor): proxysql_user.delete_user(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The user is already absent from the" + " mysql_users memory configuration") except mysql_driver.Error as e: module.fail_json( msg="unable to remove user.. %s" % to_native(e) ) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
hongliuliao/log_monitor
dependency/googletest/googlemock/test/gmock_output_test.py
986
5999
#!/usr/bin/env python # # Copyright 2008, 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. """Tests the text output of Google C++ Mocking Framework. SYNOPSIS gmock_output_test.py --build_dir=BUILD/DIR --gengolden # where BUILD/DIR contains the built gmock_output_test_ file. gmock_output_test.py --gengolden gmock_output_test.py """ __author__ = 'wan@google.com (Zhanyong Wan)' import os import re import sys import gmock_test_utils # The flag for generating the golden file GENGOLDEN_FLAG = '--gengolden' PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_output_test_') COMMAND = [PROGRAM_PATH, '--gtest_stack_trace_depth=0', '--gtest_print_time=0'] GOLDEN_NAME = 'gmock_output_test_golden.txt' GOLDEN_PATH = os.path.join(gmock_test_utils.GetSourceDir(), GOLDEN_NAME) def ToUnixLineEnding(s): """Changes all Windows/Mac line endings in s to UNIX line endings.""" return s.replace('\r\n', '\n').replace('\r', '\n') def RemoveReportHeaderAndFooter(output): """Removes Google Test result report's header and footer from the output.""" output = re.sub(r'.*gtest_main.*\n', '', output) output = re.sub(r'\[.*\d+ tests.*\n', '', output) output = re.sub(r'\[.* test environment .*\n', '', output) output = re.sub(r'\[=+\] \d+ tests .* ran.*', '', output) output = re.sub(r'.* FAILED TESTS\n', '', output) return output def RemoveLocations(output): """Removes all file location info from a Google Test program's output. Args: output: the output of a Google Test program. Returns: output with all file location info (in the form of 'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or 'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by 'FILE:#: '. """ return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\:', 'FILE:#:', output) def NormalizeErrorMarker(output): """Normalizes the error marker, which is different on Windows vs on Linux.""" return re.sub(r' error: ', ' Failure\n', output) def RemoveMemoryAddresses(output): """Removes memory addresses from the test output.""" return re.sub(r'@\w+', '@0x#', output) def RemoveTestNamesOfLeakedMocks(output): """Removes the test names of leaked mock objects from the test output.""" return re.sub(r'\(used in test .+\) ', '', output) def GetLeakyTests(output): """Returns a list of test names that leak mock objects.""" # findall() returns a list of all matches of the regex in output. # For example, if '(used in test FooTest.Bar)' is in output, the # list will contain 'FooTest.Bar'. return re.findall(r'\(used in test (.+)\)', output) def GetNormalizedOutputAndLeakyTests(output): """Normalizes the output of gmock_output_test_. Args: output: The test output. Returns: A tuple (the normalized test output, the list of test names that have leaked mocks). """ output = ToUnixLineEnding(output) output = RemoveReportHeaderAndFooter(output) output = NormalizeErrorMarker(output) output = RemoveLocations(output) output = RemoveMemoryAddresses(output) return (RemoveTestNamesOfLeakedMocks(output), GetLeakyTests(output)) def GetShellCommandOutput(cmd): """Runs a command in a sub-process, and returns its STDOUT in a string.""" return gmock_test_utils.Subprocess(cmd, capture_stderr=False).output def GetNormalizedCommandOutputAndLeakyTests(cmd): """Runs a command and returns its normalized output and a list of leaky tests. Args: cmd: the shell command. """ # Disables exception pop-ups on Windows. os.environ['GTEST_CATCH_EXCEPTIONS'] = '1' return GetNormalizedOutputAndLeakyTests(GetShellCommandOutput(cmd)) class GMockOutputTest(gmock_test_utils.TestCase): def testOutput(self): (output, leaky_tests) = GetNormalizedCommandOutputAndLeakyTests(COMMAND) golden_file = open(GOLDEN_PATH, 'rb') golden = golden_file.read() golden_file.close() # The normalized output should match the golden file. self.assertEquals(golden, output) # The raw output should contain 2 leaked mock object errors for # test GMockOutputTest.CatchesLeakedMocks. self.assertEquals(['GMockOutputTest.CatchesLeakedMocks', 'GMockOutputTest.CatchesLeakedMocks'], leaky_tests) if __name__ == '__main__': if sys.argv[1:] == [GENGOLDEN_FLAG]: (output, _) = GetNormalizedCommandOutputAndLeakyTests(COMMAND) golden_file = open(GOLDEN_PATH, 'wb') golden_file.write(output) golden_file.close() else: gmock_test_utils.Main()
apache-2.0
ogrisel/numpy
numpy/polynomial/tests/test_polyutils.py
9
2958
"""Tests for polyutils module. """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.polynomial.polyutils as pu from numpy.testing import * class TestMisc(TestCase) : def test_trimseq(self) : for i in range(5) : tgt = [1] res = pu.trimseq([1] + [0]*5) assert_equal(res, tgt) def test_as_series(self) : # check exceptions assert_raises(ValueError, pu.as_series, [[]]) assert_raises(ValueError, pu.as_series, [[[1, 2]]]) assert_raises(ValueError, pu.as_series, [[1], ['a']]) # check common types types = ['i', 'd', 'O'] for i in range(len(types)) : for j in range(i) : ci = np.ones(1, types[i]) cj = np.ones(1, types[j]) [resi, resj] = pu.as_series([ci, cj]) assert_(resi.dtype.char == resj.dtype.char) assert_(resj.dtype.char == types[i]) def test_trimcoef(self) : coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, pu.trimcoef, coef, -1) # Test results assert_equal(pu.trimcoef(coef), coef[:-1]) assert_equal(pu.trimcoef(coef, 1), coef[:-3]) assert_equal(pu.trimcoef(coef, 2), [0]) class TestDomain(TestCase) : def test_getdomain(self) : # test for real values x = [1, 10, 3, -1] tgt = [-1, 10] res = pu.getdomain(x) assert_almost_equal(res, tgt) # test for complex values x = [1 + 1j, 1 - 1j, 0, 2] tgt = [-1j, 2 + 1j] res = pu.getdomain(x) assert_almost_equal(res, tgt) def test_mapdomain(self) : # test for real values dom1 = [0, 4] dom2 = [1, 3] tgt = dom2 res = pu. mapdomain(dom1, dom1, dom2) assert_almost_equal(res, tgt) # test for complex values dom1 = [0 - 1j, 2 + 1j] dom2 = [-2, 2] tgt = dom2 x = dom1 res = pu.mapdomain(x, dom1, dom2) assert_almost_equal(res, tgt) # test for multidimensional arrays dom1 = [0, 4] dom2 = [1, 3] tgt = np.array([dom2, dom2]) x = np.array([dom1, dom1]) res = pu.mapdomain(x, dom1, dom2) assert_almost_equal(res, tgt) # test that subtypes are preserved. dom1 = [0, 4] dom2 = [1, 3] x = np.matrix([dom1, dom1]) res = pu.mapdomain(x, dom1, dom2) assert_(isinstance(res, np.matrix)) def test_mapparms(self) : # test for real values dom1 = [0, 4] dom2 = [1, 3] tgt = [1, .5] res = pu. mapparms(dom1, dom2) assert_almost_equal(res, tgt) # test for complex values dom1 = [0 - 1j, 2 + 1j] dom2 = [-2, 2] tgt = [-1 + 1j, 1 - 1j] res = pu.mapparms(dom1, dom2) assert_almost_equal(res, tgt)
bsd-3-clause
Lab603/PicEncyclopedias
jni-build/jni-build/jni/include/tensorflow/contrib/learn/python/learn/tests/multioutput_test.py
5
1679
# 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. # ============================================================================== """Multi-output tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import random import numpy as np import tensorflow as tf from tensorflow.contrib.learn.python import learn from tensorflow.contrib.learn.python.learn.estimators._sklearn import mean_squared_error class MultiOutputTest(tf.test.TestCase): """Multi-output tests.""" def testMultiRegression(self): random.seed(42) rng = np.random.RandomState(1) x = np.sort(200 * rng.rand(100, 1) - 100, axis=0) y = np.array([np.pi * np.sin(x).ravel(), np.pi * np.cos(x).ravel()]).T regressor = learn.TensorFlowLinearRegressor( feature_columns=learn.infer_real_valued_columns_from_input(x), learning_rate=0.01, target_dimension=2) regressor.fit(x, y) score = mean_squared_error(regressor.predict(x), y) self.assertLess(score, 10, "Failed with score = {0}".format(score)) if __name__ == "__main__": tf.test.main()
mit
cmdunkers/DeeperMind
PythonEnv/lib/python2.7/site-packages/setuptools/command/setopt.py
458
5080
from distutils.util import convert_path from distutils import log from distutils.errors import DistutilsOptionError import distutils import os from setuptools import Command __all__ = ['config_file', 'edit_config', 'option_base', 'setopt'] def config_file(kind="local"): """Get the filename of the distutils, local, global, or per-user config `kind` must be one of "local", "global", or "user" """ if kind == 'local': return 'setup.cfg' if kind == 'global': return os.path.join( os.path.dirname(distutils.__file__), 'distutils.cfg' ) if kind == 'user': dot = os.name == 'posix' and '.' or '' return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot)) raise ValueError( "config_file() type must be 'local', 'global', or 'user'", kind ) def edit_config(filename, settings, dry_run=False): """Edit a configuration file to include `settings` `settings` is a dictionary of dictionaries or ``None`` values, keyed by command/section name. A ``None`` value means to delete the entire section, while a dictionary lists settings to be changed or deleted in that section. A setting of ``None`` means to delete that setting. """ from setuptools.compat import ConfigParser log.debug("Reading configuration from %s", filename) opts = ConfigParser.RawConfigParser() opts.read([filename]) for section, options in settings.items(): if options is None: log.info("Deleting section [%s] from %s", section, filename) opts.remove_section(section) else: if not opts.has_section(section): log.debug("Adding new section [%s] to %s", section, filename) opts.add_section(section) for option, value in options.items(): if value is None: log.debug( "Deleting %s.%s from %s", section, option, filename ) opts.remove_option(section, option) if not opts.options(section): log.info("Deleting empty [%s] section from %s", section, filename) opts.remove_section(section) else: log.debug( "Setting %s.%s to %r in %s", section, option, value, filename ) opts.set(section, option, value) log.info("Writing %s", filename) if not dry_run: with open(filename, 'w') as f: opts.write(f) class option_base(Command): """Abstract base class for commands that mess with config files""" user_options = [ ('global-config', 'g', "save options to the site-wide distutils.cfg file"), ('user-config', 'u', "save options to the current user's pydistutils.cfg file"), ('filename=', 'f', "configuration file to use (default=setup.cfg)"), ] boolean_options = [ 'global-config', 'user-config', ] def initialize_options(self): self.global_config = None self.user_config = None self.filename = None def finalize_options(self): filenames = [] if self.global_config: filenames.append(config_file('global')) if self.user_config: filenames.append(config_file('user')) if self.filename is not None: filenames.append(self.filename) if not filenames: filenames.append(config_file('local')) if len(filenames) > 1: raise DistutilsOptionError( "Must specify only one configuration file option", filenames ) self.filename, = filenames class setopt(option_base): """Save command-line options to a file""" description = "set an option in setup.cfg or another config file" user_options = [ ('command=', 'c', 'command to set an option for'), ('option=', 'o', 'option to set'), ('set-value=', 's', 'value of the option'), ('remove', 'r', 'remove (unset) the value'), ] + option_base.user_options boolean_options = option_base.boolean_options + ['remove'] def initialize_options(self): option_base.initialize_options(self) self.command = None self.option = None self.set_value = None self.remove = None def finalize_options(self): option_base.finalize_options(self) if self.command is None or self.option is None: raise DistutilsOptionError("Must specify --command *and* --option") if self.set_value is None and not self.remove: raise DistutilsOptionError("Must specify --set-value or --remove") def run(self): edit_config( self.filename, { self.command: {self.option.replace('-', '_'): self.set_value} }, self.dry_run )
bsd-3-clause
RatulGhosh/pybrain
pybrain/rl/explorers/discrete/discretesde.py
26
2189
__author__ = "Thomas Rueckstiess, ruecksti@in.tum.de" from pybrain.rl.explorers.discrete.discrete import DiscreteExplorer from pybrain.rl.learners.valuebased.interface import ActionValueTable, ActionValueNetwork from copy import deepcopy from numpy import random, array class DiscreteStateDependentExplorer(DiscreteExplorer): """ A discrete explorer, that directly manipulates the ActionValue estimator (table or network) and keeps the changes fixed for one full episode (if episodic) or slowly changes it over time. TODO: currently only implemented for episodes """ def __init__(self, epsilon = 0.2, decay = 0.9998): """ TODO: the epsilon and decay parameters are currently not implemented. """ DiscreteExplorer.__init__(self) self.state = None def _setModule(self, module): """ Tell the explorer the module. """ self._module = module # copy the original module for exploration self.explorerModule = deepcopy(module) def _getModule(self): return self._module module = property(_getModule, _setModule) def activate(self, state, action): """ Save the current state for state-dependent exploration. """ self.state = state return DiscreteExplorer.activate(self, state, action) def _forwardImplementation(self, inbuf, outbuf): """ Activate the copied module instead of the original and feed it with the current state. """ if random.random() < 0.001: outbuf[:] = array([random.randint(self.module.numActions)]) else: outbuf[:] = self.explorerModule.activate(self.state) def newEpisode(self): """ Inform the explorer about the start of a new episode. """ self.explorerModule = deepcopy(self.module) if isinstance(self.explorerModule, ActionValueNetwork): self.explorerModule.network.mutationStd = 0.01 self.explorerModule.network.mutate() elif isinstance(self.explorerModule, ActionValueTable): self.explorerModule.mutationStd = 0.01 self.explorerModule.mutate()
bsd-3-clause
urosgruber/dd-agent
checks.d/mesos_master.py
5
13366
"""Mesos Master check Collects metrics from mesos master node, only the leader is sending metrics. """ # 3rd party import requests # project from checks import AgentCheck, CheckException class MesosMaster(AgentCheck): GAUGE = AgentCheck.gauge MONOTONIC_COUNT = AgentCheck.monotonic_count SERVICE_CHECK_NAME = "mesos_master.can_connect" service_check_needed = True FRAMEWORK_METRICS = { 'cpus' : ('mesos.framework.cpu', GAUGE), 'mem' : ('mesos.framework.mem', GAUGE), 'disk' : ('mesos.framework.disk', GAUGE), } ROLE_RESOURCES_METRICS = { 'cpus' : ('mesos.role.cpu', GAUGE), 'mem' : ('mesos.role.mem', GAUGE), 'disk' : ('mesos.role.disk', GAUGE), } # These metrics are aggregated only on the elected master CLUSTER_TASKS_METRICS = { 'master/tasks_error' : ('mesos.cluster.tasks_error', GAUGE), 'master/tasks_failed' : ('mesos.cluster.tasks_failed', MONOTONIC_COUNT), 'master/tasks_finished' : ('mesos.cluster.tasks_finished', MONOTONIC_COUNT), 'master/tasks_killed' : ('mesos.cluster.tasks_killed', MONOTONIC_COUNT), 'master/tasks_lost' : ('mesos.cluster.tasks_lost', MONOTONIC_COUNT), 'master/tasks_running' : ('mesos.cluster.tasks_running', GAUGE), 'master/tasks_staging' : ('mesos.cluster.tasks_staging', GAUGE), 'master/tasks_starting' : ('mesos.cluster.tasks_starting', GAUGE), } # These metrics are aggregated only on the elected master CLUSTER_SLAVES_METRICS = { 'master/slave_registrations' : ('mesos.cluster.slave_registrations', GAUGE), 'master/slave_removals' : ('mesos.cluster.slave_removals', GAUGE), 'master/slave_reregistrations' : ('mesos.cluster.slave_reregistrations', GAUGE), 'master/slave_shutdowns_canceled' : ('mesos.cluster.slave_shutdowns_canceled', GAUGE), 'master/slave_shutdowns_scheduled' : ('mesos.cluster.slave_shutdowns_scheduled', GAUGE), 'master/slaves_active' : ('mesos.cluster.slaves_active', GAUGE), 'master/slaves_connected' : ('mesos.cluster.slaves_connected', GAUGE), 'master/slaves_disconnected' : ('mesos.cluster.slaves_disconnected', GAUGE), 'master/slaves_inactive' : ('mesos.cluster.slaves_inactive', GAUGE), 'master/recovery_slave_removals' : ('mesos.cluster.recovery_slave_removals', GAUGE), } # These metrics are aggregated only on the elected master CLUSTER_RESOURCES_METRICS = { 'master/cpus_percent' : ('mesos.cluster.cpus_percent', GAUGE), 'master/cpus_total' : ('mesos.cluster.cpus_total', GAUGE), 'master/cpus_used' : ('mesos.cluster.cpus_used', GAUGE), 'master/disk_percent' : ('mesos.cluster.disk_percent', GAUGE), 'master/disk_total' : ('mesos.cluster.disk_total', GAUGE), 'master/disk_used' : ('mesos.cluster.disk_used', GAUGE), 'master/mem_percent' : ('mesos.cluster.mem_percent', GAUGE), 'master/mem_total' : ('mesos.cluster.mem_total', GAUGE), 'master/mem_used' : ('mesos.cluster.mem_used', GAUGE), } # These metrics are aggregated only on the elected master CLUSTER_REGISTRAR_METRICS = { 'registrar/queued_operations' : ('mesos.registrar.queued_operations', GAUGE), 'registrar/registry_size_bytes' : ('mesos.registrar.registry_size_bytes', GAUGE), 'registrar/state_fetch_ms' : ('mesos.registrar.state_fetch_ms', GAUGE), 'registrar/state_store_ms' : ('mesos.registrar.state_store_ms', GAUGE), 'registrar/state_store_ms/count' : ('mesos.registrar.state_store_ms.count', GAUGE), 'registrar/state_store_ms/max' : ('mesos.registrar.state_store_ms.max', GAUGE), 'registrar/state_store_ms/min' : ('mesos.registrar.state_store_ms.min', GAUGE), 'registrar/state_store_ms/p50' : ('mesos.registrar.state_store_ms.p50', GAUGE), 'registrar/state_store_ms/p90' : ('mesos.registrar.state_store_ms.p90', GAUGE), 'registrar/state_store_ms/p95' : ('mesos.registrar.state_store_ms.p95', GAUGE), 'registrar/state_store_ms/p99' : ('mesos.registrar.state_store_ms.p99', GAUGE), 'registrar/state_store_ms/p999' : ('mesos.registrar.state_store_ms.p999', GAUGE), 'registrar/state_store_ms/p9999' : ('mesos.registrar.state_store_ms.p9999', GAUGE), } # These metrics are aggregated only on the elected master CLUSTER_FRAMEWORK_METRICS = { 'master/frameworks_active' : ('mesos.cluster.frameworks_active', GAUGE), 'master/frameworks_connected' : ('mesos.cluster.frameworks_connected', GAUGE), 'master/frameworks_disconnected' : ('mesos.cluster.frameworks_disconnected', GAUGE), 'master/frameworks_inactive' : ('mesos.cluster.frameworks_inactive', GAUGE), } # These metrics are aggregated on all nodes in the cluster SYSTEM_METRICS = { 'system/cpus_total' : ('mesos.stats.system.cpus_total', GAUGE), 'system/load_15min' : ('mesos.stats.system.load_15min', GAUGE), 'system/load_1min' : ('mesos.stats.system.load_1min', GAUGE), 'system/load_5min' : ('mesos.stats.system.load_5min', GAUGE), 'system/mem_free_bytes' : ('mesos.stats.system.mem_free_bytes', GAUGE), 'system/mem_total_bytes' : ('mesos.stats.system.mem_total_bytes', GAUGE), 'master/elected' : ('mesos.stats.elected', GAUGE), 'master/uptime_secs' : ('mesos.stats.uptime_secs', GAUGE), } # These metrics are aggregated only on the elected master STATS_METRICS = { 'master/dropped_messages' : ('mesos.cluster.dropped_messages', GAUGE), 'master/outstanding_offers' : ('mesos.cluster.outstanding_offers', GAUGE), 'master/event_queue_dispatches' : ('mesos.cluster.event_queue_dispatches', GAUGE), 'master/event_queue_http_requests' : ('mesos.cluster.event_queue_http_requests', GAUGE), 'master/event_queue_messages' : ('mesos.cluster.event_queue_messages', GAUGE), 'master/invalid_framework_to_executor_messages' : ('mesos.cluster.invalid_framework_to_executor_messages', GAUGE), 'master/invalid_status_update_acknowledgements' : ('mesos.cluster.invalid_status_update_acknowledgements', GAUGE), 'master/invalid_status_updates' : ('mesos.cluster.invalid_status_updates', GAUGE), 'master/valid_framework_to_executor_messages' : ('mesos.cluster.valid_framework_to_executor_messages', GAUGE), 'master/valid_status_update_acknowledgements' : ('mesos.cluster.valid_status_update_acknowledgements', GAUGE), 'master/valid_status_updates' : ('mesos.cluster.valid_status_updates', GAUGE), } def _get_json(self, url, timeout): tags = ["url:%s" % url] msg = None status = None try: r = requests.get(url, timeout=timeout) if r.status_code != 200: status = AgentCheck.CRITICAL msg = "Got %s when hitting %s" % (r.status_code, url) else: status = AgentCheck.OK msg = "Mesos master instance detected at %s " % url except requests.exceptions.Timeout as e: # If there's a timeout msg = "%s seconds timeout when hitting %s" % (timeout, url) status = AgentCheck.CRITICAL except Exception as e: msg = str(e) status = AgentCheck.CRITICAL finally: if self.service_check_needed: self.service_check(self.SERVICE_CHECK_NAME, status, tags=tags, message=msg) self.service_check_needed = False if status is AgentCheck.CRITICAL: self.service_check(self.SERVICE_CHECK_NAME, status, tags=tags, message=msg) raise CheckException("Cannot connect to mesos, please check your configuration.") if r.encoding is None: r.encoding = 'UTF8' return r.json() def _get_master_state(self, url, timeout): return self._get_json(url + '/state.json', timeout) def _get_master_stats(self, url, timeout): if self.version >= [0, 22, 0]: endpoint = '/metrics/snapshot' else: endpoint = '/stats.json' return self._get_json(url + endpoint, timeout) def _get_master_roles(self, url, timeout): return self._get_json(url + '/roles.json', timeout) def _check_leadership(self, url, timeout): state_metrics = self._get_master_state(url, timeout) self.leader = False if state_metrics is not None: self.version = map(int, state_metrics['version'].split('.')) if state_metrics['leader'] == state_metrics['pid']: self.leader = True return state_metrics def check(self, instance): if 'url' not in instance: raise Exception('Mesos instance missing "url" value.') url = instance['url'] instance_tags = instance.get('tags', []) default_timeout = self.init_config.get('default_timeout', 5) timeout = float(instance.get('timeout', default_timeout)) state_metrics = self._check_leadership(url, timeout) if state_metrics: tags = [ 'mesos_pid:{0}'.format(state_metrics['pid']), 'mesos_node:master', ] if 'cluster' in state_metrics: tags.append('mesos_cluster:{0}'.format(state_metrics['cluster'])) tags += instance_tags if self.leader: self.GAUGE('mesos.cluster.total_frameworks', len(state_metrics['frameworks']), tags=tags) for framework in state_metrics['frameworks']: framework_tags = ['framework_name:' + framework['name']] + tags self.GAUGE('mesos.framework.total_tasks', len(framework['tasks']), tags=framework_tags) resources = framework['used_resources'] for key_name, (metric_name, metric_func) in self.FRAMEWORK_METRICS.iteritems(): metric_func(self, metric_name, resources[key_name], tags=framework_tags) role_metrics = self._get_master_roles(url, timeout) if role_metrics is not None: for role in role_metrics['roles']: role_tags = ['mesos_role:' + role['name']] + tags self.GAUGE('mesos.role.frameworks.count', len(role['frameworks']), tags=role_tags) self.GAUGE('mesos.role.weight', role['weight'], tags=role_tags) for key_name, (metric_name, metric_func) in self.ROLE_RESOURCES_METRICS.iteritems(): metric_func(self, metric_name, role['resources'][key_name], tags=role_tags) stats_metrics = self._get_master_stats(url, timeout) if stats_metrics is not None: metrics = [self.SYSTEM_METRICS] if self.leader: metrics += [self.CLUSTER_TASKS_METRICS, self.CLUSTER_SLAVES_METRICS, self.CLUSTER_RESOURCES_METRICS, self.CLUSTER_REGISTRAR_METRICS, self.CLUSTER_FRAMEWORK_METRICS, self.STATS_METRICS] for m in metrics: for key_name, (metric_name, metric_func) in m.iteritems(): metric_func(self, metric_name, stats_metrics[key_name], tags=tags) self.service_check_needed = True
bsd-3-clause
wavefrontHQ/python-client
wavefront_api_client/models/response_container_service_account.py
1
4422
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API documentation you must add the header \"Authorization: Bearer &lt;&lt;API-TOKEN&gt;&gt;\" to your HTTP requests.</p> # noqa: E501 OpenAPI spec version: v2 Contact: chitimba@wavefront.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ResponseContainerServiceAccount(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'response': 'ServiceAccount', 'status': 'ResponseStatus' } attribute_map = { 'response': 'response', 'status': 'status' } def __init__(self, response=None, status=None): # noqa: E501 """ResponseContainerServiceAccount - a model defined in Swagger""" # noqa: E501 self._response = None self._status = None self.discriminator = None if response is not None: self.response = response self.status = status @property def response(self): """Gets the response of this ResponseContainerServiceAccount. # noqa: E501 :return: The response of this ResponseContainerServiceAccount. # noqa: E501 :rtype: ServiceAccount """ return self._response @response.setter def response(self, response): """Sets the response of this ResponseContainerServiceAccount. :param response: The response of this ResponseContainerServiceAccount. # noqa: E501 :type: ServiceAccount """ self._response = response @property def status(self): """Gets the status of this ResponseContainerServiceAccount. # noqa: E501 :return: The status of this ResponseContainerServiceAccount. # noqa: E501 :rtype: ResponseStatus """ return self._status @status.setter def status(self, status): """Sets the status of this ResponseContainerServiceAccount. :param status: The status of this ResponseContainerServiceAccount. # noqa: E501 :type: ResponseStatus """ if status is None: raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501 self._status = status def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ResponseContainerServiceAccount, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ResponseContainerServiceAccount): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
apache-2.0
wdv4758h/ZipPy
edu.uci.python.test/regressiontests/test_grammar.py
1
33140
# Python test set -- part 1, grammar. # This just tests whether the parser accepts them all. #from test.support import run_unittest, check_syntax_error # Currently test.support cannot be imported import unittest #import sys # testing import * #from sys import * class TokenTests(unittest.TestCase): def testBackslash(self): # Backslash means line continuation: x = 1 \ + 1 self.assertEqual(x, 2, 'backslash for line continuation') # Backslash does not means continuation in comments :\ x = 0 self.assertEqual(x, 0, 'backslash ending comment') def testPlainIntegers(self): self.assertEqual(type(000), type(0)) self.assertEqual(0xff, 255) self.assertEqual(0o377, 255) self.assertEqual(2147483647, 0o17777777777) self.assertEqual(0b1001, 9) # "0x" is not a valid literal self.assertRaises(SyntaxError, eval, "0x") from sys import maxsize if maxsize == 2147483647: self.assertEqual(-2147483647-1, -0o20000000000) # XXX -2147483648 self.assertTrue(0o37777777777 > 0) self.assertTrue(0xffffffff > 0) self.assertTrue(0b1111111111111111111111111111111 > 0) for s in ('2147483648', '0o40000000000', '0x100000000', '0b10000000000000000000000000000000'): try: x = eval(s) except OverflowError: self.fail("OverflowError on huge integer literal %r" % s) elif maxsize == 9223372036854775807: self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000) self.assertTrue(0o1777777777777777777777 > 0) self.assertTrue(0xffffffffffffffff > 0) self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0) for s in '9223372036854775808', '0o2000000000000000000000', \ '0x10000000000000000', \ '0b100000000000000000000000000000000000000000000000000000000000000': try: x = eval(s) except OverflowError: self.fail("OverflowError on huge integer literal %r" % s) else: self.fail('Weird maxsize value %r' % maxsize) def testLongIntegers(self): x = 0 x = 0xffffffffffffffff x = 0Xffffffffffffffff x = 0o77777777777777777 x = 0O77777777777777777 x = 123456789012345678901234567890 x = 0b100000000000000000000000000000000000000000000000000000000000000000000 x = 0B111111111111111111111111111111111111111111111111111111111111111111111 def testFloats(self): x = 3.14 x = 314. x = 0.314 # XXX x = 000.314 x = .314 x = 3e14 x = 3E14 x = 3e-14 x = 3e+14 x = 3.e14 x = .3e14 x = 3.1e4 def testStringLiterals(self): x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y) x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39) x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34) x = "doesn't \"shrink\" does it" y = 'doesn\'t "shrink" does it' self.assertTrue(len(x) == 24 and x == y) x = "does \"shrink\" doesn't it" y = 'does "shrink" doesn\'t it' self.assertTrue(len(x) == 24 and x == y) x = """ The "quick" brown fox jumps over the 'lazy' dog. """ y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' self.assertEqual(x, y) y = ''' The "quick" brown fox jumps over the 'lazy' dog. ''' self.assertEqual(x, y) y = "\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the 'lazy' dog.\n\ " self.assertEqual(x, y) y = '\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the \'lazy\' dog.\n\ ' self.assertEqual(x, y) # def testEllipsis(self): # x = ... # self.assertTrue(x is Ellipsis) # self.assertRaises(SyntaxError, eval, ".. .") class GrammarTests(unittest.TestCase): # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE # XXX can't test in a script -- this rule is only used when interactive # file_input: (NEWLINE | stmt)* ENDMARKER # Being tested as this very moment this very module # expr_input: testlist NEWLINE # XXX Hard to test -- used only in calls to input() def testEvalInput(self): # testlist ENDMARKER x = eval('1, 0 or 1') def testFuncdef(self): ### [decorators] 'def' NAME parameters ['->' test] ':' suite ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE ### decorators: decorator+ ### parameters: '(' [typedargslist] ')' ### typedargslist: ((tfpdef ['=' test] ',')* ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) ### tfpdef: NAME [':' test] ### varargslist: ((vfpdef ['=' test] ',')* ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) ### vfpdef: NAME def f1(): pass f1() f1(*()) f1(*(), **{}) def f2(one_argument): pass def f3(two, arguments): pass self.assertEqual(f2.__code__.co_varnames, ('one_argument',)) self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments')) def a1(one_arg,): pass def a2(two, args,): pass def v0(*rest): pass def v1(a, *rest): pass def v2(a, b, *rest): pass f1() f2(1) f2(1,) f3(1, 2) f3(1, 2,) v0() v0(1) v0(1,) v0(1,2) v0(1,2,3,4,5,6,7,8,9,0) v1(1) v1(1,) v1(1,2) v1(1,2,3) v1(1,2,3,4,5,6,7,8,9,0) v2(1,2) v2(1,2,3) v2(1,2,3,4) v2(1,2,3,4,5,6,7,8,9,0) def d01(a=1): pass d01() d01(1) d01(*(1,)) d01(**{'a':2}) def d11(a, b=1): pass d11(1) d11(1, 2) d11(1, **{'b':2}) def d21(a, b, c=1): pass d21(1, 2) d21(1, 2, 3) d21(*(1, 2, 3)) d21(1, *(2, 3)) d21(1, 2, *(3,)) d21(1, 2, **{'c':3}) def d02(a=1, b=2): pass d02() d02(1) d02(1, 2) d02(*(1, 2)) d02(1, *(2,)) d02(1, **{'b':2}) d02(**{'a': 1, 'b': 2}) def d12(a, b=1, c=2): pass d12(1) d12(1, 2) d12(1, 2, 3) def d22(a, b, c=1, d=2): pass d22(1, 2) d22(1, 2, 3) d22(1, 2, 3, 4) def d01v(a=1, *rest): pass d01v() d01v(1) d01v(1, 2) d01v(*(1, 2, 3, 4)) d01v(*(1,)) d01v(**{'a':2}) def d11v(a, b=1, *rest): pass d11v(1) d11v(1, 2) d11v(1, 2, 3) def d21v(a, b, c=1, *rest): pass d21v(1, 2) d21v(1, 2, 3) d21v(1, 2, 3, 4) d21v(*(1, 2, 3, 4)) d21v(1, 2, **{'c': 3}) def d02v(a=1, b=2, *rest): pass d02v() d02v(1) d02v(1, 2) d02v(1, 2, 3) d02v(1, *(2, 3, 4)) d02v(**{'a': 1, 'b': 2}) def d12v(a, b=1, c=2, *rest): pass d12v(1) d12v(1, 2) d12v(1, 2, 3) d12v(1, 2, 3, 4) d12v(*(1, 2, 3, 4)) d12v(1, 2, *(3, 4, 5)) d12v(1, *(2,), **{'c': 3}) def d22v(a, b, c=1, d=2, *rest): pass d22v(1, 2) d22v(1, 2, 3) d22v(1, 2, 3, 4) d22v(1, 2, 3, 4, 5) d22v(*(1, 2, 3, 4)) d22v(1, 2, *(3, 4, 5)) d22v(1, *(2, 3), **{'d': 4}) # keyword argument type tests try: str('x', **{b'foo':1 }) except TypeError: pass else: self.fail('Bytes should not work as keyword argument names') # keyword only argument tests # def pos0key1(*, key): return key # pos0key1(key=100) # def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2 # pos2key2(1, 2, k1=100) # pos2key2(1, 2, k1=100, k2=200) # pos2key2(1, 2, k2=100, k1=200) # def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg # pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200) # pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100) # keyword arguments after *arglist def f(*args, **kwargs): return args, kwargs self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), {'x':2, 'y':5})) self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)") self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") # argument annotation tests # def f(x) -> list: pass # self.assertEqual(f.__annotations__, {'return': list}) # def f(x:int): pass # self.assertEqual(f.__annotations__, {'x': int}) # def f(*x:str): pass # self.assertEqual(f.__annotations__, {'x': str}) # def f(**x:float): pass # self.assertEqual(f.__annotations__, {'x': float}) # def f(x, y:1+2): pass # self.assertEqual(f.__annotations__, {'y': 3}) # def f(a, b:1, c:2, d): pass # self.assertEqual(f.__annotations__, {'b': 1, 'c': 2}) # def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass # self.assertEqual(f.__annotations__, # {'b': 1, 'c': 2, 'e': 3, 'g': 6}) # def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10, # **k:11) -> 12: pass # self.assertEqual(f.__annotations__, # {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, # 'k': 11, 'return': 12}) # Check for SF Bug #1697248 - mixing decorators and a return annotation # def null(x): return x # @null # def f(x) -> list: pass # self.assertEqual(f.__annotations__, {'return': list}) # # # test MAKE_CLOSURE with a variety of oparg's # closure = 1 # def f(): return closure # def f(x=1): return closure # def f(*, k=1): return closure # def f() -> int: return closure # Check ast errors in *args and *kwargs # check_syntax_error(self, "f(*g(1=2))") # Currently test.support module is not supported, so check_syntax_error is handled as the following self.assertRaises(SyntaxError, compile, "f(*g(1=2))", '<test string>', 'exec') # check_syntax_error(self, "f(**g(1=2))") self.assertRaises(SyntaxError, compile, "f(**g(1=2))", '<test string>', 'exec') def testLambdef(self): ### lambdef: 'lambda' [varargslist] ':' test l1 = lambda : 0 self.assertEqual(l1(), 0) l2 = lambda : a[d] # XXX just testing the expression l3 = lambda : [2 < x for x in [-1, 3, 0]] self.assertEqual(l3(), [0, 1, 0]) l4 = lambda x = lambda y = lambda z=1 : z : y() : x() self.assertEqual(l4(), 1) l5 = lambda x, y, z=2: x + y + z self.assertEqual(l5(1, 2), 5) self.assertEqual(l5(1, 2, 3), 6) # check_syntax_error(self, "lambda x: x = 2") # Currently test.support module is not supported, so check_syntax_error is handled as the following self.assertRaises(SyntaxError, compile, "lambda x: x = 2", '<test string>', 'exec') # check_syntax_error(self, "lambda (None,): None") self.assertRaises(SyntaxError, compile, "lambda (None,): None", '<test string>', 'exec') # l6 = lambda x, y, *, k=20: x+y+k # self.assertEqual(l6(1,2), 1+2+20) # self.assertEqual(l6(1,2,k=10), 1+2+10) ### stmt: simple_stmt | compound_stmt # Tested below def testSimpleStmt(self): ### simple_stmt: small_stmt (';' small_stmt)* [';'] x = 1; pass; del x def foo(): # verify statements that end with semi-colons x = 1; pass; del x; foo() ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt # Tested below def testExprStmt(self): # (exprlist '=')* exprlist 1 1, 2, 3 x = 1 x = 1, 2, 3 x = y = z = 1, 2, 3 x, y, z = 1, 2, 3 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) # check_syntax_error(self, "x + 1 = 1") # Currently test.support module is not supported, so check_syntax_error is handled as the following self.assertRaises(SyntaxError, compile, "x + 1 = 1", '<test string>', 'exec') # check_syntax_error(self, "a + 1 = b + 2") self.assertRaises(SyntaxError, compile, "a + 1 = b + 2", '<test string>', 'exec') def testDelStmt(self): # 'del' exprlist abc = [1,2,3] x, y, z = abc xyz = x, y, z del abc del x, y, (z, xyz) def testPassStmt(self): # 'pass' pass # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt # Tested below def testBreakStmt(self): # 'break' while 1: break def testContinueStmt(self): # 'continue' i = 1 while i: i = 0; continue msg = "" while not msg: msg = "ok" try: continue msg = "continue failed to continue inside try" except: msg = "continue inside try called except block" if msg != "ok": self.fail(msg) msg = "" while not msg: msg = "finally block not called" try: continue finally: msg = "ok" if msg != "ok": self.fail(msg) def test_break_continue_loop(self): # This test warrants an explanation. It is a test specifically for SF bugs # #463359 and #462937. The bug is that a 'break' statement executed or # exception raised inside a try/except inside a loop, *after* a continue # statement has been executed in that loop, will cause the wrong number of # arguments to be popped off the stack and the instruction pointer reset to # a very small number (usually 0.) Because of this, the following test # *must* written as a function, and the tracking vars *must* be function # arguments with default values. Otherwise, the test will loop and loop. def test_inner(extra_burning_oil = 1, count=0): big_hippo = 2 while big_hippo: count += 1 try: if extra_burning_oil and big_hippo == 1: extra_burning_oil -= 1 break big_hippo -= 1 continue except: raise if count > 2 or big_hippo != 1: self.fail("continue then break in try/except in loop broken!") test_inner() def testReturn(self): # 'return' [testlist] def g1(): return def g2(): return 1 g1() x = g2() # check_syntax_error(self, "class foo:return 1") # Currently test.support module is not supported, so check_syntax_error is handled as the following self.assertRaises(SyntaxError, compile, "class foo:return 1", '<test string>', 'exec') def testYield(self): # check_syntax_error(self, "class foo:yield 1") # Currently test.support module is not supported, so check_syntax_error is handled as the following self.assertRaises(SyntaxError, compile, "class foo:yield 1", '<test string>', 'exec') def testRaise(self): # 'raise' test [',' test] try: raise RuntimeError('just testing') except RuntimeError: pass try: raise KeyboardInterrupt except KeyboardInterrupt: pass def testImport(self): # 'import' dotted_as_names import sys import time, sys # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) from time import time from time import (time) # not testable inside a function, but already done at top of the module # from sys import * from sys import path, argv from sys import (path, argv) from sys import (path, argv,) def testGlobal(self): # 'global' NAME (',' NAME)* global a global a, b global one, two, three, four, five, six, seven, eight, nine, ten # def testNonlocal(self): # # 'nonlocal' NAME (',' NAME)* # x = 0 # y = 0 # def f(): # nonlocal x # nonlocal x, y def testAssert(self): # assertTruestmt: 'assert' test [',' test] assert 1 assert 1, 1 assert lambda x:x assert 1, lambda x:x+1 try: assert True except AssertionError as e: self.fail("'assert True' should not have raised an AssertionError") try: assert True, 'this should always pass' except AssertionError as e: self.fail("'assert True, msg' should not have " "raised an AssertionError") # these tests fail if python is run with -O, so check __debug__ @unittest.skipUnless(__debug__, "Won't work if __debug__ is False") def testAssert2(self): try: assert 0, "msg" except AssertionError as e: self.assertEqual(e.args[0], "msg") else: self.fail("AssertionError not raised by assert 0") try: assert False except AssertionError as e: self.assertEqual(len(e.args), 0) else: self.fail("AssertionError not raised by 'assert False'") ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef # Tested below def testIf(self): # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] if 1: pass if 1: pass else: pass if 0: pass elif 0: pass if 0: pass elif 0: pass elif 0: pass elif 0: pass else: pass def testWhile(self): # 'while' test ':' suite ['else' ':' suite] while 0: pass while 0: pass else: pass # Issue1920: "while 0" is optimized away, # ensure that the "else" clause is still present. x = 0 while 0: x = 1 else: x = 2 self.assertEqual(x, 2) def testFor(self): # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] for i in 1, 2, 3: pass for i, j, k in (): pass else: pass class Squares: def __init__(self, max): self.max = max self.sofar = [] def __len__(self): return len(self.sofar) def __getitem__(self, i): if not 0 <= i < self.max: raise IndexError n = len(self.sofar) while n <= i: self.sofar.append(n*n) n = n+1 return self.sofar[i] n = 0 for x in Squares(10): n = n+x if n != 285: self.fail('for over growing sequence') result = [] for x, in [(1,), (2,), (3,)]: result.append(x) self.assertEqual(result, [1, 2, 3]) def testTry(self): ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] ### | 'try' ':' suite 'finally' ':' suite ### except_clause: 'except' [expr ['as' expr]] try: 1/0 except ZeroDivisionError: pass else: pass try: 1/0 except EOFError: pass except TypeError as msg: pass except RuntimeError as msg: pass except: pass else: pass try: 1/0 except (EOFError, TypeError, ZeroDivisionError): pass try: 1/0 except (EOFError, TypeError, ZeroDivisionError) as msg: pass try: pass finally: pass def testSuite(self): # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT if 1: pass if 1: pass if 1: # # # pass pass # pass # def testTest(self): ### and_test ('or' and_test)* ### and_test: not_test ('and' not_test)* ### not_test: 'not' not_test | comparison if not 1: pass if 1 and 1: pass if 1 or 1: pass if not not not 1: pass if not 1 and 1 and 1: pass if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass def testComparison(self): ### comparison: expr (comp_op expr)* ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not' if 1: pass x = (1 == 1) if 1 == 1: pass if 1 != 1: pass if 1 < 1: pass if 1 > 1: pass if 1 <= 1: pass if 1 >= 1: pass if 1 is 1: pass if 1 is not 1: pass if 1 in (): pass if 1 not in (): pass if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass def testBinaryMaskOps(self): x = 1 & 1 x = 1 ^ 1 x = 1 | 1 def testShiftOps(self): x = 1 << 1 x = 1 >> 1 x = 1 << 1 >> 1 def testAdditiveOps(self): x = 1 x = 1 + 1 x = 1 - 1 - 1 x = 1 - 1 + 1 - 1 + 1 def testMultiplicativeOps(self): x = 1 * 1 x = 1 / 1 x = 1 % 1 x = 1 / 1 * 1 % 1 def testUnaryOps(self): x = +1 x = -1 x = ~1 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 x = -1*1/1 + 1*1 - ---1*1 def testSelectors(self): ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME ### subscript: expr | [expr] ':' [expr] import sys, time c = sys.path[0] x = time.time() x = sys.modules['time'].time() a = '01234' c = a[0] c = a[-1] s = a[0:5] s = a[:5] s = a[0:] s = a[:] s = a[-5:] s = a[:-1] s = a[-4:-3] # A rough test of SF bug 1333982. http://python.org/sf/1333982 # The testing here is fairly incomplete. # Test cases should include: commas with 1 and 2 colons d = {} d[1] = 1 d[1,] = 2 d[1,2] = 3 d[1,2,3] = 4 L = list(d) L.sort(key=lambda x: x if isinstance(x, tuple) else ()) self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') def testAtoms(self): ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [',']) x = (1) x = (1 or 2 or 3) x = (1 or 2 or 3, 2, 3) x = [] x = [1] x = [1 or 2 or 3] x = [1 or 2 or 3, 2, 3] x = [] x = {} x = {'one': 1} x = {'one': 1,} x = {'one' or 'two': 1 or 2} x = {'one': 1, 'two': 2} x = {'one': 1, 'two': 2,} x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} x = {'one'} x = {'one', 1,} x = {'one', 'two', 'three'} x = {2, 3, 4,} x = x x = 'x' x = 123 ### exprlist: expr (',' expr)* [','] ### testlist: test (',' test)* [','] # These have been exercised enough above def testClassdef(self): # 'class' NAME ['(' [testlist] ')'] ':' suite class B: pass class B2(): pass class C1(B): pass class C2(B): pass class D(C1, C2, B): pass class C: def meth1(self): pass def meth2(self, arg): pass def meth3(self, a1, a2): pass # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE # decorators: decorator+ # decorated: decorators (classdef | funcdef) def class_decorator(x): return x @class_decorator class G: pass def testDictcomps(self): # dictorsetmaker: ( (test ':' test (comp_for | # (',' test ':' test)* [','])) | # (test (comp_for | (',' test)* [','])) ) nums = [1, 2, 3] self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4}) def testListcomps(self): # list comprehension tests nums = [1, 2, 3, 4, 5] strs = ["Apple", "Banana", "Coconut"] spcs = [" Apple", " Banana ", "Coco nut "] self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut']) self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15]) self.assertEqual([x for x in nums if x > 2], [3, 4, 5]) self.assertEqual([(i, s) for i in nums for s in strs], [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')]) self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]], [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), (5, 'Banana'), (5, 'Coconut')]) self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)], [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]) def test_in_func(l): return [0 < x < 3 for x in l if x > 2] self.assertEqual(test_in_func(nums), [False, False, False]) def test_nested_front(): self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]], [[1, 2], [3, 4], [5, 6]]) test_nested_front() # check_syntax_error(self, "[i, s for i in nums for s in strs]") # Currently test.support module is not supported, so check_syntax_error is handled as the following self.assertRaises(SyntaxError, compile, "[i, s for i in nums for s in strs]", '<test string>', 'exec') # check_syntax_error(self, "[x if y]") self.assertRaises(SyntaxError, compile, "[x if y]", '<test string>', 'exec') suppliers = [ (1, "Boeing"), (2, "Ford"), (3, "Macdonalds") ] parts = [ (10, "Airliner"), (20, "Engine"), (30, "Cheeseburger") ] suppart = [ (1, 10), (1, 20), (2, 20), (3, 30) ] x = [ (sname, pname) for (sno, sname) in suppliers for (pno, pname) in parts for (sp_sno, sp_pno) in suppart if sno == sp_sno and pno == sp_pno ] self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), ('Macdonalds', 'Cheeseburger')]) def testGenexps(self): # generator expression tests g = ([x for x in range(10)] for x in range(1)) self.assertEqual(next(g), [x for x in range(10)]) try: next(g) self.fail('should produce StopIteration exception') except StopIteration: pass a = 1 try: g = (a for d in a) next(g) self.fail('should produce TypeError') except TypeError: pass self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd']) self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy']) a = [x for x in range(10)] b = (x for x in (y for y in a)) self.assertEqual(sum(b), sum([x for x in range(10)])) self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)])) self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2])) self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)])) self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)])) self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)])) self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)])) self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0) # check_syntax_error(self, "foo(x for x in range(10), 100)") # Currently test.support module is not supported, so check_syntax_error is handled as the following self.assertRaises(SyntaxError, compile, "foo(x for x in range(10), 100)", '<test string>', 'exec') # check_syntax_error(self, "foo(100, x for x in range(10))") self.assertRaises(SyntaxError, compile, "foo(100, x for x in range(10))", '<test string>', 'exec') def testComprehensionSpecials(self): # test for outmost iterable precomputation x = 10; g = (i for i in range(x)); x = 5 self.assertEqual(len(list(g)), 10) # This should hold, since we're only precomputing outmost iterable. x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x)) x = 5; t = True; self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g)) # Grammar allows multiple adjacent 'if's in listcomps and genexps, # even though it's silly. Make sure it works (ifelse broke this.) self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7]) self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7]) # verify unpacking single element tuples in listcomp/genexp. self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6]) self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9]) def test_with_statement(self): class manager(object): def __enter__(self): return (1, 2) def __exit__(self, *args): pass with manager(): pass with manager() as x: pass with manager() as (x, y): pass with manager(), manager(): pass with manager() as x, manager() as y: pass with manager() as x, manager(): pass def testIfElseExpr(self): # Test ifelse expressions in various cases def _checkeval(msg, ret): "helper to check that evaluation of expressions is done correctly" print(x) return ret # the next line is not allowed anymore #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True]) self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True]) self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5) self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5) self.assertEqual((5 and 6 if 0 else 1), 1) self.assertEqual(((5 and 6) if 0 else 1), 1) self.assertEqual((5 and (6 if 1 else 1)), 6) self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3) self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1) self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5) self.assertEqual((not 5 if 1 else 1), False) self.assertEqual((not 5 if 0 else 1), 1) self.assertEqual((6 + 1 if 1 else 2), 7) self.assertEqual((6 - 1 if 1 else 2), 5) self.assertEqual((6 * 2 if 1 else 4), 12) self.assertEqual((6 / 2 if 1 else 3), 3) self.assertEqual((6 < 4 if 0 else 2), 2) def test_paren_evaluation(self): self.assertEqual(16 // (4 // 2), 8) self.assertEqual((16 // 4) // 2, 2) self.assertEqual(16 // 4 // 2, 2) self.assertTrue(False is (2 is 3)) self.assertFalse((False is 2) is 3) self.assertFalse(False is 2 is 3) # def test_main(): # run_unittest(TokenTests, GrammarTests) if __name__ == '__main__': #test_main() unittest.main()
bsd-3-clause
chaffra/sympy
sympy/physics/quantum/dagger.py
116
2242
"""Hermitian conjugation.""" from __future__ import print_function, division from sympy.core import Expr from sympy.functions.elementary.complexes import adjoint __all__ = [ 'Dagger' ] class Dagger(adjoint): """General Hermitian conjugate operation. Take the Hermetian conjugate of an argument [1]_. For matrices this operation is equivalent to transpose and complex conjugate [2]_. Parameters ========== arg : Expr The sympy expression that we want to take the dagger of. Examples ======== Daggering various quantum objects: >>> from sympy.physics.quantum.dagger import Dagger >>> from sympy.physics.quantum.state import Ket, Bra >>> from sympy.physics.quantum.operator import Operator >>> Dagger(Ket('psi')) <psi| >>> Dagger(Bra('phi')) |phi> >>> Dagger(Operator('A')) Dagger(A) Inner and outer products:: >>> from sympy.physics.quantum import InnerProduct, OuterProduct >>> Dagger(InnerProduct(Bra('a'), Ket('b'))) <b|a> >>> Dagger(OuterProduct(Ket('a'), Bra('b'))) |b><a| Powers, sums and products:: >>> A = Operator('A') >>> B = Operator('B') >>> Dagger(A*B) Dagger(B)*Dagger(A) >>> Dagger(A+B) Dagger(A) + Dagger(B) >>> Dagger(A**2) Dagger(A)**2 Dagger also seamlessly handles complex numbers and matrices:: >>> from sympy import Matrix, I >>> m = Matrix([[1,I],[2,I]]) >>> m Matrix([ [1, I], [2, I]]) >>> Dagger(m) Matrix([ [ 1, 2], [-I, -I]]) References ========== .. [1] http://en.wikipedia.org/wiki/Hermitian_adjoint .. [2] http://en.wikipedia.org/wiki/Hermitian_transpose """ def __new__(cls, arg): if hasattr(arg, 'adjoint'): obj = arg.adjoint() elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose'): obj = arg.conjugate().transpose() if obj is not None: return obj return Expr.__new__(cls, arg) adjoint.__name__ = "Dagger" adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
bsd-3-clause
BenHenning/oppia
core/controllers/base_test.py
11
9041
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for generic controller behavior.""" __author__ = 'Sean Lip' import copy import datetime import feconf import re import types from core.controllers import base from core.domain import exp_services from core.platform import models current_user_services = models.Registry.import_current_user_services() from core.tests import test_utils import main import webapp2 import webtest class BaseHandlerTest(test_utils.GenericTestBase): def test_dev_indicator_appears_in_dev_and_not_in_production(self): """Test dev indicator appears in dev and not in production.""" with self.swap(feconf, 'DEV_MODE', True): response = self.testapp.get('/gallery') self.assertIn('<div class="oppia-dev-mode">', response.body) with self.swap(feconf, 'DEV_MODE', False): response = self.testapp.get('/gallery') self.assertNotIn('<div class="oppia-dev-mode">', response.body) def test_that_no_get_results_in_500_error(self): """Test that no GET request results in a 500 error.""" for route in main.urls: # This was needed for the Django tests to pass (at the time we had # a Django branch of the codebase). if isinstance(route, tuple): continue else: url = route.template url = re.sub('<([^/^:]+)>', 'abc123', url) # Some of these will 404 or 302. This is expected. response = self.testapp.get(url, expect_errors=True) self.log_line( 'Fetched %s with status code %s' % (url, response.status_int)) self.assertIn(response.status_int, [200, 302, 404]) # TODO(sll): Add similar tests for POST, PUT, DELETE. # TODO(sll): Set a self.payload attr in the BaseHandler for # POST, PUT and DELETE. Something needs to regulate what # the fields in the payload should be. def test_requests_for_invalid_paths(self): """Test that requests for invalid paths result in a 404 error.""" response = self.testapp.get('/gallery/extra', expect_errors=True) self.assertEqual(response.status_int, 404) response = self.testapp.get('/gallery/data/extra', expect_errors=True) self.assertEqual(response.status_int, 404) response = self.testapp.post('/gallery/extra', {}, expect_errors=True) self.assertEqual(response.status_int, 404) response = self.testapp.put('/gallery/extra', {}, expect_errors=True) self.assertEqual(response.status_int, 404) class CsrfTokenManagerTest(test_utils.GenericTestBase): def test_create_and_validate_token(self): uid = 'user_id' page = 'page_name' token = base.CsrfTokenManager.create_csrf_token(uid, page) self.assertTrue(base.CsrfTokenManager.is_csrf_token_valid( uid, page, token)) self.assertFalse( base.CsrfTokenManager.is_csrf_token_valid('bad_user', page, token)) self.assertFalse(base.CsrfTokenManager.is_csrf_token_valid( uid, 'wrong_page', token)) self.assertFalse(base.CsrfTokenManager.is_csrf_token_valid( uid, self.UNICODE_TEST_STRING, token)) self.assertFalse( base.CsrfTokenManager.is_csrf_token_valid(uid, page, 'new_token')) self.assertFalse( base.CsrfTokenManager.is_csrf_token_valid(uid, page, 'new/token')) def test_nondefault_csrf_secret_is_used(self): base.CsrfTokenManager.create_csrf_token('uid', 'page') self.assertNotEqual(base.CSRF_SECRET.value, base.DEFAULT_CSRF_SECRET) def test_token_expiry(self): # This can be any value. ORIG_TIME = 100.0 FORTY_EIGHT_HOURS_IN_SECS = 48 * 60 * 60 PADDING = 1 current_time = ORIG_TIME # Create a fake copy of the CsrfTokenManager class so that its # _get_current_time() method can be swapped out without affecting the # original class. FakeCsrfTokenManager = copy.deepcopy(base.CsrfTokenManager) def _get_current_time(cls): return current_time setattr( FakeCsrfTokenManager, _get_current_time.__name__, types.MethodType(_get_current_time, FakeCsrfTokenManager) ) # Create a token and check that it expires correctly. token = FakeCsrfTokenManager.create_csrf_token('uid', 'page') self.assertTrue( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page', token)) current_time = ORIG_TIME + 1 self.assertTrue( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page', token)) current_time = ORIG_TIME + FORTY_EIGHT_HOURS_IN_SECS - PADDING self.assertTrue( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page', token)) current_time = ORIG_TIME + FORTY_EIGHT_HOURS_IN_SECS + PADDING self.assertFalse( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page', token)) # Check that the expiry of one token does not cause the other to # expire. current_time = ORIG_TIME token1 = FakeCsrfTokenManager.create_csrf_token('uid', 'page1') self.assertTrue( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page1', token1)) current_time = ORIG_TIME + 100 token2 = FakeCsrfTokenManager.create_csrf_token('uid', 'page2') self.assertTrue( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page2', token2)) current_time = ORIG_TIME + FORTY_EIGHT_HOURS_IN_SECS + PADDING self.assertFalse( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page1', token1)) self.assertTrue( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page2', token2)) current_time = ORIG_TIME + 100 + FORTY_EIGHT_HOURS_IN_SECS + PADDING self.assertFalse( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page1', token1)) self.assertFalse( FakeCsrfTokenManager.is_csrf_token_valid('uid', 'page2', token2)) class EscapingTest(test_utils.GenericTestBase): class FakeAboutPage(base.BaseHandler): """Fake page for testing autoescaping.""" def get(self): """Handles GET requests.""" self.values.update({ 'CONTACT_EMAIL_ADDRESS': ['<[angular_tag]>'], 'SITE_FORUM_URL': 'x{{51 * 3}}y', }) self.render_template('pages/about.html') def post(self): """Handles POST requests.""" self.render_json({'big_value': u'\n<script>马={{'}) def setUp(self): super(EscapingTest, self).setUp() self.testapp = webtest.TestApp(webapp2.WSGIApplication( [webapp2.Route('/fake', self.FakeAboutPage, name='FakePage')], debug=feconf.DEBUG, )) def test_jinja_autoescaping(self): response = self.testapp.get('/fake') self.assertEqual(response.status_int, 200) self.assertIn('&lt;[angular_tag]&gt;', response.body) self.assertNotIn('<[angular_tag]>', response.body) self.assertIn('x{{51 * 3}}y', response.body) self.assertNotIn('x153y', response.body) def test_special_char_escaping(self): response = self.testapp.post('/fake', {}) self.assertEqual(response.status_int, 200) self.assertTrue(response.body.startswith(feconf.XSSI_PREFIX)) self.assertIn('\\n\\u003cscript\\u003e\\u9a6c={{', response.body) self.assertNotIn('<script>', response.body) self.assertNotIn('马', response.body) class LogoutPageTest(test_utils.GenericTestBase): def test_logout_page(self): """Tests for logout handler.""" exp_services.load_demo('0') # Logout with valid query arg. This test only validates that the login # cookies have expired after hitting the logout url. current_page = '/explore/0' response = self.testapp.get(current_page) self.assertEqual(response.status_int, 200) response = self.testapp.get(current_user_services.create_logout_url( current_page)) expiry_date = response.headers['Set-Cookie'].rsplit('=', 1) self.assertTrue(datetime.datetime.now() > datetime.datetime.strptime( expiry_date[1], '%a, %d %b %Y %H:%M:%S GMT',))
apache-2.0
awkspace/ansible
lib/ansible/modules/network/panos/panos_restart.py
11
2810
#!/usr/bin/python # -*- coding: utf-8 -*- # # Ansible module to manage PaloAltoNetworks Firewall # (c) 2016, techbizdev <techbizdev@paloaltonetworks.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/>. DOCUMENTATION = ''' --- module: panos_restart short_description: restart a device description: - Restart a device author: "Luigi Mori (@jtschichold), Ivan Bojer (@ivanbojer)" version_added: "2.3" requirements: - pan-python extends_documentation_fragment: panos ''' EXAMPLES = ''' - panos_restart: ip_address: "192.168.1.1" username: "admin" password: "admin" ''' RETURN = ''' status: description: success status returned: success type: str sample: "okey dokey" ''' ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import sys import traceback try: import pan.xapi HAS_LIB = True except ImportError: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native def main(): argument_spec = dict( ip_address=dict(), password=dict(no_log=True), username=dict(default='admin') ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_LIB: module.fail_json(msg='pan-python required for this module') ip_address = module.params["ip_address"] if not ip_address: module.fail_json(msg="ip_address should be specified") password = module.params["password"] if not password: module.fail_json(msg="password is required") username = module.params['username'] xapi = pan.xapi.PanXapi( hostname=ip_address, api_username=username, api_password=password ) try: xapi.op(cmd="<request><restart><system></system></restart></request>") except Exception as e: if 'succeeded' in to_native(e): module.exit_json(changed=True, msg=to_native(e)) else: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) module.exit_json(changed=True, msg="okey dokey") if __name__ == '__main__': main()
gpl-3.0
tengyifei/grpc
test/core/http/test_server.py
30
2921
#!/usr/bin/env python2.7 # Copyright 2015, 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. """Server for httpcli_test""" import argparse import BaseHTTPServer import os import ssl import sys _PEM = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../../..', 'src/core/lib/tsi/test_creds/server1.pem')) _KEY = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../../..', 'src/core/lib/tsi/test_creds/server1.key')) print _PEM open(_PEM).close() argp = argparse.ArgumentParser(description='Server for httpcli_test') argp.add_argument('-p', '--port', default=10080, type=int) argp.add_argument('-s', '--ssl', default=False, action='store_true') args = argp.parse_args() print 'server running on port %d' % args.port class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def good(self): self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write('<html><head><title>Hello world!</title></head>') self.wfile.write('<body><p>This is a test</p></body></html>') def do_GET(self): if self.path == '/get': self.good() def do_POST(self): content = self.rfile.read(int(self.headers.getheader('content-length'))) if self.path == '/post' and content == 'hello': self.good() httpd = BaseHTTPServer.HTTPServer(('localhost', args.port), Handler) if args.ssl: httpd.socket = ssl.wrap_socket(httpd.socket, certfile=_PEM, keyfile=_KEY, server_side=True) httpd.serve_forever()
bsd-3-clause
denova/TaskBoard
taskboard/settings.py
2
2192
""" Django settings for taskboard project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'h=8*4c8boaft480baxkzb!!t90n-5q64=yso!t$far%0+m-yqi' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False TEMPLATE_DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'taskboard.urls' WSGI_APPLICATION = 'taskboard.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'taskboard', 'USER': 'djangouser', 'PASSWORD': 'djangopassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' LOGIN_URL = '/'
unlicense
sovietspy2/uzletiProject
python/Lib/ctypes/util.py
3
7264
###################################################################### # This file should be kept compatible with Python 2.3, see PEP 291. # ###################################################################### import sys, os # find_library(name) returns the pathname of a library, or None. if os.name == "nt": def _get_build_version(): """Return the version of MSVC that was used to build Python. For Python 2.3 and up, the version number is included in sys.version. For earlier versions, assume the compiler is MSVC 6. """ # This function was copied from Lib/distutils/msvccompiler.py prefix = "MSC v." i = sys.version.find(prefix) if i == -1: return 6 i = i + len(prefix) s, rest = sys.version[i:].split(" ", 1) majorVersion = int(s[:-2]) - 6 minorVersion = int(s[2:3]) / 10.0 # I don't think paths are affected by minor version in version 6 if majorVersion == 6: minorVersion = 0 if majorVersion >= 6: return majorVersion + minorVersion # else we don't know what version of the compiler this is return None def find_msvcrt(): """Return the name of the VC runtime dll""" version = _get_build_version() if version is None: # better be safe than sorry return None if version <= 6: clibname = 'msvcrt' else: clibname = 'msvcr%d' % (version * 10) # If python was built with in debug mode import imp if imp.get_suffixes()[0][0] == '_d.pyd': clibname += 'd' return clibname+'.dll' def find_library(name): if name in ('c', 'm'): return find_msvcrt() # See MSDN for the REAL search order. for directory in os.environ['PATH'].split(os.pathsep): fname = os.path.join(directory, name) if os.path.exists(fname): return fname if fname.lower().endswith(".dll"): continue fname = fname + ".dll" if os.path.exists(fname): return fname return None if os.name == "ce": # search path according to MSDN: # - absolute path specified by filename # - The .exe launch directory # - the Windows directory # - ROM dll files (where are they?) # - OEM specified search path: HKLM\Loader\SystemPath def find_library(name): return name if os.name == "posix" and sys.platform == "darwin": from ctypes.macholib.dyld import dyld_find as _dyld_find def find_library(name): possible = ['lib%s.dylib' % name, '%s.dylib' % name, '%s.framework/%s' % (name, name)] for name in possible: try: return _dyld_find(name) except ValueError: continue return None elif os.name == "posix": # Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump import re, tempfile, errno def _findLib_gcc(name): expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) fdout, ccout = tempfile.mkstemp() os.close(fdout) cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; else CC=cc; fi;' \ '$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name try: f = os.popen(cmd) trace = f.read() f.close() finally: try: os.unlink(ccout) except OSError, e: if e.errno != errno.ENOENT: raise res = re.search(expr, trace) if not res: return None return res.group(0) if sys.platform == "sunos5": # use /usr/ccs/bin/dump on solaris def _get_soname(f): if not f: return None cmd = "/usr/ccs/bin/dump -Lpv 2>/dev/null " + f res = re.search(r'\[.*\]\sSONAME\s+([^\s]+)', os.popen(cmd).read()) if not res: return None return res.group(1) else: def _get_soname(f): # assuming GNU binutils / ELF if not f: return None cmd = "objdump -p -j .dynamic 2>/dev/null " + f res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read()) if not res: return None return res.group(1) if (sys.platform.startswith("freebsd") or sys.platform.startswith("openbsd") or sys.platform.startswith("dragonfly")): def _num_version(libname): # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ] parts = libname.split(".") nums = [] try: while parts: nums.insert(0, int(parts.pop())) except ValueError: pass return nums or [ sys.maxint ] def find_library(name): ename = re.escape(name) expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename) res = re.findall(expr, os.popen('/sbin/ldconfig -r 2>/dev/null').read()) if not res: return _get_soname(_findLib_gcc(name)) res.sort(cmp= lambda x,y: cmp(_num_version(x), _num_version(y))) return res[-1] else: def _findLib_ldconfig(name): # XXX assuming GLIBC's ldconfig (with option -p) expr = r'/[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) res = re.search(expr, os.popen('/sbin/ldconfig -p 2>/dev/null').read()) if not res: # Hm, this works only for libs needed by the python executable. cmd = 'ldd %s 2>/dev/null' % sys.executable res = re.search(expr, os.popen(cmd).read()) if not res: return None return res.group(0) def find_library(name): return _get_soname(_findLib_ldconfig(name) or _findLib_gcc(name)) ################################################################ # test code def test(): from ctypes import cdll if os.name == "nt": print cdll.msvcrt print cdll.load("msvcrt") print find_library("msvcrt") if os.name == "posix": # find and load_version print find_library("m") print find_library("c") print find_library("bz2") # getattr ## print cdll.m ## print cdll.bz2 # load if sys.platform == "darwin": print cdll.LoadLibrary("libm.dylib") print cdll.LoadLibrary("libcrypto.dylib") print cdll.LoadLibrary("libSystem.dylib") print cdll.LoadLibrary("System.framework/System") else: print cdll.LoadLibrary("libm.so") print cdll.LoadLibrary("libcrypt.so") print find_library("crypt") if __name__ == "__main__": test()
gpl-3.0
z01nl1o02/tests
text/mlpbase.py
1
8554
import os,sys,pdb,pickle import numpy as np import cv2 import theano import theano.tensor as T import random #you may try several times to get a good model and the init 'cost' may be quite large, 78 .e.g. class Layer(object): """ a layer is a maxtrix with row = output of this layer and col = output of previous layer """ def __init__(self, W_init, b_init, activation): n_output,n_input = W_init.shape assert b_init.shape == (n_output,) self.W = theano.shared(value=W_init.astype(theano.config.floatX), name="W", borrow=True) self.b = theano.shared(value=b_init.reshape(n_output,1).astype(theano.config.floatX), name="b", borrow=True, broadcastable=(False,True)) self.activation = activation self.params = [self.W, self.b] def output(self,x): lin_output = T.dot(self.W,x) + self.b return (lin_output if self.activation is None else self.activation(lin_output)) class MLP(object): def __init__(self, W_init, b_init, activations): assert len(W_init) == len(b_init) == len(activations) self.layers = [] for W,b,activation in zip(W_init, b_init, activations): self.layers.append(Layer(W,b,activation)) self.params = [] for layer in self.layers: self.params += layer.params def output(self,x): for layer in self.layers: x = layer.output(x) return x def squared_error(self,x,y): return T.sum((self.output(x) - y) ** 2) return T.mean((self.output(x) - y) ** 2) def cvt2c(self): line = "" for param in self.params: parval = param.get_value() line += "%d"%(parval.shape[0]) + ',' + "%d"%(parval.shape[1]) + ',\n' for y in range(parval.shape[0]): for x in range(parval.shape[1]): line += "%lf"%(parval[y,x])+ ',' line += '\n' return line class MLP_PROXY(object): def __init__(self, modelpath): self._train = None self._predict = None self._cost = None self._minmax = None self._modelpath = modelpath self._mlp = None def gradient_updates_momentum(self,cost, params, learning_rate, momentum): assert momentum < 1 and momentum >= 0 updates = [] for param in params: param_update = theano.shared(param.get_value() * 0., broadcastable=param.broadcastable) updates.append((param, param - learning_rate * param_update)) updates.append((param_update, momentum * param_update + (1. - momentum)*T.grad(cost, param))) return updates def write_in_c_format(self,outpath): line = "" for m0,m1 in zip(self._minmax[0], self._minmax[1]): line += "%lf,%lf,"%(m0,m1) line += '\n' line += self._mlp.cvt2c() with open(outpath, 'w') as f: f.writelines(line) return def create(self, layer_sizes, learning_rate = 0.01, momentum = 0.6): W_init = [] b_init = [] activations = [] for n_input, n_output in zip(layer_sizes[:-1], layer_sizes[1:]): W_init.append(np.random.randn(n_output, n_input)) b_init.append(np.random.randn(n_output)) activations.append(T.nnet.sigmoid) mlp = MLP(W_init, b_init, activations) mlp_input = T.matrix('mlp_input') mlp_target = T.matrix('mlp_target') self._cost = mlp.squared_error(mlp_input, mlp_target) self._train = theano.function([mlp_input,mlp_target], self._cost, updates=self.gradient_updates_momentum(self._cost, mlp.params, learning_rate, momentum)) self._predict = theano.function([mlp_input], mlp.output(mlp_input)) self._mlp = mlp return def train(self,samples, targets, max_iteration=5000, min_cost = 0.01): #samples and targets : (samples num) X (feature dimenstion) iteration = 0 samplesT = np.transpose(samples) #W*x + b targetsT = np.transpose(targets) batchsize = 5 echostep = max_iteration / 10 if echostep > 1000: echostep = 1000 while iteration < max_iteration: cost = 0 total = 0 for k in range(0,samplesT.shape[1],batchsize): kk = k if kk + batchsize > samplesT.shape[1]: kk = samplesT.shape[1] - batchsize s = np.reshape(samplesT[:,kk:kk+batchsize],(-1,batchsize)) t = np.reshape(targetsT[:,kk:kk+batchsize],(-1,batchsize)) current_cost = self._train(s,t) cost = cost + current_cost.sum() total += batchsize if (1+iteration)% echostep == 0: print iteration + 1, ',', cost if cost < min_cost: break iteration += 1 return def predict(self,samples): samplesT = np.transpose(samples) #W*x + b output = self._predict(samplesT) targets = np.transpose(output) return targets def pre_normalization(self, samples): m0 = samples[0,:] m1 = samples[0,:] for k in range(1,samples.shape[0]): m0 = np.minimum(samples[k,:],m0) m1 = np.maximum(samples[k,:],m1) self._minmax = (m0,m1) return def normalization(self, samples, u=1, l=-1): if None == self._minmax: return None m0,m1 = self._minmax rng = m1 - m0 tmp = np.ones(rng.shape) for k in range(len(rng)): if rng[k] < 0.001: rng[k] = 1 tmp[k] = 0 ratio = tmp / rng for k in range(samples.shape[0]): feat = samples[k,:] feat = (feat - m0) * ratio * (u - l) + l idx = feat>u feat[idx] = u idx = feat<l feat[idx] = l samples[k,:] = feat return samples def shuffle(self, samples, targets): totalnum = samples.shape[0] idx = range(totalnum) random.shuffle(idx) rnd_samples = np.zeros(samples.shape) rnd_targets = np.zeros(targets.shape) for k in range(len(idx)): i = idx[k] rnd_samples[k,:] = samples[i,:] rnd_targets[k,:] = targets[i,:] return (rnd_samples, rnd_targets) def target_vec2mat(self, target_list, labelnum, hvalue = 1.0, lvalue = 0.0): #0-based targetnum = len(target_list) targets = np.zeros((targetnum, labelnum)) for k in range(targetnum): for j in range(labelnum): targets[k,j] = lvalue for j in target_list[k]: targets[k,j] = hvalue return targets def target_mat2vec(self, targets, labelnum, thresh = 0.5): target_list = [] if thresh > 0: for k in range(targets.shape[0]): l = [] for j in range(targets.shape[1]): if targets[k,j] >= thresh: l.append(j) target_list.append(l) if thresh < -1024.0: for k in range(targets.shape[0]): l = [] m1 = targets[k,:].max() for j in range(targets.shape[1]): if np.abs(targets[k,j] - m1) < 0.01: l.append((j,m1)) #label and confidence target_list.append(l) else: #top value for k in range(targets.shape[0]): l = [] m1 = targets[k,:].max() for j in range(targets.shape[1]): if np.abs(targets[k,j] - m1) < 0.01: l.append(j) target_list.append(l) return target_list def save(self): if None == self._modelpath: return -1 with open(self._modelpath, 'wb') as f: pickle.dump((self._cost, self._train, self._predict, self._minmax,self._mlp), f) return 0 def load(self): if None == self._modelpath: return -1 with open(self._modelpath, 'rb') as f: self._cost, self._train, self._predict, self._minmax, self._mlp = pickle.load(f) return 0
gpl-2.0
Learningtribes/edx-platform
common/djangoapps/third_party_auth/tasks.py
47
6565
# -*- coding: utf-8 -*- """ Code to manage fetching and storing the metadata of IdPs. """ from celery.task import task import datetime import dateutil.parser import logging from lxml import etree import requests from onelogin.saml2.utils import OneLogin_Saml2_Utils from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig, SAMLProviderData log = logging.getLogger(__name__) SAML_XML_NS = 'urn:oasis:names:tc:SAML:2.0:metadata' # The SAML Metadata XML namespace class MetadataParseError(Exception): """ An error occurred while parsing the SAML metadata from an IdP """ pass @task(name='third_party_auth.fetch_saml_metadata') def fetch_saml_metadata(): """ Fetch and store/update the metadata of all IdPs This task should be run on a daily basis. It's OK to run this whether or not SAML is enabled. Return value: tuple(num_changed, num_failed, num_total) num_changed: Number of providers that are either new or whose metadata has changed num_failed: Number of providers that could not be updated num_total: Total number of providers whose metadata was fetched """ if not SAMLConfiguration.is_enabled(): return (0, 0, 0) # Nothing to do until SAML is enabled. num_changed, num_failed = 0, 0 # First make a list of all the metadata XML URLs: url_map = {} for idp_slug in SAMLProviderConfig.key_values('idp_slug', flat=True): config = SAMLProviderConfig.current(idp_slug) if not config.enabled: continue url = config.metadata_source if url not in url_map: url_map[url] = [] if config.entity_id not in url_map[url]: url_map[url].append(config.entity_id) # Now fetch the metadata: for url, entity_ids in url_map.items(): try: log.info("Fetching %s", url) if not url.lower().startswith('https'): log.warning("This SAML metadata URL is not secure! It should use HTTPS. (%s)", url) response = requests.get(url, verify=True) # May raise HTTPError or SSLError or ConnectionError response.raise_for_status() # May raise an HTTPError try: parser = etree.XMLParser(remove_comments=True) xml = etree.fromstring(response.content, parser) except etree.XMLSyntaxError: raise # TODO: Can use OneLogin_Saml2_Utils to validate signed XML if anyone is using that for entity_id in entity_ids: log.info(u"Processing IdP with entityID %s", entity_id) public_key, sso_url, expires_at = _parse_metadata_xml(xml, entity_id) changed = _update_data(entity_id, public_key, sso_url, expires_at) if changed: log.info(u"→ Created new record for SAMLProviderData") num_changed += 1 else: log.info(u"→ Updated existing SAMLProviderData. Nothing has changed.") except Exception as err: # pylint: disable=broad-except log.exception(err.message) num_failed += 1 return (num_changed, num_failed, len(url_map)) def _parse_metadata_xml(xml, entity_id): """ Given an XML document containing SAML 2.0 metadata, parse it and return a tuple of (public_key, sso_url, expires_at) for the specified entityID. Raises MetadataParseError if anything is wrong. """ if xml.tag == etree.QName(SAML_XML_NS, 'EntityDescriptor'): entity_desc = xml else: if xml.tag != etree.QName(SAML_XML_NS, 'EntitiesDescriptor'): raise MetadataParseError("Expected root element to be <EntitiesDescriptor>, not {}".format(xml.tag)) entity_desc = xml.find( ".//{}[@entityID='{}']".format(etree.QName(SAML_XML_NS, 'EntityDescriptor'), entity_id) ) if not entity_desc: raise MetadataParseError("Can't find EntityDescriptor for entityID {}".format(entity_id)) expires_at = None if "validUntil" in xml.attrib: expires_at = dateutil.parser.parse(xml.attrib["validUntil"]) if "cacheDuration" in xml.attrib: cache_expires = OneLogin_Saml2_Utils.parse_duration(xml.attrib["cacheDuration"]) if expires_at is None or cache_expires < expires_at: expires_at = cache_expires sso_desc = entity_desc.find(etree.QName(SAML_XML_NS, "IDPSSODescriptor")) if not sso_desc: raise MetadataParseError("IDPSSODescriptor missing") if 'urn:oasis:names:tc:SAML:2.0:protocol' not in sso_desc.get("protocolSupportEnumeration"): raise MetadataParseError("This IdP does not support SAML 2.0") # Now we just need to get the public_key and sso_url public_key = sso_desc.findtext("./{}//{}".format( etree.QName(SAML_XML_NS, "KeyDescriptor"), "{http://www.w3.org/2000/09/xmldsig#}X509Certificate" )) if not public_key: raise MetadataParseError("Public Key missing. Expected an <X509Certificate>") public_key = public_key.replace(" ", "") binding_elements = sso_desc.iterfind("./{}".format(etree.QName(SAML_XML_NS, "SingleSignOnService"))) sso_bindings = {element.get('Binding'): element.get('Location') for element in binding_elements} try: # The only binding supported by python-saml and python-social-auth is HTTP-Redirect: sso_url = sso_bindings['urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'] except KeyError: raise MetadataParseError("Unable to find SSO URL with HTTP-Redirect binding.") return public_key, sso_url, expires_at def _update_data(entity_id, public_key, sso_url, expires_at): """ Update/Create the SAMLProviderData for the given entity ID. Return value: False if nothing has changed and existing data's "fetched at" timestamp is just updated. True if a new record was created. (Either this is a new provider or something changed.) """ data_obj = SAMLProviderData.current(entity_id) fetched_at = datetime.datetime.now() if data_obj and (data_obj.public_key == public_key and data_obj.sso_url == sso_url): data_obj.expires_at = expires_at data_obj.fetched_at = fetched_at data_obj.save() return False else: SAMLProviderData.objects.create( entity_id=entity_id, fetched_at=fetched_at, expires_at=expires_at, sso_url=sso_url, public_key=public_key, ) return True
agpl-3.0
wpoely86/vsc-base
lib/vsc/utils/run.py
2
31071
# # Copyright 2009-2013 Ghent University # # This file is part of vsc-base, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (http://www.herculesstichting.be/in_English) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/vsc-base # # vsc-base 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. # # vsc-base 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 vsc-base. If not, see <http://www.gnu.org/licenses/>. # """ Python module to execute a command Historical overview of existing equivalent code - EasyBuild filetools module - C{run_cmd(cmd, log_ok=True, log_all=False, simple=False, inp=None, regexp=True, log_output=False, path=None)} - C{run_cmd_qa(cmd, qa, no_qa=None, log_ok=True, log_all=False, simple=False, regexp=True, std_qa=None, path=None)} - Executes a command cmd - looks for questions and tries to answer based on qa dictionary - returns exitcode and stdout+stderr (mixed) - no input though stdin - if C{log_ok} or C{log_all} are set -> will C{log.error} if non-zero exit-code - if C{simple} is C{True} -> instead of returning a tuple (output, ec) it will just return C{True} or C{False} signifying succes - C{regexp} -> Regex used to check the output for errors. If C{True} will use default (see C{parselogForError}) - if log_output is True -> all output of command will be logged to a tempfile - path is the path run_cmd should chdir to before doing anything - Q&A: support reading stdout asynchronous and replying to a question through stdin - Manage C{managecommands} module C{Command} class - C{run} method - python-package-vsc-utils run module Command class - C{run} method - C{mympirun} (old) - C{runrun(self, cmd, returnout=False, flush=False, realcmd=False)}: - C{runrunnormal(self, cmd, returnout=False, flush=False)} - C{runrunfile(self, cmd, returnout=False, flush=False)} - C{hanything} commands/command module - C{run} method - fake pty support @author: Stijn De Weirdt (Ghent University) """ import errno import logging import os import pty import re import signal import sys import time from vsc.utils.fancylogger import getLogger, getAllExistingLoggers PROCESS_MODULE_ASYNCPROCESS_PATH = 'vsc.utils.asyncprocess' PROCESS_MODULE_SUBPROCESS_PATH = 'subprocess' RUNRUN_TIMEOUT_OUTPUT = '' RUNRUN_TIMEOUT_EXITCODE = 123 RUNRUN_QA_MAX_MISS_EXITCODE = 124 BASH = '/bin/bash' SHELL = BASH class DummyFunction(object): def __getattr__(self, name): def dummy(*args, **kwargs): pass return dummy class Run(object): """Base class for static run method""" INIT_INPUT_CLOSE = True USE_SHELL = True SHELL = SHELL # set the shell via the module constant @classmethod def run(cls, cmd, **kwargs): """static method return (exitcode,output) """ r = cls(cmd, **kwargs) return r._run() def __init__(self, cmd=None, **kwargs): """ Handle initiliastion @param cmd: command to run @param input: set "simple" input @param startpath: directory to change to before executing command @param disable_log: use fake logger (won't log anything) @param use_shell: use the subshell @param shell: change the shell """ self.input = kwargs.pop('input', None) self.startpath = kwargs.pop('startpath', None) self.use_shell = kwargs.pop('use_shell', self.USE_SHELL) self.shell = kwargs.pop('shell', self.SHELL) if kwargs.pop('disable_log', None): self.log = DummyFunction() # No logging if not hasattr(self, 'log'): self.log = getLogger(self._get_log_name()) self.cmd = cmd # actual command self._cwd_before_startpath = None self._process_module = None self._process = None self.readsize = 1024 # number of bytes to read blocking self._shellcmd = None self._popen_named_args = None self._process_exitcode = None self._process_output = None self._post_exitcode_log_failure = self.log.error super(Run, self).__init__(**kwargs) def _get_log_name(self): """Set the log name""" return self.__class__.__name__ def _prep_module(self, modulepath=None, extendfromlist=None): # these will provide the required Popen, PIPE and STDOUT if modulepath is None: modulepath = PROCESS_MODULE_SUBPROCESS_PATH fromlist = ['Popen', 'PIPE', 'STDOUT'] if extendfromlist is not None: fromlist.extend(extendfromlist) self._process_modulepath = modulepath self._process_module = __import__(self._process_modulepath, globals(), locals(), fromlist) def _run(self): """actual method Structure - pre - convert command to shell command - DONE - chdir before start - DONE - start C{Popen} - DONE - support async and subprocess - DONE - support for - filehandle - PIPE - DONE - pty - DONE - main - should capture exitcode and output - features - separate stdout and stderr ? - simple single run - no timeout/waiting - DONE - flush to - stdout - logger - DONE - both stdout and logger - process intermediate output - qa - input - qa - from file ? - text - DONE - post - parse with regexp - raise/log error on match - return - return output - log output - write to file - return in string - DONE - on C{ec > 0} - error - DONE - raiseException - simple - just return True/False """ self._run_pre() self._wait_for_process() return self._run_post() def _run_pre(self): """Non-blocking start""" if self._process_module is None: self._prep_module() if self.startpath is not None: self._start_in_path() if self._shellcmd is None: self._make_shell_command() if self._popen_named_args is None: self._make_popen_named_args() self._init_process() self._init_input() def _run_post(self): self._cleanup_process() self._post_exitcode() self._post_output() if self.startpath is not None: self._return_to_previous_start_in_path() return self._run_return() def _start_in_path(self): """Change path before the run""" if self.startpath is None: self.log.debug("_start_in_path: no startpath set") return if os.path.exists(self.startpath): if os.path.isdir(self.startpath): try: self._cwd_before_startpath = os.getcwd() # store it some one can return to it os.chdir(self.startpath) except: self.raiseException("_start_in_path: failed to change path from %s to startpath %s" % (self._cwd_before_startpath, self.startpath)) else: self.log.raiseExcpetion("_start_in_path: provided startpath %s exists but is no directory" % self.startpath) else: self.raiseException("_start_in_path: startpath %s does not exist" % self.startpath) def _return_to_previous_start_in_path(self): """Change to original path before the change to startpath""" if self._cwd_before_startpath is None: self.log.warning("_return_to_previous_start_in_path: previous cwd is empty. Not trying anything") return if os.path.exists(self._cwd_before_startpath): if os.path.isdir(self._cwd_before_startpath): try: currentpath = os.getcwd() if not currentpath == self.startpath: self.log.warning(("_return_to_previous_start_in_path: current diretory %s does not match " "startpath %s") % (currentpath, self.startpath)) os.chdir(self._cwd_before_startpath) except: self.raiseException(("_return_to_previous_start_in_path: failed to change path from current %s " "to previous path %s") % (currentpath, self._cwd_before_startpath)) else: self.log.raiseExcpetion(("_return_to_previous_start_in_path: provided previous cwd path %s exists " "but is no directory") % self._cwd_before_startpath) else: self.raiseException("_return_to_previous_start_in_path: previous cwd path %s does not exist" % self._cwd_before_startpath) def _make_popen_named_args(self, others=None): """Create the named args for Popen""" self._popen_named_args = { 'stdout': self._process_module.PIPE, 'stderr': self._process_module.STDOUT, 'stdin': self._process_module.PIPE, 'close_fds': True, 'shell': self.use_shell, 'executable': self.shell, } if others is not None: self._popen_named_args.update(others) self.log.debug("_popen_named_args %s" % self._popen_named_args) def _make_shell_command(self): """Convert cmd into shell command""" if self.cmd is None: self.log.raiseExcpetion("_make_shell_command: no cmd set.") if isinstance(self.cmd, basestring): self._shellcmd = self.cmd elif isinstance(self.cmd, (list, tuple,)): self._shellcmd = " ".join(self.cmd) else: self.log.raiseException("Failed to convert cmd %s (type %s) into shell command" % (self.cmd, type(self.cmd))) def _init_process(self): """Initialise the self._process""" try: self._process = self._process_module.Popen(self._shellcmd, **self._popen_named_args) except OSError: self.log.raiseException("_init_process: init Popen shellcmd %s failed: %s" % (self._shellcmd)) def _init_input(self): """Handle input, if any in a simple way""" if self.input is not None: # allow empty string (whatever it may mean) try: self._process.stdin.write(self.input) except: self.log.raiseException("_init_input: Failed write input %s to process" % self.input) if self.INIT_INPUT_CLOSE: self._process.stdin.close() self.log.debug("_init_input: process stdin closed") else: self.log.debug("_init_input: process stdin NOT closed") def _wait_for_process(self): """The main loop This one has most simple loop """ try: self._process_exitcode = self._process.wait() self._process_output = self._read_process(-1) # -1 is read all except: self.log.raiseException("_wait_for_process: problem during wait exitcode %s output %s" % (self._process_exitcode, self._process_output)) def _cleanup_process(self): """Cleanup any leftovers from the process""" pass def _read_process(self, readsize=None): """Read from process, return out""" if readsize is None: readsize = self.readsize if readsize is None: readsize = -1 # read all self.log.debug("_read_process: going to read with readsize %s" % readsize) out = self._process.stdout.read(readsize) return out def _post_exitcode(self): """Postprocess the exitcode in self._process_exitcode""" if not self._process_exitcode == 0: self._post_exitcode_log_failure("_post_exitcode: problem occured with cmd %s: output %s" % (self.cmd, self._process_output)) else: self.log.debug("_post_exitcode: success cmd %s: output %s" % (self.cmd, self._process_output)) def _post_output(self): """Postprocess the output in self._process_output""" pass def _run_return(self): """What to return""" return self._process_exitcode, self._process_output def _killtasks(self, tasks=None, sig=signal.SIGKILL, kill_pgid=False): """ Kill all tasks @param: tasks list of processids @param: sig, signal to use to kill @apram: kill_pgid, send kill to group """ if tasks is None: self.log.error("killtasks no tasks passed") elif isinstance(tasks, basestring): try: tasks = [int(tasks)] except: self.log.error("killtasks failed to convert tasks string %s to int" % tasks) for pid in tasks: pgid = os.getpgid(pid) try: os.kill(int(pid), sig) if kill_pgid: os.killpg(pgid, sig) self.log.debug("Killed %s with signal %s" % (pid, sig)) except OSError, err: # ERSCH is no such process, so no issue if not err.errno == errno.ESRCH: self.log.error("Failed to kill %s: %s" % (pid, err)) except Exception, err: self.log.error("Failed to kill %s: %s" % (pid, err)) def stop_tasks(self): """Cleanup current run""" self._killtasks(tasks=[self._process.pid]) try: os.waitpid(-1, os.WNOHANG) except: pass class RunNoWorries(Run): """When the exitcode is >0, log.debug instead of log.error""" def __init__(self, cmd, **kwargs): super(RunNoWorries, self).__init__(cmd, **kwargs) self._post_exitcode_log_failure = self.log.debug class RunLoopException(Exception): def __init__(self, code, output): self.code = code self.output = output def __str__(self): return "%s code %s output %s" % (self.__class__.__name__, self.code, self.output) class RunLoop(Run): """Main process is a while loop which reads the output in blocks need to read from time to time. otherwise the stdout/stderr buffer gets filled and it all stops working """ LOOP_TIMEOUT_INIT = 0.1 LOOP_TIMEOUT_MAIN = 1 def __init__(self, cmd, **kwargs): super(RunLoop, self).__init__(cmd, **kwargs) self._loop_count = None self._loop_continue = None # intial state, change this to break out the loop def _wait_for_process(self): """Loop through the process in timesteps collected output is run through _loop_process_output """ # these are initialised outside the function (cannot be forgotten, but can be overwritten) self._loop_count = 0 # internal counter self._loop_continue = True self._process_output = '' # further initialisation self._loop_initialise() time.sleep(self.LOOP_TIMEOUT_INIT) ec = self._process.poll() try: while self._loop_continue and ec < 0: output = self._read_process() self._process_output += output # process after updating the self._process_ vars self._loop_process_output(output) if len(output) == 0: time.sleep(self.LOOP_TIMEOUT_MAIN) ec = self._process.poll() self._loop_count += 1 self.log.debug("_wait_for_process: loop stopped after %s iterations (ec %s loop_continue %s)" % (self._loop_count, ec, self._loop_continue)) # read remaining data (all of it) output = self._read_process(-1) self._process_output += output self._process_exitcode = ec # process after updating the self._process_ vars self._loop_process_output_final(output) except RunLoopException, err: self.log.debug('RunLoopException %s' % err) self._process_output = err.output self._process_exitcode = err.code def _loop_initialise(self): """Initialisation before the loop starts""" pass def _loop_process_output(self, output): """Process the output that is read in blocks simplest form: do nothing """ pass def _loop_process_output_final(self, output): """Process the remaining output that is read simplest form: do the same as _loop_process_output """ self._loop_process_output(output) class RunLoopLog(RunLoop): LOOP_LOG_LEVEL = logging.INFO def _wait_for_process(self): # initialise the info logger self.log.info("Going to run cmd %s" % self._shellcmd) super(RunLoopLog, self)._wait_for_process() def _loop_process_output(self, output): """Process the output that is read in blocks send it to the logger. The logger need to be stream-like """ self.log.streamLog(self.LOOP_LOG_LEVEL, output) super(RunLoopLog, self)._loop_process_output(output) class RunLoopStdout(RunLoop): def _loop_process_output(self, output): """Process the output that is read in blocks send it to the stdout """ sys.stdout.write(output) sys.stdout.flush() super(RunLoopStdout, self)._loop_process_output(output) class RunAsync(Run): """Async process class""" def _prep_module(self, modulepath=None, extendfromlist=None): # these will provide the required Popen, PIPE and STDOUT if modulepath is None: modulepath = PROCESS_MODULE_ASYNCPROCESS_PATH if extendfromlist is None: extendfromlist = ['send_all', 'recv_some'] super(RunAsync, self)._prep_module(modulepath=modulepath, extendfromlist=extendfromlist) def _read_process(self, readsize=None): """Read from async process, return out""" if readsize is None: readsize = self.readsize if self._process.stdout is None: # Nothing yet/anymore return '' try: if readsize is not None and readsize < 0: # read all blocking (it's not why we should use async out = self._process.stdout.read() else: # non-blocking read (readsize is a maximum to return ! out = self._process_module.recv_some(self._process, maxread=readsize) return out except (IOError, Exception): # recv_some may throw Exception self.log.exception("_read_process: read failed") return '' class RunFile(Run): """Popen to filehandle""" def __init__(self, cmd, **kwargs): self.filename = kwargs.pop('filename', None) self.filehandle = None super(RunFile, self).__init__(cmd, **kwargs) def _make_popen_named_args(self, others=None): if others is None: if os.path.exists(self.filename): if os.path.isfile(self.filename): self.log.warning("_make_popen_named_args: going to overwrite existing file %s" % self.filename) elif os.path.isdir(self.filename): self.raiseException(("_make_popen_named_args: writing to filename %s impossible. Path exists and " "is a directory.") % self.filename) else: self.raiseException("_make_popen_named_args: path exists and is not a file or directory %s" % self.filename) else: dirname = os.path.dirname(self.filename) if dirname and not os.path.isdir(dirname): try: os.makedirs(dirname) except: self.log.raiseException(("_make_popen_named_args: dirname %s for file %s does not exists. " "Creating it failed.") % (dirname, self.filename)) try: self.filehandle = open(self.filename, 'w') except: self.log.raiseException("_make_popen_named_args: failed to open filehandle for file %s" % self.filename) others = { 'stdout': self.filehandle, } super(RunFile, self)._make_popen_named_args(others=others) def _cleanup_process(self): """Close the filehandle""" try: self.filehandle.close() except: self.log.raiseException("_cleanup_process: failed to close filehandle for filename %s" % self.filename) def _read_process(self, readsize=None): """Meaningless for filehandle""" return '' class RunPty(Run): """Pty support (eg for screen sessions)""" def _read_process(self, readsize=None): """This does not work for pty""" return '' def _make_popen_named_args(self, others=None): if others is None: (master, slave) = pty.openpty() others = { 'stdin': slave, 'stdout': slave, 'stderr': slave } super(RunPty, self)._make_popen_named_args(others=others) class RunTimeout(RunLoop, RunAsync): """Question/Answer processing""" def __init__(self, cmd, **kwargs): self.timeout = float(kwargs.pop('timeout', None)) self.start = time.time() super(RunTimeout, self).__init__(cmd, **kwargs) def _loop_process_output(self, output): """""" time_passed = time.time() - self.start if self.timeout is not None and time_passed > self.timeout: self.log.debug("Time passed %s > timeout %s." % (time_passed, self.timeout)) self.stop_tasks() # go out of loop raise RunLoopException(RUNRUN_TIMEOUT_EXITCODE, RUNRUN_TIMEOUT_OUTPUT) super(RunTimeout, self)._loop_process_output(output) class RunQA(RunLoop, RunAsync): """Question/Answer processing""" LOOP_MAX_MISS_COUNT = 20 INIT_INPUT_CLOSE = False CYCLE_ANSWERS = True def __init__(self, cmd, **kwargs): """ Add question and answer style running @param qa: dict with exact questions and answers @param qa_reg: dict with (named) regex-questions and answers (answers can contain named string templates) @param no_qa: list of regex that can block the output, but is not seen as a question. Regular expressions are compiled, just pass the (raw) text. """ qa = kwargs.pop('qa', {}) qa_reg = kwargs.pop('qa_reg', {}) no_qa = kwargs.pop('no_qa', []) self._loop_miss_count = None # maximum number of misses self._loop_previous_ouput_length = None # track length of output through loop super(RunQA, self).__init__(cmd, **kwargs) self.qa, self.qa_reg, self.no_qa = self._parse_qa(qa, qa_reg, no_qa) def _parse_qa(self, qa, qa_reg, no_qa): """ process the QandA dictionary - given initial set of Q and A (in dict), return dict of reg. exp. and A - make regular expression that matches the string with - replace whitespace - replace newline - qa_reg: question is compiled as is, and whitespace+ending is added - provided answers can be either strings or lists of strings (which will be used iteratively) """ def escape_special(string): specials = '.*+?(){}[]|\$^' return re.sub(r"([%s])" % ''.join(['\%s' % x for x in specials]), r"\\\1", string) SPLIT = '[\s\n]+' REG_SPLIT = re.compile(r"" + SPLIT) def process_answers(answers): """Construct list of newline-terminated answers (as strings).""" if isinstance(answers, basestring): answers = [answers] elif isinstance(answers, list): # list is manipulated when answering matching question, so take a copy answers = answers[:] else: msg_tmpl = "Invalid type for answer, not a string or list: %s (%s)" self.log.raiseException(msg_tmpl % (type(answers), answers), exception=TypeError) # add optional split at the end for i in [idx for idx, a in enumerate(answers) if not a.endswith('\n')]: answers[i] += '\n' return answers def process_question(question): """Convert string question to regex.""" split_q = [escape_special(x) for x in REG_SPLIT.split(question)] reg_q_txt = SPLIT.join(split_q) + SPLIT.rstrip('+') + "*$" reg_q = re.compile(r"" + reg_q_txt) if reg_q.search(question): return reg_q else: # this is just a sanity check on the created regex, can this actually occur? msg_tmpl = "_parse_qa process_question: question %s converted in %s does not match itself" self.log.raiseException(msg_tmpl % (question.pattern, reg_q_txt), exception=ValueError) new_qa = {} self.log.debug("new_qa: ") for question, answers in qa.items(): reg_q = process_question(question) new_qa[reg_q] = process_answers(answers) self.log.debug("new_qa[%s]: %s" % (reg_q.pattern.__repr__(), answers)) new_qa_reg = {} self.log.debug("new_qa_reg: ") for question, answers in qa_reg.items(): reg_q = re.compile(r"" + question + r"[\s\n]*$") new_qa_reg[reg_q] = process_answers(answers) self.log.debug("new_qa_reg[%s]: %s" % (reg_q.pattern.__repr__(), answers)) # simple statements, can contain wildcards new_no_qa = [re.compile(r"" + x + r"[\s\n]*$") for x in no_qa] self.log.debug("new_no_qa: %s" % [x.pattern.__repr__() for x in new_no_qa]) return new_qa, new_qa_reg, new_no_qa def _loop_initialise(self): """Initialisation before the loop starts""" self._loop_miss_count = 0 self._loop_previous_ouput_length = 0 def _loop_process_output(self, output): """Process the output that is read in blocks check the output passed to questions available """ hit = False self.log.debug('output %s all_output %s' % (output, self._process_output)) # qa first and then qa_reg nr_qa = len(self.qa) for idx, (question, answers) in enumerate(self.qa.items() + self.qa_reg.items()): res = question.search(self._process_output) if output and res: answer = answers[0] % res.groupdict() if len(answers) > 1: prev_answer = answers.pop(0) if self.CYCLE_ANSWERS: answers.append(prev_answer) self.log.debug("New answers list for question %s: %s" % (question.pattern, answers)) self.log.debug("_loop_process_output: answer %s question %s (std: %s) out %s" % (answer, question.pattern, idx >= nr_qa, self._process_output[-50:])) self._process_module.send_all(self._process, answer) hit = True break if not hit: curoutlen = len(self._process_output) if curoutlen > self._loop_previous_ouput_length: # still progress in output, just continue (but don't reset miss counter either) self._loop_previous_ouput_length = curoutlen else: noqa = False for r in self.no_qa: if r.search(self._process_output): self.log.debug("_loop_process_output: no_qa found for out %s" % self._process_output[-50:]) noqa = True if not noqa: self._loop_miss_count += 1 else: self._loop_miss_count = 0 # rreset miss counter on hit if self._loop_miss_count > self.LOOP_MAX_MISS_COUNT: self.log.debug("loop_process_output: max misses LOOP_MAX_MISS_COUNT %s reached. End of output: %s" % (self.LOOP_MAX_MISS_COUNT, self._process_output[-500:])) self.stop_tasks() # go out of loop raise RunLoopException(RUNRUN_QA_MAX_MISS_EXITCODE, self._process_output) super(RunQA, self)._loop_process_output(output) class RunAsyncLoop(RunLoop, RunAsync): """Async read in loop""" pass class RunAsyncLoopLog(RunLoopLog, RunAsync): """Async read, log to logger""" pass class RunQALog(RunLoopLog, RunQA): """Async loop QA with LoopLog""" pass class RunQAStdout(RunLoopStdout, RunQA): """Async loop QA with LoopLogStdout""" pass class RunAsyncLoopStdout(RunLoopStdout, RunAsync): """Async read, flush to stdout""" pass # convenient names # eg: from vsc.utils.run import trivial run_simple = Run.run run_simple_noworries = RunNoWorries.run run_async = RunAsync.run run_asyncloop = RunAsyncLoop.run run_timeout = RunTimeout.run run_to_file = RunFile.run run_async_to_stdout = RunAsyncLoopStdout.run run_qa = RunQA.run run_qalog = RunQALog.run run_qastdout = RunQAStdout.run if __name__ == "__main__": run_simple('echo ok')
lgpl-2.1
nzavagli/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Python-2.7.10/Tools/framer/framer/member.py
50
1933
from framer import template from framer.util import cstring, unindent T_SHORT = "T_SHORT" T_INT = "T_INT" T_LONG = "T_LONG" T_FLOAT = "T_FLOAT" T_DOUBLE = "T_DOUBLE" T_STRING = "T_STRING" T_OBJECT = "T_OBJECT" T_CHAR = "T_CHAR" T_BYTE = "T_BYTE" T_UBYTE = "T_UBYTE" T_UINT = "T_UINT" T_ULONG = "T_ULONG" T_STRING_INPLACE = "T_STRING_INPLACE" T_OBJECT_EX = "T_OBJECT_EX" RO = READONLY = "READONLY" READ_RESTRICTED = "READ_RESTRICTED" WRITE_RESTRICTED = "WRITE_RESTRICTED" RESTRICT = "RESTRICTED" c2t = {"int" : T_INT, "unsigned int" : T_UINT, "long" : T_LONG, "unsigned long" : T_LONG, "float" : T_FLOAT, "double" : T_DOUBLE, "char *" : T_CHAR, "PyObject *" : T_OBJECT, } class member(object): def __init__(self, cname=None, type=None, flags=None, doc=None): self.type = type self.flags = flags self.cname = cname self.doc = doc self.name = None self.struct = None def register(self, name, struct): self.name = name self.struct = struct self.initvars() def initvars(self): v = self.vars = {} v["PythonName"] = self.name if self.cname is not None: v["CName"] = self.cname else: v["CName"] = self.name v["Flags"] = self.flags or "0" v["Type"] = self.get_type() if self.doc is not None: v["Docstring"] = cstring(unindent(self.doc)) v["StructName"] = self.struct.name def get_type(self): """Deduce type code from struct specification if not defined""" if self.type is not None: return self.type ctype = self.struct.get_type(self.name) return c2t[ctype] def dump(self, f): if self.doc is None: print >> f, template.memberdef_def % self.vars else: print >> f, template.memberdef_def_doc % self.vars
mit
danielvdao/TheAnimalFarm
venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py
93
12036
'''SSL with SNI-support for Python 2. This needs the following packages installed: * pyOpenSSL (tested with 0.13) * ndg-httpsclient (tested with 0.3.2) * pyasn1 (tested with 0.1.6) To activate it call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3`. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this:: try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass Now you can use :mod:`urllib3` as you normally would, and it will support SNI when the required modules are installed. ''' from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT from ndg.httpsclient.subj_alt_name import SubjectAltName import OpenSSL.SSL from pyasn1.codec.der import decoder as der_decoder from socket import _fileobject import ssl import select from cStringIO import StringIO from .. import connection from .. import util __all__ = ['inject_into_urllib3', 'extract_from_urllib3'] # SNI only *really* works if we can read the subjectAltName of certificates. HAS_SNI = SUBJ_ALT_NAME_SUPPORT # Map from urllib3 to PyOpenSSL compatible parameter-values. _openssl_versions = { ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD, ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, } _openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } orig_util_HAS_SNI = util.HAS_SNI orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket def inject_into_urllib3(): 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.' connection.ssl_wrap_socket = ssl_wrap_socket util.HAS_SNI = HAS_SNI def extract_from_urllib3(): 'Undo monkey-patching by :func:`inject_into_urllib3`.' connection.ssl_wrap_socket = orig_connection_ssl_wrap_socket util.HAS_SNI = orig_util_HAS_SNI ### Note: This is a slightly bug-fixed version of same from ndg-httpsclient. def get_subj_alt_name(peer_cert): # Search through extensions dns_name = [] if not SUBJ_ALT_NAME_SUPPORT: return dns_name general_names = SubjectAltName() for i in range(peer_cert.get_extension_count()): ext = peer_cert.get_extension(i) ext_name = ext.get_short_name() if ext_name != 'subjectAltName': continue # PyOpenSSL returns extension data in ASN.1 encoded form ext_dat = ext.get_data() decoded_dat = der_decoder.decode(ext_dat, asn1Spec=general_names) for name in decoded_dat: if not isinstance(name, SubjectAltName): continue for entry in range(len(name)): component = name.getComponentByPosition(entry) if component.getName() != 'dNSName': continue dns_name.append(str(component.getComponent())) return dns_name class fileobject(_fileobject): def read(self, size=-1): # Use max, disallow tiny reads in a loop as they are very inefficient. # We never leave read() with any leftover data from a new recv() call # in our internal buffer. rbufsize = max(self._rbufsize, self.default_bufsize) # Our use of StringIO rather than lists of string objects returned by # recv() minimizes memory usage and fragmentation that occurs when # rbufsize is large compared to the typical return value of recv(). buf = self._rbuf buf.seek(0, 2) # seek end if size < 0: # Read until EOF self._rbuf = StringIO() # reset _rbuf. we consume it via buf. while True: try: data = self._sock.recv(rbufsize) except OpenSSL.SSL.WantReadError: continue if not data: break buf.write(data) return buf.getvalue() else: # Read until size bytes or EOF seen, whichever comes first buf_len = buf.tell() if buf_len >= size: # Already have size bytes in our buffer? Extract and return. buf.seek(0) rv = buf.read(size) self._rbuf = StringIO() self._rbuf.write(buf.read()) return rv self._rbuf = StringIO() # reset _rbuf. we consume it via buf. while True: left = size - buf_len # recv() will malloc the amount of memory given as its # parameter even though it often returns much less data # than that. The returned data string is short lived # as we copy it into a StringIO and free it. This avoids # fragmentation issues on many platforms. try: data = self._sock.recv(left) except OpenSSL.SSL.WantReadError: continue if not data: break n = len(data) if n == size and not buf_len: # Shortcut. Avoid buffer data copies when: # - We have no data in our buffer. # AND # - Our call to recv returned exactly the # number of bytes we were asked to read. return data if n == left: buf.write(data) del data # explicit free break assert n <= left, "recv(%d) returned %d bytes" % (left, n) buf.write(data) buf_len += n del data # explicit free #assert buf_len == buf.tell() return buf.getvalue() def readline(self, size=-1): buf = self._rbuf buf.seek(0, 2) # seek end if buf.tell() > 0: # check if we already have it in our buffer buf.seek(0) bline = buf.readline(size) if bline.endswith('\n') or len(bline) == size: self._rbuf = StringIO() self._rbuf.write(buf.read()) return bline del bline if size < 0: # Read until \n or EOF, whichever comes first if self._rbufsize <= 1: # Speed up unbuffered case buf.seek(0) buffers = [buf.read()] self._rbuf = StringIO() # reset _rbuf. we consume it via buf. data = None recv = self._sock.recv while True: try: while data != "\n": data = recv(1) if not data: break buffers.append(data) except OpenSSL.SSL.WantReadError: continue break return "".join(buffers) buf.seek(0, 2) # seek end self._rbuf = StringIO() # reset _rbuf. we consume it via buf. while True: try: data = self._sock.recv(self._rbufsize) except OpenSSL.SSL.WantReadError: continue if not data: break nl = data.find('\n') if nl >= 0: nl += 1 buf.write(data[:nl]) self._rbuf.write(data[nl:]) del data break buf.write(data) return buf.getvalue() else: # Read until size bytes or \n or EOF seen, whichever comes first buf.seek(0, 2) # seek end buf_len = buf.tell() if buf_len >= size: buf.seek(0) rv = buf.read(size) self._rbuf = StringIO() self._rbuf.write(buf.read()) return rv self._rbuf = StringIO() # reset _rbuf. we consume it via buf. while True: try: data = self._sock.recv(self._rbufsize) except OpenSSL.SSL.WantReadError: continue if not data: break left = size - buf_len # did we just receive a newline? nl = data.find('\n', 0, left) if nl >= 0: nl += 1 # save the excess data to _rbuf self._rbuf.write(data[nl:]) if buf_len: buf.write(data[:nl]) break else: # Shortcut. Avoid data copy through buf when returning # a substring of our first recv(). return data[:nl] n = len(data) if n == size and not buf_len: # Shortcut. Avoid data copy through buf when # returning exactly all of our first recv(). return data if n >= left: buf.write(data[:left]) self._rbuf.write(data[left:]) break buf.write(data) buf_len += n #assert buf_len == buf.tell() return buf.getvalue() class WrappedSocket(object): '''API-compatibility wrapper for Python OpenSSL's Connection-class.''' def __init__(self, connection, socket): self.connection = connection self.socket = socket def fileno(self): return self.socket.fileno() def makefile(self, mode, bufsize=-1): return fileobject(self.connection, mode, bufsize) def settimeout(self, timeout): return self.socket.settimeout(timeout) def sendall(self, data): return self.connection.sendall(data) def close(self): return self.connection.shutdown() def getpeercert(self, binary_form=False): x509 = self.connection.get_peer_certificate() if not x509: return x509 if binary_form: return OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_ASN1, x509) return { 'subject': ( (('commonName', x509.get_subject().CN),), ), 'subjectAltName': [ ('DNS', value) for value in get_subj_alt_name(x509) ] } def _verify_callback(cnx, x509, err_no, err_depth, return_code): return err_no == 0 def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None): ctx = OpenSSL.SSL.Context(_openssl_versions[ssl_version]) if certfile: ctx.use_certificate_file(certfile) if keyfile: ctx.use_privatekey_file(keyfile) if cert_reqs != ssl.CERT_NONE: ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback) if ca_certs: try: ctx.load_verify_locations(ca_certs, None) except OpenSSL.SSL.Error as e: raise ssl.SSLError('bad ca_certs: %r' % ca_certs, e) cnx = OpenSSL.SSL.Connection(ctx, sock) cnx.set_tlsext_host_name(server_hostname) cnx.set_connect_state() while True: try: cnx.do_handshake() except OpenSSL.SSL.WantReadError: select.select([sock], [], []) continue except OpenSSL.SSL.Error as e: raise ssl.SSLError('bad handshake', e) break return WrappedSocket(cnx, sock)
gpl-2.0
jamessergeant/pylearn2
pylearn2/utils/utlc.py
49
7347
"""Several utilities for experimenting upon utlc datasets""" # Standard library imports import logging import os import inspect import zipfile from tempfile import TemporaryFile # Third-party imports import numpy import theano from pylearn2.datasets.utlc import load_ndarray_dataset, load_sparse_dataset from pylearn2.utils import subdict, sharedX logger = logging.getLogger(__name__) ################################################## # Shortcuts and auxiliary functions ################################################## def getboth(dict1, dict2, key, default=None): """ Try to retrieve key from dict1 if exists, otherwise try with dict2. If the key is not found in any of them, raise an exception. Parameters ---------- dict1 : dict WRITEME dict2 : dict WRITEME key : WRITEME default : WRITEME Returns ------- WRITEME """ try: return dict1[key] except KeyError: if default is None: return dict2[key] else: return dict2.get(key, default) ################################################## # Datasets loading and contest facilities ################################################## def load_data(conf): """ Loads a specified dataset according to the parameters in the dictionary Parameters ---------- conf : WRITEME Returns ------- WRITEME """ logger.info('... loading dataset') # Special case for sparse format if conf.get('sparse', False): expected = inspect.getargspec(load_sparse_dataset)[0][1:] data = load_sparse_dataset(conf['dataset'], **subdict(conf, expected)) valid, test = data[1:3] # Sparse TERRY data on LISA servers contains an extra null first row in # valid and test subsets. if conf['dataset'] == 'terry': valid = valid[1:] test = test[1:] assert valid.shape[0] == test.shape[0] == 4096, \ 'Sparse TERRY data loaded has wrong number of examples' if len(data) == 3: return [data[0], valid, test] else: return [data[0], valid, test, data[3]] # Load as the usual ndarray expected = inspect.getargspec(load_ndarray_dataset)[0][1:] data = load_ndarray_dataset(conf['dataset'], **subdict(conf, expected)) # Special case for on-the-fly normalization if conf.get('normalize_on_the_fly', False): return data # Allocate shared variables def shared_dataset(data_x): """Function that loads the dataset into shared variables""" if conf.get('normalize', True): return sharedX(data_x, borrow=True) else: return theano.shared(theano._asarray(data_x), borrow=True) return map(shared_dataset, data) def save_submission(conf, valid_repr, test_repr): """ Create a submission file given a configuration dictionary and a representation for valid and test. Parameters ---------- conf : WRITEME valid_repr : WRITEME test_repr : WRITEME """ logger.info('... creating zipfile') # Ensure the given directory is correct submit_dir = conf['savedir'] if not os.path.exists(submit_dir): os.makedirs(submit_dir) elif not os.path.isdir(submit_dir): raise IOError('savedir %s is not a directory' % submit_dir) basename = os.path.join(submit_dir, conf['dataset'] + '_' + conf['expname']) # If there are too much features, outputs kernel matrices if (valid_repr.shape[1] > valid_repr.shape[0]): valid_repr = numpy.dot(valid_repr, valid_repr.T) test_repr = numpy.dot(test_repr, test_repr.T) # Quantitize data valid_repr = numpy.floor((valid_repr / valid_repr.max())*999) test_repr = numpy.floor((test_repr / test_repr.max())*999) # Store the representations in two temporary files valid_file = TemporaryFile() test_file = TemporaryFile() numpy.savetxt(valid_file, valid_repr, fmt="%.3f") numpy.savetxt(test_file, test_repr, fmt="%.3f") # Reread those files and put them together in a .zip valid_file.seek(0) test_file.seek(0) submission = zipfile.ZipFile(basename + ".zip", "w", compression=zipfile.ZIP_DEFLATED) submission.writestr(basename + '_valid.prepro', valid_file.read()) submission.writestr(basename + '_final.prepro', test_file.read()) submission.close() valid_file.close() test_file.close() def create_submission(conf, transform_valid, transform_test=None, features=None): """ Create a submission file given a configuration dictionary and a computation function. Note that it always reload the datasets to ensure valid & test are not permuted. Parameters ---------- conf : WRITEME transform_valid : WRITEME transform_test : WRITEME features : WRITEME """ if transform_test is None: transform_test = transform_valid # Load the dataset, without permuting valid and test kwargs = subdict(conf, ['dataset', 'normalize', 'normalize_on_the_fly', 'sparse']) kwargs.update(randomize_valid=False, randomize_test=False) valid_set, test_set = load_data(kwargs)[1:3] # Sparse datasets are not stored as Theano shared vars. if not conf.get('sparse', False): valid_set = valid_set.get_value(borrow=True) test_set = test_set.get_value(borrow=True) # Prefilter features, if needed. if features is not None: valid_set = valid_set[:, features] test_set = test_set[:, features] # Valid and test representations valid_repr = transform_valid(valid_set) test_repr = transform_test(test_set) # Convert into text info save_submission(conf, valid_repr, test_repr) ################################################## # Proxies for representation evaluations ################################################## def compute_alc(valid_repr, test_repr): """ Returns the ALC of the valid set VS test set Note: This proxy won't work in the case of transductive learning (This is an assumption) but it seems to be a good proxy in the normal case (i.e only train on training set) Parameters ---------- valid_repr : WRITEME test_repr : WRITEME Returns ------- WRITEME """ # Concatenate the sets, and give different one hot labels for valid and test n_valid = valid_repr.shape[0] n_test = test_repr.shape[0] _labvalid = numpy.hstack((numpy.ones((n_valid, 1)), numpy.zeros((n_valid, 1)))) _labtest = numpy.hstack((numpy.zeros((n_test, 1)), numpy.ones((n_test, 1)))) dataset = numpy.vstack((valid_repr, test_repr)) label = numpy.vstack((_labvalid, _labtest)) logger.info('... computing the ALC') raise NotImplementedError("This got broken by embed no longer being " "where it used to be (if it even still exists, I haven't " "looked for it)") # return embed.score(dataset, label) def lookup_alc(data, transform): """ .. todo:: WRITEME """ valid_repr = transform(data[1].get_value(borrow=True)) test_repr = transform(data[2].get_value(borrow=True)) return compute_alc(valid_repr, test_repr)
bsd-3-clause
pmisik/buildbot
master/buildbot/scripts/tryserver.py
5
1481
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This 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. # # Copyright Buildbot Team Members import os import sys import time from hashlib import md5 from buildbot.util import unicode2bytes def tryserver(config): jobdir = os.path.expanduser(config["jobdir"]) job = sys.stdin.read() # now do a 'safecat'-style write to jobdir/tmp, then move atomically to # jobdir/new . Rather than come up with a unique name randomly, I'm just # going to MD5 the contents and prepend a timestamp. timestring = "%d" % time.time() m = md5() job = unicode2bytes(job) m.update(job) jobhash = m.hexdigest() fn = "{}-{}".format(timestring, jobhash) tmpfile = os.path.join(jobdir, "tmp", fn) newfile = os.path.join(jobdir, "new", fn) with open(tmpfile, "wb") as f: f.write(job) os.rename(tmpfile, newfile) return 0
gpl-2.0
madoodia/codeLab
python/Built-in_Functions.py
1
15493
######################################### Built-in Functions ######################################### abs(x) # Return the absolute value of a number # ......................................... all(iterable) # Return True if all elements of the iterable are true # equivalent to: def all(iterable): for element in iterable: if not element: return False return True # ......................................... any(iterable) # Return True if any element of the iterable is true def any(iterable): for element in iterable: if element: return True return False # ......................................... basestring() # This abstract type is the superclass for str and unicode obj = 'hello' isinstance(obj, basestring) # Return True # ......................................... bin(x) # Convert an integer number to a binary string # ......................................... bool([x]) # Convert a value to a Boolean, using the standard truth testing procedure # ......................................... bytearray([source[, encoding[, errors]]]) # Return a new array of bytes # ......................................... callable(object) # Return True if the object argument appears callable, False if not def test(): pass callable(test) # Return True class A: pass a = A() callable(A) # Return True callable(a) # Return False class B: def __call__(self): pass b = B() callable(B) # Return True callable(b) # Return True # ......................................... chr(i) # Return a string of one character whose ASCII code is the integer i # ......................................... classmethod(function) # Return a class method for function. class C(object): @classmethod def f(cls, arg1, arg2, ...): ... # The @classmethod form is a function decorator # It can be called either on the class (such as C.f()) or on an instance (such as C().f()). # The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. # ......................................... cmp(x, y) # Compare the two objects x and y and return an integer according to the outcome # ......................................... compile(source, filename, mode[, flags[, dont_inherit]]) # Compile the source into a code or AST object # ......................................... complex([real[, imag]]) # Create a complex number with the value real + imag*j or convert a string or number to a complex number # ......................................... delattr(object, name) # This is a relative of setattr(). The arguments are an object and a string # ......................................... dict(**kwarg) dict(mapping, **kwarg) dict(iterable, **kwarg) # Create a new dictionary. The dict object is the dictionary class # ......................................... dir([object]) # Without arguments, return the list of names in the current local scope class Shape(object): def __dir__(self): return ['area', 'perimeter', 'location'] s = Shape() dir(s) # ['area', 'perimeter', 'location'] # ......................................... divmod(a, b) # Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division # ......................................... enumerate(sequence, start=0) # Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration seasons = ['Spring', 'Summer', 'Fall', 'Winter'] list(enumerate(seasons)) # [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] list(enumerate(seasons, start=1)) # [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] # Equivalent to: def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 # ......................................... eval(expression[, globals[, locals]]) # The arguments are a Unicode or Latin-1 encoded string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object. # ......................................... execfile(filename[, globals[, locals]]) # This function is similar to the exec statement, but parses a file instead of a string # ......................................... file(name[, mode[, buffering]]) # Constructor function for the file type, described further in section File Objects isinstance(f, file) # ......................................... filter(function, iterable) # Construct a list from those elements of iterable for which function returns true # Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] # ......................................... float([x]) # Convert a string or a number to floating point # ......................................... format(value[, format_spec]) # Convert a value to a “formatted” representation, as controlled by format_spec # ......................................... frozenset([iterable]) # Return a new frozenset object, optionally with elements taken from iterable # ......................................... getattr(object, name[, default]) # Return the value of the named attribute of object # ......................................... globals() # Return a dictionary representing the current global symbol table # ......................................... hasattr(object, name) # The arguments are an object and a string # ......................................... hash(object) # Return the hash value of the object (if it has one). Hash values are integers # ......................................... help([object]) # Invoke the built-in help system # ......................................... hex(x) # Convert an integer number (of any size) to a hexadecimal string # ......................................... id(object) # Return the “identity” of an object # ......................................... input([prompt]) # Equivalent to eval(raw_input(prompt)). # ......................................... int(x=0) int(x, base=10) # Convert a number or string x to an integer, or return 0 if no arguments are given # ......................................... isinstance(object, classinfo) # Return true if the object argument is an instance of the classinfo argument # ......................................... issubclass(class, classinfo) # Return true if class is a subclass (direct, indirect or virtual) of classinfo # ......................................... iter(o[, sentinel]) # Return an iterator object with open('mydata.txt') as fp: for line in iter(fp.readline, ''): process_line(line) # ......................................... len(s) # Return the length (the number of items) of an object # ......................................... list([iterable]) # Return a list whose items are the same and in the same order as iterable‘s items # ......................................... locals() # Update and return a dictionary representing the current local symbol table # ......................................... long(x=0) long(x, base=10) # Convert a string or number to a long integer. # ......................................... map(function, iterable, ...) # Apply function to every item of iterable and return a list of the results def adder(a, b): return a + b numbers1 = [2, 4, 6, 8, 1, 10, 8, 9] numbers2 = [4, 6, 8, 1, 10, 8, 9, 1] mapper = map(adder, numbers1, numbers2) # Result: [6, 10, 14, 9, 11, 18, 17, 10] # # ......................................... max(iterable[, key]) max(arg1, arg2, *args[, key]) # Return the largest item in an iterable or the largest of two or more arguments. # ......................................... memoryview(obj) # Return a “memory view” object created from the given argument # ......................................... min(iterable[, key]) min(arg1, arg2, *args[, key]) # Return the smallest item in an iterable or the smallest of two or more arguments. # ......................................... next(iterator[, default]) # Retrieve the next item from the iterator by calling its next() method # ......................................... object() # Return a new featureless object # ......................................... oct(x) # Convert an integer number (of any size) to an octal string # ......................................... open(name[, mode[, buffering]]) # Open a file, returning an object of the file type described in section File Objects. If the file cannot be opened, IOError is raised # ......................................... ord(c) # Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object # ......................................... pow(x, y[, z]) # Return x to the power y # pow(x, y) is equivalent to using the power operator: x**y # To disable the statement and use the print() function, use this future statement at the top of your module: from __future__ import print_function # ......................................... property([fget[, fset[, fdel[, doc]]]]) # Return a property attribute for new-style classes (classes that derive from object). class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") # If then c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter and del c.x the deleter. class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage # turns the voltage() method into a “getter” for a read-only attribute with the same name class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x # ......................................... range(stop) range(start, stop[, step]) # This is a versatile function to create lists containing arithmetic progressions range(10) range(1, 11) range(0, 30, 5) range(0, 10, 3) range(0, -10, -1) range(0) range(1, 0) # ......................................... raw_input([prompt]) # If the prompt argument is present, it is written to standard output without a trailing newline s = raw_input('--> ') # --> # ......................................... reduce(function, iterable[, initializer]) # Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: try: initializer = next(it) except StopIteration: raise TypeError('reduce() of empty sequence with no initial value') accum_value = initializer for x in it: accum_value = function(accum_value, x) return accum_value # ......................................... reload(module) # Reload a previously imported module # ......................................... repr(object) # Return a string containing a printable representation of an object. This is the same value yielded by conversions # A class can control what this function returns for its instances by defining a __repr__() method. # ......................................... reversed(seq) # Return a reverse iterator. # ......................................... round(number[, ndigits]) # Return the floating point value number rounded to ndigits digits after the decimal point # ......................................... set([iterable]) # Return a new set object, optionally with elements taken from iterable # ......................................... setattr(object, name, value) # This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value # For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123. # ......................................... slice(stop) slice(start, stop[, step]) # Return a slice object representing the set of indices specified by range(start, stop, step) # ......................................... sorted(iterable[, cmp[, key[, reverse]]]) # Return a new sorted list from the items in iterable. cmp=lambda x,y: cmp(x.lower(), y.lower()) # ......................................... staticmethod(function) # Return a static method for function. class C(object): @staticmethod def f(arg1, arg2, ...): ... # It can be called either on the class (such as C.f()) or on an instance (such as C().f()). # ......................................... str(object='') # Return a string containing a nicely printable representation of an object. # ......................................... sum(iterable[, start]) # Sums start and the items of an iterable from left to right and returns the total # ......................................... super(type[, object-or-type]) # Return a proxy object that delegates method calls to a parent or sibling class of type # Note: super() only works for new-style classes. class C(B): def method(self, arg): super(C, self).method(arg) # ......................................... tuple([iterable]) # Return a tuple whose items are the same and in the same order as iterable‘s items # ......................................... type(object) # With one argument, return the type of an object. The return value is a type object type(name, bases, dict) # With three arguments, return a new type object # This is essentially a dynamic form of the class statement. class X(object): a = 1 X = type('X', (object,), dict(a=1)) # ......................................... unichr(i) # Return the Unicode string of one character whose Unicode code is the integer i # ......................................... unicode(object='') unicode(object[, encoding[, errors]]) # Return the Unicode string version of object # ......................................... vars([object]) # Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. # Without an argument, vars() acts like locals(). # ......................................... xrange(stop) xrange(start, stop[, step]) # This function is very similar to range(), but returns an xrange object instead of a list # ......................................... zip([iterable, ...]) # This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables # zip() is similar to map() with an initial argument of None x = [1, 2, 3] y = [4, 5, 6] zipped = zip(x, y) zipped # [(1, 4), (2, 5), (3, 6)] x2, y2 = zip(*zipped) x == list(x2) and y == list(y2) # True # ......................................... __import__(name[, globals[, locals[, fromlist[, level]]]]) # Note: This is an advanced function that is not needed in everyday Python programming # This function is invoked by the import statement # ......................................... # ......................................... # .........................................
mit
pmrowla/goonbcs
goonbcs/models.py
1
3450
# Copyright (c) 2013 Peter Rowlands from __future__ import absolute_import from flask.ext.security import UserMixin, RoleMixin from . import db class Conference(db.Model): """A college football conference""" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), unique=True) subdivision_id = db.Column(db.Integer, db.ForeignKey('subdivision.id')) teams = db.relationship('Team', backref='conference', lazy='dynamic') divisions = db.relationship('Division', backref='conference', lazy='dynamic') class Division(db.Model): """A conference division (i.e. the SEC East)""" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), unique=True) conference_id = db.Column(db.Integer, db.ForeignKey('conference.id')) teams = db.relationship('Team', backref='division', lazy='dynamic') class Poll(db.Model): """A single user's poll for a single week""" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) week_id = db.Column(db.Integer, db.ForeignKey('week.id')) moon_poll = db.Column(db.Boolean, default=False) votes = db.relationship('Vote', backref='poll', lazy='dynamic') class Season(db.Model): id = db.Column(db.Integer, primary_key=True) year = db.Column(db.Integer, unique=True) weeks = db.relationship('Week', backref='season', lazy='dynamic') class Subdivision(db.Model): """A college football subdivision (i.e. FBS)""" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) conferences = db.relationship('Conference', backref='subdivision', lazy='dynamic') class Team(db.Model): """A college football team""" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) school = db.Column(db.String(255), unique=True) conference_id = db.Column(db.Integer, db.ForeignKey('conference.id')) division_id = db.Column(db.Integer, db.ForeignKey('division.id')) class Vote(db.Model): id = db.Column(db.Integer, primary_key=True) poll_id = db.Column(db.Integer, db.ForeignKey('poll.id')) team_id = db.Column(db.Integer, db.ForeignKey('team.id')) rank = db.Column(db.Integer) db.UniqueConstraint('poll_id', 'team_id', name='uidx_poll_team') class Week(db.Model): id = db.Column(db.Integer, primary_key=True) num = db.Column(db.Integer) season_id = db.Column(db.Integer, db.ForeignKey('season.id')) ####################### # Flask-security models ####################### roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) polls = db.relationship('Poll', backref='user', lazy='dynamic')
mit
acuicultor/Radioactive-kernel-HAM
tools/perf/scripts/python/syscall-counts-by-pid.py
11180
1927
# system call counts, by pid # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide system call totals, broken down by syscall. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os, sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import syscall_name usage = "perf script -s syscall-counts-by-pid.py [comm]\n"; for_comm = None for_pid = None if len(sys.argv) > 2: sys.exit(usage) if len(sys.argv) > 1: try: for_pid = int(sys.argv[1]) except: for_comm = sys.argv[1] syscalls = autodict() def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): print_syscall_totals() def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): if (for_comm and common_comm != for_comm) or \ (for_pid and common_pid != for_pid ): return try: syscalls[common_comm][common_pid][id] += 1 except TypeError: syscalls[common_comm][common_pid][id] = 1 def print_syscall_totals(): if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events by comm/pid:\n\n", print "%-40s %10s\n" % ("comm [pid]/syscalls", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "----------"), comm_keys = syscalls.keys() for comm in comm_keys: pid_keys = syscalls[comm].keys() for pid in pid_keys: print "\n%s [%d]\n" % (comm, pid), id_keys = syscalls[comm][pid].keys() for id, val in sorted(syscalls[comm][pid].iteritems(), \ key = lambda(k, v): (v, k), reverse = True): print " %-38s %10d\n" % (syscall_name(id), val),
gpl-2.0
draugiskisprendimai/odoo
addons/website/tests/test_views.py
144
9831
# -*- coding: utf-8 -*- import itertools import unittest2 from lxml import etree as ET, html from lxml.html import builder as h from openerp.tests import common def attrs(**kwargs): return dict(('data-oe-%s' % key, str(value)) for key, value in kwargs.iteritems()) class TestViewSaving(common.TransactionCase): def eq(self, a, b): self.assertEqual(a.tag, b.tag) self.assertEqual(a.attrib, b.attrib) self.assertEqual((a.text or '').strip(), (b.text or '').strip()) self.assertEqual((a.tail or '').strip(), (b.tail or '').strip()) for ca, cb in itertools.izip_longest(a, b): self.eq(ca, cb) def setUp(self): super(TestViewSaving, self).setUp() self.arch = h.DIV( h.DIV( h.H3("Column 1"), h.UL( h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))), h.DIV( h.H3("Column 2"), h.UL( h.LI("Item 1"), h.LI(h.SPAN("My Company", attrs(model='res.company', id=1, field='name', type='char'))), h.LI(h.SPAN("+00 00 000 00 0 000", attrs(model='res.company', id=1, field='phone', type='char'))) )) ) self.view_id = self.registry('ir.ui.view').create(self.cr, self.uid, { 'name': "Test View", 'type': 'qweb', 'arch': ET.tostring(self.arch, encoding='utf-8').decode('utf-8') }) def test_embedded_extraction(self): fields = self.registry('ir.ui.view').extract_embedded_fields( self.cr, self.uid, self.arch, context=None) expect = [ h.SPAN("My Company", attrs(model='res.company', id=1, field='name', type='char')), h.SPAN("+00 00 000 00 0 000", attrs(model='res.company', id=1, field='phone', type='char')), ] for actual, expected in itertools.izip_longest(fields, expect): self.eq(actual, expected) def test_embedded_save(self): embedded = h.SPAN("+00 00 000 00 0 000", attrs( model='res.company', id=1, field='phone', type='char')) self.registry('ir.ui.view').save_embedded_field(self.cr, self.uid, embedded) company = self.registry('res.company').browse(self.cr, self.uid, 1) self.assertEqual(company.phone, "+00 00 000 00 0 000") @unittest2.skip("save conflict for embedded (saved by third party or previous version in page) not implemented") def test_embedded_conflict(self): e1 = h.SPAN("My Company", attrs(model='res.company', id=1, field='name')) e2 = h.SPAN("Leeroy Jenkins", attrs(model='res.company', id=1, field='name')) View = self.registry('ir.ui.view') View.save_embedded_field(self.cr, self.uid, e1) # FIXME: more precise exception with self.assertRaises(Exception): View.save_embedded_field(self.cr, self.uid, e2) def test_embedded_to_field_ref(self): View = self.registry('ir.ui.view') embedded = h.SPAN("My Company", attrs(expression="bob")) self.eq( View.to_field_ref(self.cr, self.uid, embedded, context=None), h.SPAN({'t-field': 'bob'}) ) def test_to_field_ref_keep_attributes(self): View = self.registry('ir.ui.view') att = attrs(expression="bob", model="res.company", id=1, field="name") att['id'] = "whop" att['class'] = "foo bar" embedded = h.SPAN("My Company", att) self.eq(View.to_field_ref(self.cr, self.uid, embedded, context=None), h.SPAN({'t-field': 'bob', 'class': 'foo bar', 'id': 'whop'})) def test_replace_arch(self): replacement = h.P("Wheee") result = self.registry('ir.ui.view').replace_arch_section( self.cr, self.uid, self.view_id, None, replacement) self.eq(result, h.DIV("Wheee")) def test_replace_arch_2(self): replacement = h.DIV(h.P("Wheee")) result = self.registry('ir.ui.view').replace_arch_section( self.cr, self.uid, self.view_id, None, replacement) self.eq(result, replacement) def test_fixup_arch(self): replacement = h.H1("I am the greatest title alive!") result = self.registry('ir.ui.view').replace_arch_section( self.cr, self.uid, self.view_id, '/div/div[1]/h3', replacement) self.eq(result, h.DIV( h.DIV( h.H3("I am the greatest title alive!"), h.UL( h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))), h.DIV( h.H3("Column 2"), h.UL( h.LI("Item 1"), h.LI(h.SPAN("My Company", attrs(model='res.company', id=1, field='name', type='char'))), h.LI(h.SPAN("+00 00 000 00 0 000", attrs(model='res.company', id=1, field='phone', type='char'))) )) )) def test_multiple_xpath_matches(self): with self.assertRaises(ValueError): self.registry('ir.ui.view').replace_arch_section( self.cr, self.uid, self.view_id, '/div/div/h3', h.H6("Lol nope")) def test_save(self): Company = self.registry('res.company') View = self.registry('ir.ui.view') replacement = ET.tostring(h.DIV( h.H3("Column 2"), h.UL( h.LI("wob wob wob"), h.LI(h.SPAN("Acme Corporation", attrs(model='res.company', id=1, field='name', expression="bob", type='char'))), h.LI(h.SPAN("+12 3456789", attrs(model='res.company', id=1, field='phone', expression="edmund", type='char'))), ) ), encoding='utf-8') View.save(self.cr, self.uid, res_id=self.view_id, value=replacement, xpath='/div/div[2]') company = Company.browse(self.cr, self.uid, 1) self.assertEqual(company.name, "Acme Corporation") self.assertEqual(company.phone, "+12 3456789") self.eq( ET.fromstring(View.browse(self.cr, self.uid, self.view_id).arch.encode('utf-8')), h.DIV( h.DIV( h.H3("Column 1"), h.UL( h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))), h.DIV( h.H3("Column 2"), h.UL( h.LI("wob wob wob"), h.LI(h.SPAN({'t-field': "bob"})), h.LI(h.SPAN({'t-field': "edmund"})) )) ) ) def test_save_escaped_text(self): """ Test saving html special chars in text nodes """ view_id = self.registry('ir.ui.view').create(self.cr, self.uid, { 'arch':'<t><p><h1>hello world</h1></p></t>', 'type':'qweb' }) view = self.registry('ir.ui.view').browse(self.cr, self.uid, view_id) # script and style text nodes should not escaped client side replacement = '<script>1 && "hello & world"</script>' view.save(replacement, xpath='/t/p/h1') self.assertIn( replacement.replace('&', '&amp;'), view.arch, 'inline script should be escaped server side' ) self.assertIn( replacement, view.render(), 'inline script should not be escaped when rendering' ) # common text nodes should be be escaped client side replacement = 'world &amp;amp; &amp;lt;b&amp;gt;cie' view.save(replacement, xpath='/t/p') self.assertIn(replacement, view.arch, 'common text node should not be escaped server side') self.assertIn( replacement, view.render().replace('&', '&amp;'), 'text node characters wrongly unescaped when rendering' ) def test_save_only_embedded(self): Company = self.registry('res.company') company_id = 1 Company.write(self.cr, self.uid, company_id, {'name': "Foo Corporation"}) node = html.tostring(h.SPAN( "Acme Corporation", attrs(model='res.company', id=company_id, field="name", expression='bob', type='char'))) self.registry('ir.ui.view').save(self.cr, self.uid, res_id=company_id,value=node) company = Company.browse(self.cr, self.uid, company_id) self.assertEqual(company.name, "Acme Corporation") def test_field_tail(self): View = self.registry('ir.ui.view') replacement = ET.tostring( h.LI(h.SPAN("+12 3456789", attrs( model='res.company', id=1, type='char', field='phone', expression="edmund")), "whop whop" ), encoding="utf-8") View.save(self.cr, self.uid, res_id = self.view_id, value=replacement, xpath='/div/div[2]/ul/li[3]') self.eq( ET.fromstring(View.browse(self.cr, self.uid, self.view_id).arch.encode('utf-8')), h.DIV( h.DIV( h.H3("Column 1"), h.UL( h.LI("Item 1"), h.LI("Item 2"), h.LI("Item 3"))), h.DIV( h.H3("Column 2"), h.UL( h.LI("Item 1"), h.LI(h.SPAN("My Company", attrs(model='res.company', id=1, field='name', type='char'))), h.LI(h.SPAN({'t-field': "edmund"}), "whop whop"), )) ) )
agpl-3.0
ryuunosukeyoshi/PartnerPoi-Bot
lib/pip/_vendor/appdirs.py
327
22368
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2005-2010 ActiveState Software Inc. # Copyright (c) 2013 Eddy Petrișor """Utilities for determining application-specific dirs. See <http://github.com/ActiveState/appdirs> for details and usage. """ # Dev Notes: # - MSDN on where to store app data files: # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 # - macOS: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html # - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html __version_info__ = (1, 4, 0) __version__ = '.'.join(map(str, __version_info__)) import sys import os PY3 = sys.version_info[0] == 3 if PY3: unicode = str if sys.platform.startswith('java'): import platform os_name = platform.java_ver()[3][0] if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc. system = 'win32' elif os_name.startswith('Mac'): # "macOS", etc. system = 'darwin' else: # "Linux", "SunOS", "FreeBSD", etc. # Setting this to "linux2" is not ideal, but only Windows or Mac # are actually checked for and the rest of the module expects # *sys.platform* style strings. system = 'linux2' else: system = sys.platform def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: macOS: ~/Library/Application Support/<AppName> Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName> Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName> Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName> Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName> For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/<AppName>". """ if system == "win32": if appauthor is None: appauthor = appname const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" path = os.path.normpath(_get_win_folder(const)) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == 'darwin': path = os.path.expanduser('~/Library/Application Support/') if appname: path = os.path.join(path, appname) else: path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): """Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical user data directories are: macOS: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == 'darwin': path = os.path.expanduser('/Library/Application Support') if appname: path = os.path.join(path, appname) else: # XDG default for $XDG_DATA_DIRS # only first, if multipath is False path = os.getenv('XDG_DATA_DIRS', os.pathsep.join(['/usr/local/share', '/usr/share'])) pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path if appname and version: path = os.path.join(path, version) return path def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: macOS: same as user_data_dir Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by deafult "~/.config/<AppName>". """ if system in ["win32", "darwin"]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): """Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of config dirs should be returned. By default, the first item from XDG_CONFIG_DIRS is returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set Typical user data directories are: macOS: same as site_data_dir Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in $XDG_CONFIG_DIRS Win *: same as site_data_dir Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system in ["win32", "darwin"]: path = site_data_dir(appname, appauthor) if appname and version: path = os.path.join(path, version) else: # XDG default for $XDG_CONFIG_DIRS # only first, if multipath is False path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Cache" to the base app data dir for Windows. See discussion below. Typical user cache directories are: macOS: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir` above). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. This can be disabled with the `opinion=False` option. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) if opinion: path = os.path.join(path, "Cache") elif system == 'darwin': path = os.path.expanduser('~/Library/Caches') if appname: path = os.path.join(path, appname) else: path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user cache directories are: macOS: ~/Library/Logs/<AppName> Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option. """ if system == "darwin": path = os.path.join( os.path.expanduser('~/Library/Logs'), appname) elif system == "win32": path = user_data_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "Logs") else: path = user_cache_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "log") if appname and version: path = os.path.join(path, version) return path class AppDirs(object): """Convenience wrapper for getting application dirs.""" def __init__(self, appname, appauthor=None, version=None, roaming=False, multipath=False): self.appname = appname self.appauthor = appauthor self.version = version self.roaming = roaming self.multipath = multipath @property def user_data_dir(self): return user_data_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_data_dir(self): return site_data_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_config_dir(self): return user_config_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_config_dir(self): return site_config_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_cache_dir(self): return user_cache_dir(self.appname, self.appauthor, version=self.version) @property def user_log_dir(self): return user_log_dir(self.appname, self.appauthor, version=self.version) #---- internal support stuff def _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) dir, type = _winreg.QueryValueEx(key, shell_folder_name) return dir def _get_win_folder_with_pywin32(csidl_name): from win32com.shell import shellcon, shell dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) # Try to make this a unicode path because SHGetFolderPath does # not return unicode strings when there is unicode data in the # path. try: dir = unicode(dir) # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in dir: if ord(c) > 255: has_high_char = True break if has_high_char: try: import win32api dir = win32api.GetShortPathName(dir) except ImportError: pass except UnicodeError: pass return dir def _get_win_folder_with_ctypes(csidl_name): import ctypes csidl_const = { "CSIDL_APPDATA": 26, "CSIDL_COMMON_APPDATA": 35, "CSIDL_LOCAL_APPDATA": 28, }[csidl_name] buf = ctypes.create_unicode_buffer(1024) ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in buf: if ord(c) > 255: has_high_char = True break if has_high_char: buf2 = ctypes.create_unicode_buffer(1024) if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): buf = buf2 return buf.value def _get_win_folder_with_jna(csidl_name): import array from com.sun import jna from com.sun.jna.platform import win32 buf_size = win32.WinDef.MAX_PATH * 2 buf = array.zeros('c', buf_size) shell = win32.Shell32.INSTANCE shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf) dir = jna.Native.toString(buf.tostring()).rstrip("\0") # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in dir: if ord(c) > 255: has_high_char = True break if has_high_char: buf = array.zeros('c', buf_size) kernel = win32.Kernel32.INSTANCE if kernal.GetShortPathName(dir, buf, buf_size): dir = jna.Native.toString(buf.tostring()).rstrip("\0") return dir if system == "win32": try: import win32com.shell _get_win_folder = _get_win_folder_with_pywin32 except ImportError: try: from ctypes import windll _get_win_folder = _get_win_folder_with_ctypes except ImportError: try: import com.sun.jna _get_win_folder = _get_win_folder_with_jna except ImportError: _get_win_folder = _get_win_folder_from_registry #---- self test code if __name__ == "__main__": appname = "MyApp" appauthor = "MyCompany" props = ("user_data_dir", "site_data_dir", "user_config_dir", "site_config_dir", "user_cache_dir", "user_log_dir") print("-- app dirs (with optional 'version')") dirs = AppDirs(appname, appauthor, version="1.0") for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (without optional 'version')") dirs = AppDirs(appname, appauthor) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (without optional 'appauthor')") dirs = AppDirs(appname) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (with disabled 'appauthor')") dirs = AppDirs(appname, appauthor=False) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop)))
gpl-3.0
jbenden/ansible
test/integration/targets/module_precedence/lib_with_extension/ping.py
102
2144
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, 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/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = ''' --- module: ping version_added: historical short_description: Try to connect to host, verify a usable python and return C(pong) on success. description: - A trivial test module, this module always returns C(pong) on successful contact. It does not make sense in playbooks, but it is useful from C(/usr/bin/ansible) to verify the ability to login and that a usable python is configured. - This is NOT ICMP ping, this is just a trivial test module. options: {} author: - "Ansible Core Team" - "Michael DeHaan" ''' EXAMPLES = ''' # Test we can logon to 'webservers' and execute python with json lib. ansible webservers -m ping ''' from ansible.module_utils.basic import AnsibleModule def main(): module = AnsibleModule( argument_spec=dict( data=dict(required=False, default=None), ), supports_check_mode=True ) result = dict(ping='pong') if module.params['data']: if module.params['data'] == 'crash': raise Exception("boom") result['ping'] = module.params['data'] result['location'] = 'library' module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
krafczyk/spack
var/spack/repos/builtin/packages/kim-api/package.py
2
2073
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of 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 program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class KimApi(CMakePackage): """OpenKIM is an online framework for making molecular simulations reliable, reproducible, and portable. Computer implementations of inter-atomic models are archived in OpenKIM, verified for coding integrity, and tested by computing their predictions for a variety of material properties. Models conforming to the KIM application programming interface (API) work seamlessly with major simulation codes that have adopted the KIM API standard. """ homepage = "https://openkim.org/" git = "https://github.com/openkim/kim-api" version('develop', branch='master') version('2.0rc1', commit="c2ab409ec0154ebd85d20a0a1a0bd2ba6ea95a9c") def cmake_args(self): args = ['-DBUILD_MODULES=OFF'] return args
lgpl-2.1
charany1/googlecl
src/debug_util.py
2
2144
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities that should not be distributed with source.""" __author__ = 'thmiller@google.com (Tom Miller)' import atom import inspect dull_types = [str, unicode, dict, list, type(None)] def walk_attributes(myobject, object_name, tabitem='=', step=True, tablevel=0): """Walk through attributes of an instance. Just flat out prints varying values of dir() for instances and their attributes. Args: myobject: instance to walk through object_name: Name of the instance being walked through tabitem: String to show depth into myobject. Set to '' to disable. step: bool Use raw_input('') after printing each attribute tablevel: Depth into myobject (starts at 0) Returns: NATHING! """ print tabitem*tablevel + 'Object: ' + object_name print tabitem*tablevel + 'Type: ' + str(type(myobject)) attr_list = [attr for attr in dir(myobject) if not attr.startswith('_') and not inspect.ismethod(getattr(myobject, attr))] print tabitem*tablevel + 'Attributes: ' print tabitem*tablevel + str(attr_list) dull_attr = [attr for attr in attr_list if type(getattr(myobject, attr)) in dull_types] if dull_attr: print tabitem*tablevel + '(basic attributes: ' + str(dull_attr) + ')' loopable_attr = [attr for attr in attr_list if not type(getattr(myobject, attr)) in dull_types] for attr_name in loopable_attr: new_object = getattr(myobject, attr_name) if step: raw_input('') walk_attributes(new_object, attr_name, tablevel=tablevel+1)
mit
adit-chandra/tensorflow
tensorflow/python/compiler/tensorrt/test/biasadd_matmul_test.py
7
4543
# 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. # ============================================================================== """Model script to test TF-TensorRT integration.""" 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.ops import array_ops from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.platform import test class BiasaddMatMulTest(trt_test.TfTrtIntegrationTestBase): """Testing conversion of BiasAdd MatMul in TF-TRT conversion.""" def _ConstOp(self, shape): return constant_op.constant(np.random.randn(*shape), dtype=dtypes.float32) def GraphFn(self, x): input_matrix_rows = 4 input_matrix_columns = 144 b = self._ConstOp((input_matrix_columns, 4)) x1 = math_ops.matmul(x, b) b = self._ConstOp((1, 4)) x1 = x1 + b b = self._ConstOp((input_matrix_rows, 144)) x2 = self.trt_incompatible_op(x) x2 = math_ops.matmul(x2, b, transpose_a=True) x2 = gen_array_ops.reshape(x2, [4, -1]) x2 = self.trt_incompatible_op(x2) b = self._ConstOp((4, input_matrix_columns)) x3 = math_ops.matmul(x, b, transpose_b=True) b = self._ConstOp((16, input_matrix_rows)) x4 = self.trt_incompatible_op(x) x4 = math_ops.matmul(x4, b, transpose_b=True, transpose_a=True) x4 = gen_array_ops.reshape(x4, [4, -1]) x4 = self.trt_incompatible_op(x4) # Note that tf.nn.bias_add supports up to 5 dimensions. b = self._ConstOp((input_matrix_columns, 48)) x5 = math_ops.matmul(x, b) b = self._ConstOp((48,)) x5 = nn.bias_add(x5, b) x5 = gen_array_ops.reshape(x5, [4, -1]) x6 = gen_array_ops.reshape(x, [4, 24, 6]) b = self._ConstOp((6,)) x6 = nn.bias_add(x6, b, data_format="NHWC") x6 = gen_array_ops.reshape(x6, [4, -1]) x7 = gen_array_ops.reshape(x, [4, 12, 4, 3]) b = self._ConstOp((3,)) x7 = nn.bias_add(x7, b, data_format="NHWC") x7 = gen_array_ops.reshape(x7, [4, -1]) x8 = gen_array_ops.reshape(x, [4, 4, 3, 2, 6]) b = self._ConstOp((6,)) x8 = nn.bias_add(x8, b, data_format="NHWC") x8 = gen_array_ops.reshape(x8, [4, -1]) x9 = gen_array_ops.reshape(x, [4, 12, 3, 2, 2]) b = self._ConstOp((12,)) x9 = nn.bias_add(x9, b, data_format="NCHW") x9 = gen_array_ops.reshape(x9, [4, -1]) x10 = gen_array_ops.reshape(x, [4, 3, 4, 12]) b = self._ConstOp((3,)) x10 = nn.bias_add(x10, b, data_format="NCHW") x10 = gen_array_ops.reshape(x10, [4, -1]) x11 = gen_array_ops.reshape(x, [4, 6, 24]) b = self._ConstOp((6,)) x11 = nn.bias_add(x11, b, data_format="NCHW") x11 = gen_array_ops.reshape(x11, [4, -1]) out = array_ops.concat([x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11], axis=-1) return array_ops.squeeze(out, name="output_0") def GetParams(self): return self.BuildParams(self.GraphFn, dtypes.float32, [[4, 144]], [[4, 6680]]) def GetConversionParams(self, run_params): """Return a ConversionParams for test.""" conversion_params = super(BiasaddMatMulTest, self).GetConversionParams(run_params) return conversion_params._replace( max_batch_size=4, maximum_cached_engines=1, # Disable layout optimizer, since it will convert BiasAdd with NHWC # format to NCHW format under four dimentional input. rewriter_config_template=trt_test.OptimizerDisabledRewriterConfig()) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return ["TRTEngineOp_0"] if __name__ == "__main__": test.main()
apache-2.0
SummerLW/Perf-Insight-Report
third_party/gsutil/gslib/cat_helper.py
28
3005
# -*- coding: utf-8 -*- # Copyright 2014 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. """Helper for cat and cp streaming download.""" from __future__ import absolute_import import sys from gslib.exception import CommandException from gslib.wildcard_iterator import StorageUrlFromString class CatHelper(object): def __init__(self, command_obj): """Initializes the helper object. Args: command_obj: gsutil command instance of calling command. """ self.command_obj = command_obj def CatUrlStrings(self, url_strings, show_header=False, start_byte=0, end_byte=None): """Prints each of the url strings to stdout. Args: url_strings: String iterable. show_header: If true, print a header per file. start_byte: Starting byte of the file to print, used for constructing range requests. end_byte: Ending byte of the file to print; used for constructing range requests. If this is negative, the start_byte is ignored and and end range is sent over HTTP (such as range: bytes -9) Returns: 0 on success. Raises: CommandException if no URLs can be found. """ printed_one = False # We manipulate the stdout so that all other data other than the Object # contents go to stderr. cat_outfd = sys.stdout sys.stdout = sys.stderr try: for url_str in url_strings: did_some_work = False # TODO: Get only the needed fields here. for blr in self.command_obj.WildcardIterator(url_str).IterObjects(): did_some_work = True if show_header: if printed_one: print print '==> %s <==' % blr printed_one = True cat_object = blr.root_object storage_url = StorageUrlFromString(blr.url_string) if storage_url.IsCloudUrl(): self.command_obj.gsutil_api.GetObjectMedia( cat_object.bucket, cat_object.name, cat_outfd, start_byte=start_byte, end_byte=end_byte, object_size=cat_object.size, generation=storage_url.generation, provider=storage_url.scheme) else: cat_outfd.write(open(storage_url.object_name, 'rb').read()) if not did_some_work: raise CommandException('No URLs matched %s' % url_str) sys.stdout = cat_outfd finally: sys.stdout = cat_outfd return 0
bsd-3-clause
HalcyonChimera/osf.io
osf/management/commands/osf_shell.py
13
8191
"""Enhanced python shell. Includes all features from django-extension's shell_plus command plus OSF-specific niceties. By default, sessions run in a transaction, so changes won't be commited until you execute `commit()`. All models are imported by default, as well as common OSF and Django objects. To add more objects, set the `OSF_SHELL_USER_IMPORTS` Django setting to a dictionary or a callable that returns a dictionary. Example: :: from django.apps import apps def get_user_imports(): User = apps.get_model('osf.OSFUser') Node = apps.get_model('osf.AbstractNode') me = User.objects.get(username='sloria1@gmail.com') node = Node.objects.first() return { 'me': me, 'node': node, } OSF_SHELL_USER_IMPORTS = get_user_imports """ from django.conf import settings from django.db import transaction from django.utils.termcolors import colorize from django.db.models import Model from django_extensions.management.commands import shell_plus from django_extensions.management.utils import signalcommand from elasticsearch_metrics.registry import registry as metrics_registry def header(text): return colorize(text, fg='green', opts=('bold', )) def format_imported_objects(models, metrics, osf, transaction, other, user): def format_dict(d): return ', '.join(sorted(d.keys())) ret = """ {models_header} {models} {metrics_header} {metrics} {osf_header} {osf} {transaction_header} {transaction} {other_header} {other}""".format( models_header=header('Models:'), models=format_dict(models), metrics_header=header('Metrics:'), metrics=format_dict(metrics), osf_header=header('OSF:'), osf=format_dict(osf), transaction_header=header('Transaction:'), transaction=format_dict(transaction), other_header=header('Django:'), other=format_dict(other), ) if user: ret += '\n\n{user_header}\n{user}'.format( user_header=header('User Imports:'), user=format_dict(user) ) return ret # kwargs will be the grouped imports, e.g. {'models': {...}, 'osf': {...}} def make_banner(auto_transact=True, **kwargs): logo = """ .+yhhys/` `smmmmmmmmd: `--.` ommmmmmmmmmm. `.--. `odmmmmmh/ smmmhhyhdmmm- :ymmmmmdo. -dmmmmmmmmmy .hho+++++sdo smmmmmmmmmm: smmmmmmmmmmm: `++++++++: -mmmmmmmmmmmy +mmmmmmmmmmmo: :+++++++.:+mmmmmmmmmmmo +dmmmmmmmds++. .://:-``++odmmmmmmmmo `:osyhys+++/ :+++oyhyso/` `/shddds/``.-::-. `-::-.``/shdddy/` -dmmmmmds++++/. ./++++sdmmmmmd: hmmmmmmo+++++++. .++++++++dmmmmmd` hmmmmmmo+++++++. .++++++++dmmmmmd` -dmmmmmds++++/. ./++++sdmmmmmd: `/shddhs/``.-::-. `-::-.``/shdddy/` `:osyhys+++/ :+++oyhyso/` +dmmmmmmmds++. .://:- `++odmmmmmmmmo +mmmmmmmmmmmo: /++++++/`:+mmmmmmmmmmmo smmmmmmmmmmm: `++++++++. -mmmmmmmmmmmy -dmmmmmmmmmy `s++++++y/ smmmmmmmmmm: `odmmmmmh/ hmmhyyhdmm/ :ymmmmmds. `--.` `mmmmmmmmmmo `.--. /mmmmmmmmh` `+shhyo: """ greeting = 'Welcome to the OSF Shell. Happy hacking!' imported_objects = format_imported_objects(**kwargs) transaction_warning = """ *** TRANSACTION AUTOMATICALLY STARTED *** To persist changes, run 'commit()'. Keep in mind that changing documents will lock them. This feature can be disabled with the '--no-transaction' flag.""" no_transaction_warning = """ *** AUTO-TRANSACTION DISABLED *** All changes will persist. Transactions must be handled manually.""" template = """{logo} {greeting} {imported_objects} {warning} """ if auto_transact: warning = colorize(transaction_warning, fg='yellow') else: warning = colorize(no_transaction_warning, fg='red') return template.format( logo=colorize(logo, fg='cyan'), greeting=colorize(greeting, opts=('bold', )), imported_objects=imported_objects, warning=warning, ) class Command(shell_plus.Command): def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--no-transaction', action='store_false', dest='transaction', help="Don't run session in transaction. Transactions must be " 'started manually with start_transaction()' ) def get_osf_imports(self): """Return a dictionary of common OSF objects and utilities.""" from osf.management.utils import print_sql from website import settings as website_settings from framework.auth import Auth, get_user ret = { 'print_sql': print_sql, 'Auth': Auth, 'get_user': get_user, 'website_settings': website_settings, } try: # faker isn't a prod requirement from faker import Factory except ImportError: pass else: fake = Factory.create() ret['fake'] = fake return ret def get_metrics(self): return { each.__name__: each for each in metrics_registry.get_metrics() } def get_grouped_imports(self, options): """Return a dictionary of grouped import of the form: { 'osf': { 'Auth': <framework.auth.Auth>, .... } 'models': {...} 'transaction': {...} 'other': {...} } """ auto_transact = options.get('transaction', True) def start_transaction(): self.atomic.__enter__() print('New transaction opened.') def commit(): self.atomic.__exit__(None, None, None) print('Transaction committed.') if auto_transact: start_transaction() def rollback(): exc_type = RuntimeError exc_value = exc_type('Transaction rollback') self.atomic.__exit__(exc_type, exc_value, None) print('Transaction rolled back.') if auto_transact: start_transaction() groups = { 'models': {}, 'metrics': self.get_metrics(), 'other': {}, 'osf': self.get_osf_imports(), 'transaction': { 'start_transaction': start_transaction, 'commit': commit, 'rollback': rollback, }, 'user': self.get_user_imports(), } # Import models and common django imports shell_plus_imports = shell_plus.Command.get_imported_objects(self, options) for name, object in shell_plus_imports.items(): if isinstance(object, type) and issubclass(object, Model): groups['models'][name] = object else: groups['other'][name] = object return groups def get_user_imports(self): imports = getattr(settings, 'OSF_SHELL_USER_IMPORTS', None) if imports: if callable(imports): imports = imports() return imports else: return {} # Override shell_plus.Command def get_imported_objects(self, options): # Merge all the values of grouped_imports imported_objects = {} for imports in self.grouped_imports.values(): imported_objects.update(imports) return imported_objects # Override shell_plus.Command @signalcommand def handle(self, *args, **options): self.atomic = transaction.atomic() auto_transact = options.get('transaction', True) options['quiet_load'] = True # Don't show default shell_plus banner self.grouped_imports = self.get_grouped_imports(options) banner = make_banner(auto_transact=auto_transact, **self.grouped_imports) print(banner) if auto_transact: self.atomic.__enter__() super(Command, self).handle(*args, **options)
apache-2.0
timmie/cartopy
lib/cartopy/mpl/ticker.py
3
10493
# (C) British Crown Copyright 2014 - 2016, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # cartopy 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 cartopy. If not, see <https://www.gnu.org/licenses/>. """This module contains tools for handling tick marks in cartopy.""" from __future__ import (absolute_import, division, print_function) from matplotlib.ticker import Formatter import cartopy.crs as ccrs from cartopy.mpl.geoaxes import GeoAxes class _PlateCarreeFormatter(Formatter): """ Base class for formatting ticks on geographical axes using a rectangular projection (e.g. Plate Carree, Mercator). """ _target_projection = ccrs.PlateCarree() def __init__(self, degree_symbol=u'\u00B0', number_format='g', transform_precision=1e-8): """ Base class for simpler implementation of specialised formatters for latitude and longitude axes. """ self._degree_symbol = degree_symbol self._number_format = number_format self._transform_precision = transform_precision def __call__(self, value, pos=None): if not isinstance(self.axis.axes, GeoAxes): raise TypeError("This formatter can only be " "used with cartopy axes.") # We want to produce labels for values in the familiar Plate Carree # projection, so convert the tick values from their own projection # before formatting them. source = self.axis.axes.projection if not isinstance(source, (ccrs._RectangularProjection, ccrs.Mercator)): raise TypeError("This formatter cannot be used with " "non-rectangular projections.") projected_value = self._apply_transform(value, self._target_projection, source) # Round the transformed value using a given precision for display # purposes. Transforms can introduce minor rounding errors that make # the tick values look bad, these need to be accounted for. f = 1. / self._transform_precision projected_value = round(f * projected_value) / f # Return the formatted values, the formatter has both the re-projected # tick value and the original axis value available to it. return self._format_value(projected_value, value) def _format_value(self, value, original_value): hemisphere = self._hemisphere(value, original_value) fmt_string = u'{value:{number_format}}{degree}{hemisphere}' return fmt_string.format(value=abs(value), number_format=self._number_format, degree=self._degree_symbol, hemisphere=hemisphere) def _apply_transform(self, value, target_proj, source_crs): """ Given a single value, a target projection and a source CRS, transforms the value from the source CRS to the target projection, returning a single value. """ raise NotImplementedError("A subclass must implement this method.") def _hemisphere(self, value, value_source_crs): """ Given both a tick value in the Plate Carree projection and the same value in the source CRS returns a string indicating the hemisphere that the value is in. Must be over-ridden by the derived class. """ raise NotImplementedError("A subclass must implement this method.") class LatitudeFormatter(_PlateCarreeFormatter): """Tick formatter for latitude axes.""" def __init__(self, degree_symbol=u'\u00B0', number_format='g', transform_precision=1e-8): """ Tick formatter for a latitude axis. The axis must be part of an axes defined on a rectangular projection (e.g. Plate Carree, Mercator). .. note:: A formatter can only be used for one axis. A new formatter must be created for every axis that needs formatted labels. Kwargs: * degree_symbol (string): The character(s) used to represent the degree symbol in the tick labels. Defaults to u'\u00B0' which is the unicode degree symbol. Can be an empty string if no degree symbol is desired. * number_format (string): Format string to represent the tick values. Defaults to 'g'. * transform_precision (float): Sets the precision (in degrees) to which transformed tick values are rounded. The default is 1e-7, and should be suitable for most use cases. To control the appearance of tick labels use the *number_format* keyword. Examples: Label latitudes from -90 to 90 on a Plate Carree projection:: ax = plt.axes(projection=PlateCarree()) ax.set_global() ax.set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree()) lat_formatter = LatitudeFormatter() ax.yaxis.set_major_formatter(lat_formatter) Label latitudes from -80 to 80 on a Mercator projection, this time omitting the degree symbol:: ax = plt.axes(projection=Mercator()) ax.set_global() ax.set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree()) lat_formatter = LatitudeFormatter(degree_symbol='') ax.yaxis.set_major_formatter(lat_formatter) """ super(LatitudeFormatter, self).__init__( degree_symbol=degree_symbol, number_format=number_format, transform_precision=transform_precision) def _apply_transform(self, value, target_proj, source_crs): return target_proj.transform_point(0, value, source_crs)[1] def _hemisphere(self, value, value_source_crs): if value > 0: hemisphere = 'N' elif value < 0: hemisphere = 'S' else: hemisphere = '' return hemisphere class LongitudeFormatter(_PlateCarreeFormatter): """Tick formatter for a longitude axis.""" def __init__(self, zero_direction_label=False, dateline_direction_label=False, degree_symbol=u'\u00B0', number_format='g', transform_precision=1e-8): """ Create a formatter for longitude values. The axis must be part of an axes defined on a rectangular projection (e.g. Plate Carree, Mercator). .. note:: A formatter can only be used for one axis. A new formatter must be created for every axis that needs formatted labels. Kwargs: * zero_direction_label (False | True): If *True* a direction label (E or W) will be drawn next to longitude labels with the value 0. If *False* then these labels will not be drawn. Defaults to *False* (no direction labels). * dateline_direction_label (False | True): If *True* a direction label (E or W) will be drawn next to longitude labels with the value 180. If *False* then these labels will not be drawn. Defaults to *False* (no direction labels). * degree_symbol (string): The symbol used to represent degrees. Defaults to u'\u00B0' which is the unicode degree symbol. * number_format (string): Format string to represent the longitude values. Defaults to 'g'. * transform_precision (float): Sets the precision (in degrees) to which transformed tick values are rounded. The default is 1e-7, and should be suitable for most use cases. To control the appearance of tick labels use the *number_format* keyword. Examples: Label longitudes from -180 to 180 on a Plate Carree projection with a central longitude of 0:: ax = plt.axes(projection=PlateCarree()) ax.set_global() ax.set_xticks([-180, -120, -60, 0, 60, 120, 180], crs=ccrs.PlateCarree()) lon_formatter = LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) Label longitudes from 0 to 360 on a Plate Carree projection with a central longitude of 180:: ax = plt.axes(projection=PlateCarree(central_longitude=180)) ax.set_global() ax.set_xticks([0, 60, 120, 180, 240, 300, 360], crs=ccrs.PlateCarree()) ont_formatter = LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) """ super(LongitudeFormatter, self).__init__( degree_symbol=degree_symbol, number_format=number_format, transform_precision=transform_precision) self._zero_direction_labels = zero_direction_label self._dateline_direction_labels = dateline_direction_label def _apply_transform(self, value, target_proj, source_crs): return target_proj.transform_point(value, 0, source_crs)[0] def _hemisphere(self, value, value_source_crs): # Perform basic hemisphere detection. if value < 0: hemisphere = 'W' elif value > 0: hemisphere = 'E' else: hemisphere = '' # Correct for user preferences: if value == 0 and self._zero_direction_labels: # Use the original tick value to determine the hemisphere. if value_source_crs < 0: hemisphere = 'E' else: hemisphere = 'W' if value in (-180, 180) and not self._dateline_direction_labels: hemisphere = '' return hemisphere
gpl-3.0
mheap/ansible
lib/ansible/utils/helpers.py
109
1614
# (c) 2016, Ansible by Red Hat <info@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 from ansible.module_utils.six import string_types def pct_to_int(value, num_items, min_value=1): ''' Converts a given value to a percentage if specified as "x%", otherwise converts the given value to an integer. ''' if isinstance(value, string_types) and value.endswith('%'): value_pct = int(value.replace("%", "")) return int((value_pct / 100.0) * num_items) or min_value else: return int(value) def object_to_dict(obj, exclude=None): """ Converts an object into a dict making the properties into keys, allows excluding certain keys """ if exclude is None or not isinstance(exclude, list): exclude = [] return dict((key, getattr(obj, key)) for key in dir(obj) if not (key.startswith('_') or key in exclude))
gpl-3.0
jose36/plugin.video.ProyectoLuzDigital
servers/zippyshare.py
34
2012
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para zippyshare # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core import scrapertools from core import logger from core import config def test_video_exists( page_url ): return True,"" def get_video_url( page_url , premium = False , user="" , password="", video_password="" ): logger.info("[zippyshare.py] get_video_url(page_url='%s')" % page_url) video_urls = [] headers=[] headers.append(["User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:19.0) Gecko/20100101 Firefox/19.0"]) data = scrapertools.cache_page(page_url,headers=headers) location = scrapertools.get_match(data,"var submitCaptcha.*?document.location \= '([^']+)'") mediaurl = urlparse.urljoin(page_url,location)+"|"+urllib.urlencode({'Referer' : page_url}) extension = scrapertools.get_filename_from_url(mediaurl)[-4:] video_urls.append( [ extension + " [zippyshare]",mediaurl ] ) return video_urls # Encuentra vídeos del servidor en el texto pasado def find_videos(data): encontrados = set() devuelve = [] #http://www5.zippyshare.com/v/11178679/file.html patronvideos = '([a-z0-9]+\.zippyshare.com/v/\d+/file.html)' logger.info("[zippyshare.py] find_videos #"+patronvideos+"#") matches = re.compile(patronvideos,re.DOTALL).findall(data) for match in matches: titulo = "[zippyshare]" url = "http://"+match if url not in encontrados: logger.info(" url="+url) devuelve.append( [ titulo , url , 'zippyshare' ] ) encontrados.add(url) else: logger.info(" url duplicada="+url) return devuelve def test(): video_urls = get_video_url("http://www5.zippyshare.com/v/11178679/file.html") return len(video_urls)>0
apache-2.0
15Dkatz/pants
src/python/pants/util/desktop.py
4
1516
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.util.osutil import get_os_name from pants.util.process_handler import subprocess class OpenError(Exception): """Indicates an error opening a file in a desktop application.""" def _mac_open(files): subprocess.call(['open'] + list(files)) def _linux_open(files): cmd = "xdg-open" if not _cmd_exists(cmd): raise OpenError("The program '{}' isn't in your PATH. Please install and re-run this " "goal.".format(cmd)) for f in list(files): subprocess.call([cmd, f]) # From: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python def _cmd_exists(cmd): return subprocess.call(["/usr/bin/which", cmd], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0 _OPENER_BY_OS = { 'darwin': _mac_open, 'linux': _linux_open } def ui_open(*files): """Attempts to open the given files using the preferred desktop viewer or editor. :raises :class:`OpenError`: if there is a problem opening any of the files. """ if files: osname = get_os_name() opener = _OPENER_BY_OS.get(osname) if opener: opener(files) else: raise OpenError('Open currently not supported for ' + osname)
apache-2.0
samthor/intellij-community
plugins/hg4idea/testData/bin/hgext/convert/gnuarch.py
94
12716
# gnuarch.py - GNU Arch support for the convert extension # # Copyright 2008, 2009 Aleix Conchillo Flaque <aleix@member.fsf.org> # and others # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from common import NoRepo, commandline, commit, converter_source from mercurial.i18n import _ from mercurial import encoding, util import os, shutil, tempfile, stat from email.Parser import Parser class gnuarch_source(converter_source, commandline): class gnuarch_rev(object): def __init__(self, rev): self.rev = rev self.summary = '' self.date = None self.author = '' self.continuationof = None self.add_files = [] self.mod_files = [] self.del_files = [] self.ren_files = {} self.ren_dirs = {} def __init__(self, ui, path, rev=None): super(gnuarch_source, self).__init__(ui, path, rev=rev) if not os.path.exists(os.path.join(path, '{arch}')): raise NoRepo(_("%s does not look like a GNU Arch repository") % path) # Could use checktool, but we want to check for baz or tla. self.execmd = None if util.findexe('baz'): self.execmd = 'baz' else: if util.findexe('tla'): self.execmd = 'tla' else: raise util.Abort(_('cannot find a GNU Arch tool')) commandline.__init__(self, ui, self.execmd) self.path = os.path.realpath(path) self.tmppath = None self.treeversion = None self.lastrev = None self.changes = {} self.parents = {} self.tags = {} self.catlogparser = Parser() self.encoding = encoding.encoding self.archives = [] def before(self): # Get registered archives self.archives = [i.rstrip('\n') for i in self.runlines0('archives', '-n')] if self.execmd == 'tla': output = self.run0('tree-version', self.path) else: output = self.run0('tree-version', '-d', self.path) self.treeversion = output.strip() # Get name of temporary directory version = self.treeversion.split('/') self.tmppath = os.path.join(tempfile.gettempdir(), 'hg-%s' % version[1]) # Generate parents dictionary self.parents[None] = [] treeversion = self.treeversion child = None while treeversion: self.ui.status(_('analyzing tree version %s...\n') % treeversion) archive = treeversion.split('/')[0] if archive not in self.archives: self.ui.status(_('tree analysis stopped because it points to ' 'an unregistered archive %s...\n') % archive) break # Get the complete list of revisions for that tree version output, status = self.runlines('revisions', '-r', '-f', treeversion) self.checkexit(status, 'failed retrieving revisions for %s' % treeversion) # No new iteration unless a revision has a continuation-of header treeversion = None for l in output: rev = l.strip() self.changes[rev] = self.gnuarch_rev(rev) self.parents[rev] = [] # Read author, date and summary catlog, status = self.run('cat-log', '-d', self.path, rev) if status: catlog = self.run0('cat-archive-log', rev) self._parsecatlog(catlog, rev) # Populate the parents map self.parents[child].append(rev) # Keep track of the current revision as the child of the next # revision scanned child = rev # Check if we have to follow the usual incremental history # or if we have to 'jump' to a different treeversion given # by the continuation-of header. if self.changes[rev].continuationof: treeversion = '--'.join( self.changes[rev].continuationof.split('--')[:-1]) break # If we reached a base-0 revision w/o any continuation-of # header, it means the tree history ends here. if rev[-6:] == 'base-0': break def after(self): self.ui.debug('cleaning up %s\n' % self.tmppath) shutil.rmtree(self.tmppath, ignore_errors=True) def getheads(self): return self.parents[None] def getfile(self, name, rev): if rev != self.lastrev: raise util.Abort(_('internal calling inconsistency')) # Raise IOError if necessary (i.e. deleted files). if not os.path.lexists(os.path.join(self.tmppath, name)): raise IOError return self._getfile(name, rev) def getchanges(self, rev): self._update(rev) changes = [] copies = {} for f in self.changes[rev].add_files: changes.append((f, rev)) for f in self.changes[rev].mod_files: changes.append((f, rev)) for f in self.changes[rev].del_files: changes.append((f, rev)) for src in self.changes[rev].ren_files: to = self.changes[rev].ren_files[src] changes.append((src, rev)) changes.append((to, rev)) copies[to] = src for src in self.changes[rev].ren_dirs: to = self.changes[rev].ren_dirs[src] chgs, cps = self._rendirchanges(src, to) changes += [(f, rev) for f in chgs] copies.update(cps) self.lastrev = rev return sorted(set(changes)), copies def getcommit(self, rev): changes = self.changes[rev] return commit(author=changes.author, date=changes.date, desc=changes.summary, parents=self.parents[rev], rev=rev) def gettags(self): return self.tags def _execute(self, cmd, *args, **kwargs): cmdline = [self.execmd, cmd] cmdline += args cmdline = [util.shellquote(arg) for arg in cmdline] cmdline += ['>', os.devnull, '2>', os.devnull] cmdline = util.quotecommand(' '.join(cmdline)) self.ui.debug(cmdline, '\n') return os.system(cmdline) def _update(self, rev): self.ui.debug('applying revision %s...\n' % rev) changeset, status = self.runlines('replay', '-d', self.tmppath, rev) if status: # Something went wrong while merging (baz or tla # issue?), get latest revision and try from there shutil.rmtree(self.tmppath, ignore_errors=True) self._obtainrevision(rev) else: old_rev = self.parents[rev][0] self.ui.debug('computing changeset between %s and %s...\n' % (old_rev, rev)) self._parsechangeset(changeset, rev) def _getfile(self, name, rev): mode = os.lstat(os.path.join(self.tmppath, name)).st_mode if stat.S_ISLNK(mode): data = os.readlink(os.path.join(self.tmppath, name)) mode = mode and 'l' or '' else: data = open(os.path.join(self.tmppath, name), 'rb').read() mode = (mode & 0111) and 'x' or '' return data, mode def _exclude(self, name): exclude = ['{arch}', '.arch-ids', '.arch-inventory'] for exc in exclude: if name.find(exc) != -1: return True return False def _readcontents(self, path): files = [] contents = os.listdir(path) while len(contents) > 0: c = contents.pop() p = os.path.join(path, c) # os.walk could be used, but here we avoid internal GNU # Arch files and directories, thus saving a lot time. if not self._exclude(p): if os.path.isdir(p): contents += [os.path.join(c, f) for f in os.listdir(p)] else: files.append(c) return files def _rendirchanges(self, src, dest): changes = [] copies = {} files = self._readcontents(os.path.join(self.tmppath, dest)) for f in files: s = os.path.join(src, f) d = os.path.join(dest, f) changes.append(s) changes.append(d) copies[d] = s return changes, copies def _obtainrevision(self, rev): self.ui.debug('obtaining revision %s...\n' % rev) output = self._execute('get', rev, self.tmppath) self.checkexit(output) self.ui.debug('analyzing revision %s...\n' % rev) files = self._readcontents(self.tmppath) self.changes[rev].add_files += files def _stripbasepath(self, path): if path.startswith('./'): return path[2:] return path def _parsecatlog(self, data, rev): try: catlog = self.catlogparser.parsestr(data) # Commit date self.changes[rev].date = util.datestr( util.strdate(catlog['Standard-date'], '%Y-%m-%d %H:%M:%S')) # Commit author self.changes[rev].author = self.recode(catlog['Creator']) # Commit description self.changes[rev].summary = '\n\n'.join((catlog['Summary'], catlog.get_payload())) self.changes[rev].summary = self.recode(self.changes[rev].summary) # Commit revision origin when dealing with a branch or tag if 'Continuation-of' in catlog: self.changes[rev].continuationof = self.recode( catlog['Continuation-of']) except Exception: raise util.Abort(_('could not parse cat-log of %s') % rev) def _parsechangeset(self, data, rev): for l in data: l = l.strip() # Added file (ignore added directory) if l.startswith('A') and not l.startswith('A/'): file = self._stripbasepath(l[1:].strip()) if not self._exclude(file): self.changes[rev].add_files.append(file) # Deleted file (ignore deleted directory) elif l.startswith('D') and not l.startswith('D/'): file = self._stripbasepath(l[1:].strip()) if not self._exclude(file): self.changes[rev].del_files.append(file) # Modified binary file elif l.startswith('Mb'): file = self._stripbasepath(l[2:].strip()) if not self._exclude(file): self.changes[rev].mod_files.append(file) # Modified link elif l.startswith('M->'): file = self._stripbasepath(l[3:].strip()) if not self._exclude(file): self.changes[rev].mod_files.append(file) # Modified file elif l.startswith('M'): file = self._stripbasepath(l[1:].strip()) if not self._exclude(file): self.changes[rev].mod_files.append(file) # Renamed file (or link) elif l.startswith('=>'): files = l[2:].strip().split(' ') if len(files) == 1: files = l[2:].strip().split('\t') src = self._stripbasepath(files[0]) dst = self._stripbasepath(files[1]) if not self._exclude(src) and not self._exclude(dst): self.changes[rev].ren_files[src] = dst # Conversion from file to link or from link to file (modified) elif l.startswith('ch'): file = self._stripbasepath(l[2:].strip()) if not self._exclude(file): self.changes[rev].mod_files.append(file) # Renamed directory elif l.startswith('/>'): dirs = l[2:].strip().split(' ') if len(dirs) == 1: dirs = l[2:].strip().split('\t') src = self._stripbasepath(dirs[0]) dst = self._stripbasepath(dirs[1]) if not self._exclude(src) and not self._exclude(dst): self.changes[rev].ren_dirs[src] = dst
apache-2.0
exelearning/iteexe
exe/webui/imagewithtextblock.py
15
5926
# =========================================================================== # eXe # Copyright 2004-2006, University of Auckland # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # =========================================================================== """ ImageWithTextBlock can render and process ImageWithTextIdevices as XHTML """ import logging from exe.webui.block import Block from exe.webui.element import TextAreaElement, ImageElement from exe.webui import common log = logging.getLogger(__name__) # =========================================================================== class ImageWithTextBlock(Block): """ ImageWithTextBlock can render and process ImageWithTextIdevices as XHTML """ name = 'imageWithText' def __init__(self, parent, idevice): """ Initialize """ Block.__init__(self, parent, idevice) self.imageElement = ImageElement(idevice.image) # to compensate for the strange unpickling timing when objects are # loaded from an elp, ensure that proper idevices are set: # (only applies to the image-embeddable ones, not FlashMovieElement) if idevice.text.idevice is None: idevice.text.idevice = idevice self.textElement = TextAreaElement(idevice.text) def process(self, request): """ Process the request arguments from the web server to see if any apply to this block """ log.debug("process " + repr(request.args)) Block.process(self, request) if (u"action" not in request.args or request.args[u"action"][0] != u"delete"): self.imageElement.process(request) self.textElement.process(request) if "float"+self.id in request.args: self.idevice.float = request.args["float"+self.id][0] if "caption"+self.id in request.args: self.idevice.caption = request.args["caption"+self.id][0] def renderEdit(self, style): """ Returns an XHTML string with the form elements for editing this block """ log.debug("renderEdit") html = u"<div class=\"iDevice\">\n" html += self.imageElement.renderEdit() floatArr = [[_(u'Left'), 'left'], [_(u'Right'), 'right'], [_(u'None'), 'none']] this_package = None if self.idevice is not None and self.idevice.parentNode is not None: this_package = self.idevice.parentNode.package html += common.formField('select', this_package, _("Align:"), "float" + self.id, '', '', floatArr, self.idevice.float) html += u'<div class="block"><b>%s</b></div>' % _(u"Caption:") html += common.textInput("caption" + self.id, self.idevice.caption) html += common.elementInstruc(self.idevice.captionInstruc) html += "<br/>" + self.textElement.renderEdit() html += self.renderEditButtons() html += u"</div>\n" return html def renderPreview(self, style): """ Returns an XHTML string for previewing this block """ log.debug("renderPreview") html = u"\n<!-- image with text iDevice -->\n" html += u"<div class=\"iDevice " html += u"emphasis"+unicode(self.idevice.emphasis)+"\" " html += "ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n" html += u"<div class=\"image_text\" style=\"" html += u"width:" + str(self.idevice.image.width) + "px; " html += u"float:%s;\">\n" % self.idevice.float html += u"<div class=\"image\">\n" html += self.imageElement.renderPreview() html += u"" + self.idevice.caption + "</div>" html += u"</div>\n" html += self.textElement.renderPreview() html += u"<br/>\n" html += u"<div style=\"clear:both;\">" html += u"</div>\n" html += self.renderViewButtons() html += u"</div>\n" return html def renderView(self, style): """ Returns an XHTML string for viewing this block """ log.debug("renderView") html = u"\n<!-- image with text iDevice -->\n" html += u"<div class=\"iDevice " html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n" html += u"<div class=\"image_text\" style=\"" html += u"width:" + str(self.idevice.image.width) + "px; " html += u"float:%s;\">\n" % self.idevice.float html += u"<div class=\"image\">\n" html += self.imageElement.renderView() html += u"<br/>" + self.idevice.caption + "</div>" html += u"</div>\n" html += self.textElement.renderView() html += u"<div style=\"clear:both;\">" html += u"</div>\n" html += u"</div>\n" return html from exe.engine.imagewithtextidevice import ImageWithTextIdevice from exe.webui.blockfactory import g_blockFactory g_blockFactory.registerBlockType(ImageWithTextBlock, ImageWithTextIdevice) # ===========================================================================
gpl-2.0
zouzhberk/ambaridemo
demo-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/TEZ/package/scripts/tez_client.py
4
1154
""" 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. Ambari Agent """ import sys from resource_management import * from tez import tez class TezClient(Script): def install(self, env): self.install_packages(env) self.configure(env) def configure(self, env): import params env.set_params(params) tez() def status(self, env): raise ClientComponentHasNoStatus() if __name__ == "__main__": TezClient().execute()
apache-2.0
GitHublong/hue
desktop/core/ext-py/Django-1.6.10/django/utils/unittest/main.py
219
9392
"""Unittest main program""" import sys import os import types from django.utils.unittest import loader, runner try: from django.utils.unittest.signals import installHandler except ImportError: installHandler = None __unittest = True FAILFAST = " -f, --failfast Stop on first failure\n" CATCHBREAK = " -c, --catch Catch control-C and display results\n" BUFFEROUTPUT = " -b, --buffer Buffer stdout and stderr during test runs\n" USAGE_AS_MAIN = """\ Usage: %(progName)s [options] [tests] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: %(progName)s test_module - run tests from test_module %(progName)s test_module.TestClass - run tests from test_module.TestClass %(progName)s test_module.TestClass.test_method - run specified test method [tests] can be a list of any number of test modules, classes and test methods. Alternative Usage: %(progName)s discover [options] Options: -v, --verbose Verbose output %(failfast)s%(catchbreak)s%(buffer)s -s directory Directory to start discovery ('.' default) -p pattern Pattern to match test files ('test*.py' default) -t directory Top level directory of project (default to start directory) For test discovery all test modules must be importable from the top level directory of the project. """ USAGE_FROM_MODULE = """\ Usage: %(progName)s [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: %(progName)s - run default set of tests %(progName)s MyTestSuite - run suite 'MyTestSuite' %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething %(progName)s MyTestCase - run all 'test*' test methods in MyTestCase """ class TestProgram(object): """A command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. """ USAGE = USAGE_FROM_MODULE # defaults for testing failfast = catchbreak = buffer = progName = None def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None): if isinstance(module, basestring): self.module = __import__(module) for part in module.split('.')[1:]: self.module = getattr(self.module, part) else: self.module = module if argv is None: argv = sys.argv self.exit = exit self.verbosity = verbosity self.failfast = failfast self.catchbreak = catchbreak self.buffer = buffer self.defaultTest = defaultTest self.testRunner = testRunner self.testLoader = testLoader self.progName = os.path.basename(argv[0]) self.parseArgs(argv) self.runTests() def usageExit(self, msg=None): if msg: print(msg) usage = {'progName': self.progName, 'catchbreak': '', 'failfast': '', 'buffer': ''} if self.failfast != False: usage['failfast'] = FAILFAST if self.catchbreak != False and installHandler is not None: usage['catchbreak'] = CATCHBREAK if self.buffer != False: usage['buffer'] = BUFFEROUTPUT print(self.USAGE % usage) sys.exit(2) def parseArgs(self, argv): if len(argv) > 1 and argv[1].lower() == 'discover': self._do_discovery(argv[2:]) return import getopt long_opts = ['help', 'verbose', 'quiet', 'failfast', 'catch', 'buffer'] try: options, args = getopt.getopt(argv[1:], 'hHvqfcb', long_opts) for opt, value in options: if opt in ('-h','-H','--help'): self.usageExit() if opt in ('-q','--quiet'): self.verbosity = 0 if opt in ('-v','--verbose'): self.verbosity = 2 if opt in ('-f','--failfast'): if self.failfast is None: self.failfast = True # Should this raise an exception if -f is not valid? if opt in ('-c','--catch'): if self.catchbreak is None and installHandler is not None: self.catchbreak = True # Should this raise an exception if -c is not valid? if opt in ('-b','--buffer'): if self.buffer is None: self.buffer = True # Should this raise an exception if -b is not valid? if len(args) == 0 and self.defaultTest is None: # createTests will load tests from self.module self.testNames = None elif len(args) > 0: self.testNames = args if __name__ == '__main__': # to support python -m unittest ... self.module = None else: self.testNames = (self.defaultTest,) self.createTests() except getopt.error as msg: self.usageExit(msg) def createTests(self): if self.testNames is None: self.test = self.testLoader.loadTestsFromModule(self.module) else: self.test = self.testLoader.loadTestsFromNames(self.testNames, self.module) def _do_discovery(self, argv, Loader=loader.TestLoader): # handle command line args for test discovery self.progName = '%s discover' % self.progName import optparse parser = optparse.OptionParser() parser.prog = self.progName parser.add_option('-v', '--verbose', dest='verbose', default=False, help='Verbose output', action='store_true') if self.failfast != False: parser.add_option('-f', '--failfast', dest='failfast', default=False, help='Stop on first fail or error', action='store_true') if self.catchbreak != False and installHandler is not None: parser.add_option('-c', '--catch', dest='catchbreak', default=False, help='Catch ctrl-C and display results so far', action='store_true') if self.buffer != False: parser.add_option('-b', '--buffer', dest='buffer', default=False, help='Buffer stdout and stderr during tests', action='store_true') parser.add_option('-s', '--start-directory', dest='start', default='.', help="Directory to start discovery ('.' default)") parser.add_option('-p', '--pattern', dest='pattern', default='test*.py', help="Pattern to match tests ('test*.py' default)") parser.add_option('-t', '--top-level-directory', dest='top', default=None, help='Top level directory of project (defaults to start directory)') options, args = parser.parse_args(argv) if len(args) > 3: self.usageExit() for name, value in zip(('start', 'pattern', 'top'), args): setattr(options, name, value) # only set options from the parsing here # if they weren't set explicitly in the constructor if self.failfast is None: self.failfast = options.failfast if self.catchbreak is None and installHandler is not None: self.catchbreak = options.catchbreak if self.buffer is None: self.buffer = options.buffer if options.verbose: self.verbosity = 2 start_dir = options.start pattern = options.pattern top_level_dir = options.top loader = Loader() self.test = loader.discover(start_dir, pattern, top_level_dir) def runTests(self): if self.catchbreak: installHandler() if self.testRunner is None: self.testRunner = runner.TextTestRunner if isinstance(self.testRunner, (type, types.ClassType)): try: testRunner = self.testRunner(verbosity=self.verbosity, failfast=self.failfast, buffer=self.buffer) except TypeError: # didn't accept the verbosity, buffer or failfast arguments testRunner = self.testRunner() else: # it is assumed to be a TestRunner instance testRunner = self.testRunner self.result = testRunner.run(self.test) if self.exit: sys.exit(not self.result.wasSuccessful()) main = TestProgram def main_(): TestProgram.USAGE = USAGE_AS_MAIN main(module=None)
apache-2.0
FreeFighter77/venom-xbmc-addons-beta
plugin.video.vstream/resources/hosters/trash/filebase.py
4
2905
from resources.lib.jsunpacker import cJsUnpacker from resources.lib.parser import cParser from resources.lib.handler.requestHandler import cRequestHandler from resources.lib.util import cUtil from resources.hosters.hoster import iHoster class cHoster(iHoster): def __init__(self): self.__sDisplayName = 'FileBase.to' self.__sFileName = self.__sDisplayName def getDisplayName(self): return self.__sDisplayName def setDisplayName(self, sDisplayName): self.__sDisplayName = sDisplayName def setFileName(self, sFileName): self.__sFileName = sFileName def getFileName(self): return self.__sFileName def getPluginIdentifier(self): return 'filebase' def isDownloadable(self): return True def isJDownloaderable(self): return True def getPattern(self): return "" def setUrl(self, sUrl): self.__sUrl = sUrl def checkUrl(self, sUrl): return True def getUrl(self): return self.__sUrl def getMediaLink(self): return self.__getMediaLinkForGuest() def getMediaLink(self): return self.__getMediaLinkForGuest() def __getMediaLinkForGuest(self): oRequest = cRequestHandler(self.__sUrl) sHtmlContent = oRequest.request() sPattern = '<form action="#" method="post">.*?id="uid" value="([^"]+)" />' oParser = cParser() aResult = oParser.parse(sHtmlContent, sPattern) if (aResult[0] == True): sUid = aResult[1][0] oRequest = cRequestHandler(self.__sUrl) oRequest.setRequestType(cRequestHandler.REQUEST_TYPE_POST) oRequest.addParameters('dl_free12','DivX Stream') oRequest.addParameters('uid', sUid) sHtmlContent = oRequest.request() sPattern = '<input type="hidden" id="uid" name="uid" value="([^"]+)" />' oParser = cParser() aResult = oParser.parse(sHtmlContent, sPattern) if (aResult[0] == True): sUid = aResult[1][0] oRequest = cRequestHandler(self.__sUrl) oRequest.setRequestType(cRequestHandler.REQUEST_TYPE_POST) oRequest.addParameters('captcha','ok') oRequest.addParameters('filetype','divx') oRequest.addParameters('submit','Download') oRequest.addParameters('uid', sUid) sHtmlContent = oRequest.request() sPattern = '<param value="([^"]+)" name="src" />' oParser = cParser() aResult = oParser.parse(sHtmlContent, sPattern) if (aResult[0] == True): sMediaFile = aResult[1][0] return True, sMediaFile return False, aResult
gpl-2.0
haoxli/crosswalk-test-suite
webapi/tct-csp-w3c-tests/csp-py/csp_frame-src_cross-origin_multi_allowed_two-manual.py
30
2515
def main(request, response): import simplejson as json f = file('config.json') source = f.read() s = json.JSONDecoder().decode(source) url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1]) url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0]) _CSP = "frame-src " + url2 + " " + url1 response.headers.set("Content-Security-Policy", _CSP) response.headers.set("X-Content-Security-Policy", _CSP) response.headers.set("X-WebKit-CSP", _CSP) return """<!DOCTYPE html> <!-- Copyright (c) 2013 Intel Corporation. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Authors: Hao, Yunfei <yunfeix.hao@intel.com> --> <html> <head> <title>CSP Test: csp_frame-src_cross-origin_allowed_two</title> <link rel="author" title="Intel" href="http://www.intel.com/"/> <link rel="help" href="http://www.w3.org/TR/2012/CR-CSP-20121115/#frame-src"/> <meta name="flags" content=""/> <meta charset="utf-8"/> </head> <body> <p>Test passes if there is a filled green square.</p> <iframe frameborder="no" border="0" src='""" + url1 + """/tests/csp/support/green-100x100.png'/> </body> </html> """
bsd-3-clause
SUSE/azure-sdk-for-python
azure-mgmt-datalake-analytics/azure/mgmt/datalake/analytics/catalog/models/usql_package.py
4
1951
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .catalog_item import CatalogItem class USqlPackage(CatalogItem): """A Data Lake Analytics catalog U-SQL package item. :param compute_account_name: the name of the Data Lake Analytics account. :type compute_account_name: str :param version: the version of the catalog item. :type version: str :param database_name: the name of the database containing the package. :type database_name: str :param schema_name: the name of the schema associated with this package and database. :type schema_name: str :param name: the name of the package. :type name: str :param definition: the definition of the package. :type definition: str """ _attribute_map = { 'compute_account_name': {'key': 'computeAccountName', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'}, 'database_name': {'key': 'databaseName', 'type': 'str'}, 'schema_name': {'key': 'schemaName', 'type': 'str'}, 'name': {'key': 'packageName', 'type': 'str'}, 'definition': {'key': 'definition', 'type': 'str'}, } def __init__(self, compute_account_name=None, version=None, database_name=None, schema_name=None, name=None, definition=None): super(USqlPackage, self).__init__(compute_account_name=compute_account_name, version=version) self.database_name = database_name self.schema_name = schema_name self.name = name self.definition = definition
mit
maxamillion/ansible
lib/ansible/plugins/test/files.py
170
1518
# (c) 2015, Ansible, Inc # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from os.path import isdir, isfile, isabs, exists, lexists, islink, samefile, ismount from ansible import errors class TestModule(object): ''' Ansible file jinja2 tests ''' def tests(self): return { # file testing 'is_dir': isdir, 'directory': isdir, 'is_file': isfile, 'file': isfile, 'is_link': islink, 'link': islink, 'exists': exists, 'link_exists': lexists, # path testing 'is_abs': isabs, 'abs': isabs, 'is_same_file': samefile, 'same_file': samefile, 'is_mount': ismount, 'mount': ismount, }
gpl-3.0
sarthfrey/Texty
lib/requests/packages/urllib3/util/ssl_.py
196
11401
from __future__ import absolute_import import errno import warnings import hmac from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning SSLContext = None HAS_SNI = False create_default_context = None # Maps the length of a digest to a possible hash function producing this digest HASHFUNC_MAP = { 32: md5, 40: sha1, 64: sha256, } def _const_compare_digest_backport(a, b): """ Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise. """ result = abs(len(a) - len(b)) for l, r in zip(bytearray(a), bytearray(b)): result |= l ^ r return result == 0 _const_compare_digest = getattr(hmac, 'compare_digest', _const_compare_digest_backport) try: # Test for SSL features import ssl from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23 from ssl import HAS_SNI # Has SNI? except ImportError: pass try: from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION except ImportError: OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000 OP_NO_COMPRESSION = 0x20000 # A secure default. # Sources for more information on TLS ciphers: # # - https://wiki.mozilla.org/Security/Server_Side_TLS # - https://www.ssllabs.com/projects/best-practices/index.html # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/ # # The general intent is: # - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE), # - prefer ECDHE over DHE for better performance, # - prefer any AES-GCM over any AES-CBC for better performance and security, # - use 3DES as fallback which is secure but slow, # - disable NULL authentication, MD5 MACs and DSS for security reasons. DEFAULT_CIPHERS = ( 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:' '!eNULL:!MD5' ) try: from ssl import SSLContext # Modern SSL? except ImportError: import sys class SSLContext(object): # Platform-specific: Python 2 & 3.1 supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or (3, 2) <= sys.version_info) def __init__(self, protocol_version): self.protocol = protocol_version # Use default values from a real SSLContext self.check_hostname = False self.verify_mode = ssl.CERT_NONE self.ca_certs = None self.options = 0 self.certfile = None self.keyfile = None self.ciphers = None def load_cert_chain(self, certfile, keyfile): self.certfile = certfile self.keyfile = keyfile def load_verify_locations(self, cafile=None, capath=None): self.ca_certs = cafile if capath is not None: raise SSLError("CA directories not supported in older Pythons") def set_ciphers(self, cipher_suite): if not self.supports_set_ciphers: raise TypeError( 'Your version of Python does not support setting ' 'a custom cipher suite. Please upgrade to Python ' '2.7, 3.2, or later if you need this functionality.' ) self.ciphers = cipher_suite def wrap_socket(self, socket, server_hostname=None): warnings.warn( 'A true SSLContext object is not available. This prevents ' 'urllib3 from configuring SSL appropriately and may cause ' 'certain SSL connections to fail. For more information, see ' 'https://urllib3.readthedocs.org/en/latest/security.html' '#insecureplatformwarning.', InsecurePlatformWarning ) kwargs = { 'keyfile': self.keyfile, 'certfile': self.certfile, 'ca_certs': self.ca_certs, 'cert_reqs': self.verify_mode, 'ssl_version': self.protocol, } if self.supports_set_ciphers: # Platform-specific: Python 2.7+ return wrap_socket(socket, ciphers=self.ciphers, **kwargs) else: # Platform-specific: Python 2.6 return wrap_socket(socket, **kwargs) def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ fingerprint = fingerprint.replace(':', '').lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if not hashfunc: raise SSLError( 'Fingerprint of invalid length: {0}'.format(fingerprint)) # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if not _const_compare_digest(cert_digest, fingerprint_bytes): raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' .format(fingerprint, hexlify(cert_digest))) def resolve_cert_reqs(candidate): """ Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_NONE`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbrevation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket. """ if candidate is None: return CERT_NONE if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'CERT_' + candidate) return res return candidate def resolve_ssl_version(candidate): """ like resolve_cert_reqs """ if candidate is None: return PROTOCOL_SSLv23 if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'PROTOCOL_' + candidate) return res return candidate def create_urllib3_context(ssl_version=None, cert_reqs=None, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION context.options |= options if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6 context.set_ciphers(ciphers or DEFAULT_CIPHERS) context.verify_mode = cert_reqs if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False return context def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. This is not supported on Python 2.6 as the ssl module does not support it. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). """ context = ssl_context if context is None: context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir: try: context.load_verify_locations(ca_certs, ca_cert_dir) except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise if certfile: context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) warnings.warn( 'An HTTPS request has been made, but the SNI (Subject Name ' 'Indication) extension to TLS is not available on this platform. ' 'This may cause the server to present an incorrect TLS ' 'certificate, which can cause validation failures. For more ' 'information, see ' 'https://urllib3.readthedocs.org/en/latest/security.html' '#snimissingwarning.', SNIMissingWarning ) return context.wrap_socket(sock)
apache-2.0
sridevikoushik31/openstack
nova/api/openstack/compute/contrib/consoles.py
2
3828
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova import exception from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'consoles') class ConsolesController(wsgi.Controller): def __init__(self, *args, **kwargs): self.compute_api = compute.API() super(ConsolesController, self).__init__(*args, **kwargs) @wsgi.action('os-getVNCConsole') def get_vnc_console(self, req, id, body): """Get text console output.""" context = req.environ['nova.context'] authorize(context) # If type is not supplied or unknown, get_vnc_console below will cope console_type = body['os-getVNCConsole'].get('type') try: instance = self.compute_api.get(context, id) output = self.compute_api.get_vnc_console(context, instance, console_type) except exception.InstanceNotFound as e: raise webob.exc.HTTPNotFound(explanation=unicode(e)) except exception.InstanceNotReady as e: raise webob.exc.HTTPConflict(explanation=unicode(e)) return {'console': {'type': console_type, 'url': output['url']}} @wsgi.action('os-getSPICEConsole') def get_spice_console(self, req, id, body): """Get text console output.""" context = req.environ['nova.context'] authorize(context) # If type is not supplied or unknown, get_spice_console below will cope console_type = body['os-getSPICEConsole'].get('type') try: instance = self.compute_api.get(context, id) output = self.compute_api.get_spice_console(context, instance, console_type) except exception.InstanceNotFound as e: raise webob.exc.HTTPNotFound(explanation=unicode(e)) except exception.InstanceNotReady as e: raise webob.exc.HTTPConflict(explanation=unicode(e)) return {'console': {'type': console_type, 'url': output['url']}} def get_actions(self): """Return the actions the extension adds, as required by contract.""" actions = [extensions.ActionExtension("servers", "os-getVNCConsole", self.get_vnc_console), extensions.ActionExtension("servers", "os-getSPICEConsole", self.get_spice_console)] return actions class Consoles(extensions.ExtensionDescriptor): """Interactive Console support.""" name = "Consoles" alias = "os-consoles" namespace = "http://docs.openstack.org/compute/ext/os-consoles/api/v2" updated = "2011-12-23T00:00:00+00:00" def get_controller_extensions(self): controller = ConsolesController() extension = extensions.ControllerExtension(self, 'servers', controller) return [extension]
apache-2.0
heromod/migrid
mig/edpickle.py
1
2501
#!/usr/bin/python # -*- coding: utf-8 -*- # # edpickle - a simple pickled object editor. # Copyright (C) 2009 Jonas Bardino # # This file is part of MiG. # # MiG 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. # # MiG 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. """Edit pickled objects on disk""" import os import sys from shared.serial import pickle if len(sys.argv) < 2: print 'Usage: %s PATH' % sys.argv[0] print 'Edit pickled object in file PATH' sys.exit(1) dirty = False path = sys.argv[1] print "opening pickle in %s" % path pickle_fd = open(path, 'rb+') obj = pickle.load(pickle_fd) print "pickled object loaded as 'obj'" while True: command = raw_input("Enter command: ") command = command.lower().strip() if command in ['o', 'open']: path = raw_input("Path to open: ") pickle_fd = open(path, 'rb+') obj = pickle.load(pickle_fd) elif command in ['h', 'help']: print "Valid commands include:" print "(d)isplay to display the opened pickled object" print "(e)dit to edit the opened pickled object" print "(o)pen to open a new pickle file" print "(c)lose to close the opened pickled object" print "(q)uit to quit pickle editor" elif command in ['d', 'display']: print obj elif command in ['e', 'edit']: edit = raw_input("Edit command: ") #eval(edit) eval(compile(edit, 'command-line', 'single')) dirty = True elif command in ['c', 'close', 'q', 'quit']: if dirty: flush = raw_input("Modified object not saved - save now?: ") if flush.lower() in ('y', 'yes'): pickle_fd.seek(0) pickle.dump(obj, pickle_fd) pickle_fd.close() obj = None if command in ('q', 'quit'): print "Closing" break else: print "unknown command '%s'" % command
gpl-2.0
albertomurillo/ansible
lib/ansible/modules/network/fortios/fortios_router_multicast_flow.py
21
8926
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, 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 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 <https://www.gnu.org/licenses/>. # # the lib use python logging can get it if the following is set in your # Ansible config. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_router_multicast_flow short_description: Configure multicast-flow in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS by allowing the user to set and modify router feature and multicast_flow category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.2 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate ip address. required: true username: description: - FortiOS or FortiGate username. required: true password: description: - FortiOS or FortiGate password. default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol type: bool default: true router_multicast_flow: description: - Configure multicast-flow. default: null suboptions: state: description: - Indicates whether to create or remove the object choices: - present - absent comments: description: - Comment. flows: description: - Multicast-flow entries. suboptions: group-addr: description: - Multicast group IP address. id: description: - Flow ID. required: true source-addr: description: - Multicast source IP address. name: description: - Name. required: true ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" tasks: - name: Configure multicast-flow. fortios_router_multicast_flow: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" router_multicast_flow: state: "present" comments: "<your_own_value>" flows: - group-addr: "<your_own_value>" id: "6" source-addr: "<your_own_value>" name: "default_name_8" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule fos = None def login(data): host = data['host'] username = data['username'] password = data['password'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password) def filter_router_multicast_flow_data(json): option_list = ['comments', 'flows', 'name'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def flatten_multilists_attributes(data): multilist_attrs = [] for attr in multilist_attrs: try: path = "data['" + "']['".join(elem for elem in attr) + "']" current_val = eval(path) flattened_val = ' '.join(elem for elem in current_val) exec(path + '= flattened_val') except BaseException: pass return data def router_multicast_flow(data, fos): vdom = data['vdom'] router_multicast_flow_data = data['router_multicast_flow'] flattened_data = flatten_multilists_attributes(router_multicast_flow_data) filtered_data = filter_router_multicast_flow_data(flattened_data) if router_multicast_flow_data['state'] == "present": return fos.set('router', 'multicast-flow', data=filtered_data, vdom=vdom) elif router_multicast_flow_data['state'] == "absent": return fos.delete('router', 'multicast-flow', mkey=filtered_data['name'], vdom=vdom) def fortios_router(data, fos): login(data) if data['router_multicast_flow']: resp = router_multicast_flow(data, fos) fos.logout() return not resp['status'] == "success", resp['status'] == "success", resp def main(): fields = { "host": {"required": True, "type": "str"}, "username": {"required": True, "type": "str"}, "password": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "router_multicast_flow": { "required": False, "type": "dict", "options": { "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "comments": {"required": False, "type": "str"}, "flows": {"required": False, "type": "list", "options": { "group-addr": {"required": False, "type": "str"}, "id": {"required": True, "type": "int"}, "source-addr": {"required": False, "type": "str"} }}, "name": {"required": True, "type": "str"} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") global fos fos = FortiOSAPI() is_error, has_changed, result = fortios_router(module.params, fos) if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
gpl-3.0
menardorama/ReadyNAS-Add-ons
headphones-1.0.0/files/etc/apps/headphones/lib/unidecode/x09c.py
253
4659
data = ( 'Huan ', # 0x00 'Quan ', # 0x01 'Ze ', # 0x02 'Wei ', # 0x03 'Wei ', # 0x04 'Yu ', # 0x05 'Qun ', # 0x06 'Rou ', # 0x07 'Die ', # 0x08 'Huang ', # 0x09 'Lian ', # 0x0a 'Yan ', # 0x0b 'Qiu ', # 0x0c 'Qiu ', # 0x0d 'Jian ', # 0x0e 'Bi ', # 0x0f 'E ', # 0x10 'Yang ', # 0x11 'Fu ', # 0x12 'Sai ', # 0x13 'Jian ', # 0x14 'Xia ', # 0x15 'Tuo ', # 0x16 'Hu ', # 0x17 'Muroaji ', # 0x18 'Ruo ', # 0x19 'Haraka ', # 0x1a 'Wen ', # 0x1b 'Jian ', # 0x1c 'Hao ', # 0x1d 'Wu ', # 0x1e 'Fang ', # 0x1f 'Sao ', # 0x20 'Liu ', # 0x21 'Ma ', # 0x22 'Shi ', # 0x23 'Shi ', # 0x24 'Yin ', # 0x25 'Z ', # 0x26 'Teng ', # 0x27 'Ta ', # 0x28 'Yao ', # 0x29 'Ge ', # 0x2a 'Rong ', # 0x2b 'Qian ', # 0x2c 'Qi ', # 0x2d 'Wen ', # 0x2e 'Ruo ', # 0x2f 'Hatahata ', # 0x30 'Lian ', # 0x31 'Ao ', # 0x32 'Le ', # 0x33 'Hui ', # 0x34 'Min ', # 0x35 'Ji ', # 0x36 'Tiao ', # 0x37 'Qu ', # 0x38 'Jian ', # 0x39 'Sao ', # 0x3a 'Man ', # 0x3b 'Xi ', # 0x3c 'Qiu ', # 0x3d 'Biao ', # 0x3e 'Ji ', # 0x3f 'Ji ', # 0x40 'Zhu ', # 0x41 'Jiang ', # 0x42 'Qiu ', # 0x43 'Zhuan ', # 0x44 'Yong ', # 0x45 'Zhang ', # 0x46 'Kang ', # 0x47 'Xue ', # 0x48 'Bie ', # 0x49 'Jue ', # 0x4a 'Qu ', # 0x4b 'Xiang ', # 0x4c 'Bo ', # 0x4d 'Jiao ', # 0x4e 'Xun ', # 0x4f 'Su ', # 0x50 'Huang ', # 0x51 'Zun ', # 0x52 'Shan ', # 0x53 'Shan ', # 0x54 'Fan ', # 0x55 'Jue ', # 0x56 'Lin ', # 0x57 'Xun ', # 0x58 'Miao ', # 0x59 'Xi ', # 0x5a 'Eso ', # 0x5b 'Kyou ', # 0x5c 'Fen ', # 0x5d 'Guan ', # 0x5e 'Hou ', # 0x5f 'Kuai ', # 0x60 'Zei ', # 0x61 'Sao ', # 0x62 'Zhan ', # 0x63 'Gan ', # 0x64 'Gui ', # 0x65 'Sheng ', # 0x66 'Li ', # 0x67 'Chang ', # 0x68 'Hatahata ', # 0x69 'Shiira ', # 0x6a 'Mutsu ', # 0x6b 'Ru ', # 0x6c 'Ji ', # 0x6d 'Xu ', # 0x6e 'Huo ', # 0x6f 'Shiira ', # 0x70 'Li ', # 0x71 'Lie ', # 0x72 'Li ', # 0x73 'Mie ', # 0x74 'Zhen ', # 0x75 'Xiang ', # 0x76 'E ', # 0x77 'Lu ', # 0x78 'Guan ', # 0x79 'Li ', # 0x7a 'Xian ', # 0x7b 'Yu ', # 0x7c 'Dao ', # 0x7d 'Ji ', # 0x7e 'You ', # 0x7f 'Tun ', # 0x80 'Lu ', # 0x81 'Fang ', # 0x82 'Ba ', # 0x83 'He ', # 0x84 'Bo ', # 0x85 'Ping ', # 0x86 'Nian ', # 0x87 'Lu ', # 0x88 'You ', # 0x89 'Zha ', # 0x8a 'Fu ', # 0x8b 'Bo ', # 0x8c 'Bao ', # 0x8d 'Hou ', # 0x8e 'Pi ', # 0x8f 'Tai ', # 0x90 'Gui ', # 0x91 'Jie ', # 0x92 'Kao ', # 0x93 'Wei ', # 0x94 'Er ', # 0x95 'Tong ', # 0x96 'Ze ', # 0x97 'Hou ', # 0x98 'Kuai ', # 0x99 'Ji ', # 0x9a 'Jiao ', # 0x9b 'Xian ', # 0x9c 'Za ', # 0x9d 'Xiang ', # 0x9e 'Xun ', # 0x9f 'Geng ', # 0xa0 'Li ', # 0xa1 'Lian ', # 0xa2 'Jian ', # 0xa3 'Li ', # 0xa4 'Shi ', # 0xa5 'Tiao ', # 0xa6 'Gun ', # 0xa7 'Sha ', # 0xa8 'Wan ', # 0xa9 'Jun ', # 0xaa 'Ji ', # 0xab 'Yong ', # 0xac 'Qing ', # 0xad 'Ling ', # 0xae 'Qi ', # 0xaf 'Zou ', # 0xb0 'Fei ', # 0xb1 'Kun ', # 0xb2 'Chang ', # 0xb3 'Gu ', # 0xb4 'Ni ', # 0xb5 'Nian ', # 0xb6 'Diao ', # 0xb7 'Jing ', # 0xb8 'Shen ', # 0xb9 'Shi ', # 0xba 'Zi ', # 0xbb 'Fen ', # 0xbc 'Die ', # 0xbd 'Bi ', # 0xbe 'Chang ', # 0xbf 'Shi ', # 0xc0 'Wen ', # 0xc1 'Wei ', # 0xc2 'Sai ', # 0xc3 'E ', # 0xc4 'Qiu ', # 0xc5 'Fu ', # 0xc6 'Huang ', # 0xc7 'Quan ', # 0xc8 'Jiang ', # 0xc9 'Bian ', # 0xca 'Sao ', # 0xcb 'Ao ', # 0xcc 'Qi ', # 0xcd 'Ta ', # 0xce 'Yin ', # 0xcf 'Yao ', # 0xd0 'Fang ', # 0xd1 'Jian ', # 0xd2 'Le ', # 0xd3 'Biao ', # 0xd4 'Xue ', # 0xd5 'Bie ', # 0xd6 'Man ', # 0xd7 'Min ', # 0xd8 'Yong ', # 0xd9 'Wei ', # 0xda 'Xi ', # 0xdb 'Jue ', # 0xdc 'Shan ', # 0xdd 'Lin ', # 0xde 'Zun ', # 0xdf 'Huo ', # 0xe0 'Gan ', # 0xe1 'Li ', # 0xe2 'Zhan ', # 0xe3 'Guan ', # 0xe4 'Niao ', # 0xe5 'Yi ', # 0xe6 'Fu ', # 0xe7 'Li ', # 0xe8 'Jiu ', # 0xe9 'Bu ', # 0xea 'Yan ', # 0xeb 'Fu ', # 0xec 'Diao ', # 0xed 'Ji ', # 0xee 'Feng ', # 0xef 'Nio ', # 0xf0 'Gan ', # 0xf1 'Shi ', # 0xf2 'Feng ', # 0xf3 'Ming ', # 0xf4 'Bao ', # 0xf5 'Yuan ', # 0xf6 'Zhi ', # 0xf7 'Hu ', # 0xf8 'Qin ', # 0xf9 'Fu ', # 0xfa 'Fen ', # 0xfb 'Wen ', # 0xfc 'Jian ', # 0xfd 'Shi ', # 0xfe 'Yu ', # 0xff )
gpl-2.0
NewAcropolis/api
app/routes/venues/rest.py
1
3126
import os from flask import ( Blueprint, current_app, jsonify, request ) from flask_jwt_extended import jwt_required from app.dao.venues_dao import ( dao_create_venue, dao_get_venues, dao_update_venue, dao_get_venue_by_id ) from app.errors import register_errors from app.routes.venues.schemas import ( post_create_venue_schema, post_create_venues_schema, post_import_venues_schema, post_update_venue_schema ) from app.models import Venue from app.schema_validation import validate venues_blueprint = Blueprint('venues', __name__) venue_blueprint = Blueprint('venue', __name__) register_errors(venues_blueprint) register_errors(venue_blueprint) @venues_blueprint.route('/venues') @jwt_required def get_venues(): venues = [e.serialize() if e else None for e in dao_get_venues()] return jsonify(venues) @venue_blueprint.route('/venue/<uuid:venue_id>', methods=['GET']) def get_venue_by_id(venue_id): current_app.logger.info('get_venue: {}'.format(venue_id)) venue = dao_get_venue_by_id(venue_id) return jsonify(venue.serialize()) @venue_blueprint.route('/venue', methods=['POST']) def create_venue(): data = request.get_json(force=True) validate(data, post_create_venue_schema) venue = Venue(**data) dao_create_venue(venue) return jsonify(venue.serialize()), 201 @venues_blueprint.route('/venues', methods=['POST']) @jwt_required def create_venues(): data = request.get_json(force=True) validate(data, post_create_venues_schema) venues = [] for item in data: venue = Venue.query.filter(Venue.name == item['name']).first() if not venue: venue = Venue(**item) venues.append(venue) dao_create_venue(venue) else: current_app.logger.info('venue already exists: {}'.format(venue.name)) return jsonify([v.serialize() for v in venues]), 201 @venues_blueprint.route('/venues/import', methods=['POST']) @jwt_required def import_venues(): data = request.get_json(force=True) validate(data, post_import_venues_schema) venues = [] for item in data: if not item["name"]: item["name"] = "Head branch" venue = Venue.query.filter(Venue.old_id == item['id']).first() if not venue: venue = Venue( old_id=item['id'], name=item['name'], address=item['address'], directions="<div>Bus: {bus}</div><div>Train: {train}</div>".format(bus=item['bus'], train=item['tube']) ) venues.append(venue) dao_create_venue(venue) else: current_app.logger.info('venue already exists: {}'.format(venue.name)) return jsonify([v.serialize() for v in venues]), 201 @venue_blueprint.route('/venue/<uuid:venue_id>', methods=['POST']) def update_venue(venue_id): data = request.get_json() validate(data, post_update_venue_schema) fetched_venue = dao_get_venue_by_id(venue_id) dao_update_venue(venue_id, **data) return jsonify(fetched_venue.serialize()), 200
mit
bestrauc/seqan
util/py_lib/clang/cindex.py
36
57281
#===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===------------------------------------------------------------------------===# r""" Clang Indexing Library Bindings =============================== This module provides an interface to the Clang indexing library. It is a low-level interface to the indexing library which attempts to match the Clang API directly while also being "pythonic". Notable differences from the C API are: * string results are returned as Python strings, not CXString objects. * null cursors are translated to None. * access to child cursors is done via iteration, not visitation. The major indexing objects are: Index The top-level object which manages some global library state. TranslationUnit High-level object encapsulating the AST for a single translation unit. These can be loaded from .ast files or parsed on the fly. Cursor Generic object for representing a node in the AST. SourceRange, SourceLocation, and File Objects representing information about the input source. Most object information is exposed using properties, when the underlying API call is efficient. """ # TODO # ==== # # o API support for invalid translation units. Currently we can't even get the # diagnostics on failure because they refer to locations in an object that # will have been invalidated. # # o fix memory management issues (currently client must hold on to index and # translation unit, or risk crashes). # # o expose code completion APIs. # # o cleanup ctypes wrapping, would be nice to separate the ctypes details more # clearly, and hide from the external interface (i.e., help(cindex)). # # o implement additional SourceLocation, SourceRange, and File methods. from ctypes import * def get_cindex_library(): # FIXME: It's probably not the case that the library is actually found in # this location. We need a better system of identifying and loading the # CIndex library. It could be on path or elsewhere, or versioned, etc. import platform name = platform.system() if name == 'Darwin': return cdll.LoadLibrary('libclang.dylib') elif name == 'Windows': return cdll.LoadLibrary('libclang.dll') else: return cdll.LoadLibrary('libclang.so') # ctypes doesn't implicitly convert c_void_p to the appropriate wrapper # object. This is a problem, because it means that from_parameter will see an # integer and pass the wrong value on platforms where int != void*. Work around # this by marshalling object arguments as void**. c_object_p = POINTER(c_void_p) lib = get_cindex_library() ### Structures and Utility Classes ### class _CXString(Structure): """Helper for transforming CXString results.""" _fields_ = [("spelling", c_char_p), ("free", c_int)] def __del__(self): _CXString_dispose(self) @staticmethod def from_result(res, fn, args): assert isinstance(res, _CXString) return _CXString_getCString(res) class SourceLocation(Structure): """ A SourceLocation represents a particular location within a source file. """ _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)] _data = None def _get_instantiation(self): if self._data is None: f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() SourceLocation_loc(self, byref(f), byref(l), byref(c), byref(o)) f = File(f) if f else None self._data = (f, int(l.value), int(c.value), int(o.value)) return self._data @property def file(self): """Get the file represented by this source location.""" return self._get_instantiation()[0] @property def line(self): """Get the line represented by this source location.""" return self._get_instantiation()[1] @property def column(self): """Get the column represented by this source location.""" return self._get_instantiation()[2] @property def offset(self): """Get the file offset represented by this source location.""" return self._get_instantiation()[3] def __repr__(self): return "<SourceLocation file %r, line %r, column %r>" % ( self.file.name if self.file else None, self.line, self.column) class SourceRange(Structure): """ A SourceRange describes a range of source locations within the source code. """ _fields_ = [ ("ptr_data", c_void_p * 2), ("begin_int_data", c_uint), ("end_int_data", c_uint)] # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes # object. @staticmethod def from_locations(start, end): return SourceRange_getRange(start, end) @property def start(self): """ Return a SourceLocation representing the first character within a source range. """ return SourceRange_start(self) @property def end(self): """ Return a SourceLocation representing the last character within a source range. """ return SourceRange_end(self) def __repr__(self): return "<SourceRange start %r, end %r>" % (self.start, self.end) class Diagnostic(object): """ A Diagnostic is a single instance of a Clang diagnostic. It includes the diagnostic severity, the message, the location the diagnostic occurred, as well as additional source ranges and associated fix-it hints. """ Ignored = 0 Note = 1 Warning = 2 Error = 3 Fatal = 4 def __init__(self, ptr): self.ptr = ptr def __del__(self): _clang_disposeDiagnostic(self) @property def severity(self): return _clang_getDiagnosticSeverity(self) @property def location(self): return _clang_getDiagnosticLocation(self) @property def spelling(self): return _clang_getDiagnosticSpelling(self) @property def ranges(self): class RangeIterator: def __init__(self, diag): self.diag = diag def __len__(self): return int(_clang_getDiagnosticNumRanges(self.diag)) def __getitem__(self, key): if (key >= len(self)): raise IndexError return _clang_getDiagnosticRange(self.diag, key) return RangeIterator(self) @property def fixits(self): class FixItIterator: def __init__(self, diag): self.diag = diag def __len__(self): return int(_clang_getDiagnosticNumFixIts(self.diag)) def __getitem__(self, key): range = SourceRange() value = _clang_getDiagnosticFixIt(self.diag, key, byref(range)) if len(value) == 0: raise IndexError return FixIt(range, value) return FixItIterator(self) def __repr__(self): return "<Diagnostic severity %r, location %r, spelling %r>" % ( self.severity, self.location, self.spelling) def from_param(self): return self.ptr class FixIt(object): """ A FixIt represents a transformation to be applied to the source to "fix-it". The fix-it shouldbe applied by replacing the given source range with the given value. """ def __init__(self, range, value): self.range = range self.value = value def __repr__(self): return "<FixIt range %r, value %r>" % (self.range, self.value) ### Cursor Kinds ### class CursorKind(object): """ A CursorKind describes the kind of entity that a cursor points to. """ # The unique kind objects, indexed by id. _kinds = [] _name_map = None def __init__(self, value): if value >= len(CursorKind._kinds): CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1) if CursorKind._kinds[value] is not None: raise ValueError,'CursorKind already loaded' self.value = value CursorKind._kinds[value] = self CursorKind._name_map = None def from_param(self): return self.value @property def name(self): """Get the enumeration name of this cursor kind.""" if self._name_map is None: self._name_map = {} for key,value in CursorKind.__dict__.items(): if isinstance(value,CursorKind): self._name_map[value] = key return self._name_map[self] @staticmethod def from_id(id): if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None: raise ValueError,'Unknown cursor kind' return CursorKind._kinds[id] @staticmethod def get_all_kinds(): """Return all CursorKind enumeration instances.""" return filter(None, CursorKind._kinds) def is_declaration(self): """Test if this is a declaration kind.""" return CursorKind_is_decl(self) def is_reference(self): """Test if this is a reference kind.""" return CursorKind_is_ref(self) def is_expression(self): """Test if this is an expression kind.""" return CursorKind_is_expr(self) def is_statement(self): """Test if this is a statement kind.""" return CursorKind_is_stmt(self) def is_attribute(self): """Test if this is an attribute kind.""" return CursorKind_is_attribute(self) def is_invalid(self): """Test if this is an invalid kind.""" return CursorKind_is_inv(self) def __repr__(self): return 'CursorKind.%s' % (self.name,) # FIXME: Is there a nicer way to expose this enumeration? We could potentially # represent the nested structure, or even build a class hierarchy. The main # things we want for sure are (a) simple external access to kinds, (b) a place # to hang a description and name, (c) easy to keep in sync with Index.h. ### # Declaration Kinds # A declaration whose specific kind is not exposed via this interface. # # Unexposed declarations have the same operations as any other kind of # declaration; one can extract their location information, spelling, find their # definitions, etc. However, the specific kind of the declaration is not # reported. CursorKind.UNEXPOSED_DECL = CursorKind(1) # A C or C++ struct. CursorKind.STRUCT_DECL = CursorKind(2) # A C or C++ union. CursorKind.UNION_DECL = CursorKind(3) # A C++ class. CursorKind.CLASS_DECL = CursorKind(4) # An enumeration. CursorKind.ENUM_DECL = CursorKind(5) # A field (in C) or non-static data member (in C++) in a struct, union, or C++ # class. CursorKind.FIELD_DECL = CursorKind(6) # An enumerator constant. CursorKind.ENUM_CONSTANT_DECL = CursorKind(7) # A function. CursorKind.FUNCTION_DECL = CursorKind(8) # A variable. CursorKind.VAR_DECL = CursorKind(9) # A function or method parameter. CursorKind.PARM_DECL = CursorKind(10) # An Objective-C @interface. CursorKind.OBJC_INTERFACE_DECL = CursorKind(11) # An Objective-C @interface for a category. CursorKind.OBJC_CATEGORY_DECL = CursorKind(12) # An Objective-C @protocol declaration. CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13) # An Objective-C @property declaration. CursorKind.OBJC_PROPERTY_DECL = CursorKind(14) # An Objective-C instance variable. CursorKind.OBJC_IVAR_DECL = CursorKind(15) # An Objective-C instance method. CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16) # An Objective-C class method. CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17) # An Objective-C @implementation. CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18) # An Objective-C @implementation for a category. CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19) # A typedef. CursorKind.TYPEDEF_DECL = CursorKind(20) # A C++ class method. CursorKind.CXX_METHOD = CursorKind(21) # A C++ namespace. CursorKind.NAMESPACE = CursorKind(22) # A linkage specification, e.g. 'extern "C"'. CursorKind.LINKAGE_SPEC = CursorKind(23) # A C++ constructor. CursorKind.CONSTRUCTOR = CursorKind(24) # A C++ destructor. CursorKind.DESTRUCTOR = CursorKind(25) # A C++ conversion function. CursorKind.CONVERSION_FUNCTION = CursorKind(26) # A C++ template type parameter CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27) # A C++ non-type template paramater. CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28) # A C++ template template parameter. CursorKind.TEMPLATE_TEMPLATE_PARAMTER = CursorKind(29) # A C++ function template. CursorKind.FUNCTION_TEMPLATE = CursorKind(30) # A C++ class template. CursorKind.CLASS_TEMPLATE = CursorKind(31) # A C++ class template partial specialization. CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32) # A C++ namespace alias declaration. CursorKind.NAMESPACE_ALIAS = CursorKind(33) # A C++ using directive CursorKind.USING_DIRECTIVE = CursorKind(34) # A C++ using declaration CursorKind.USING_DECLARATION = CursorKind(35) # A Type alias decl. CursorKind.TYPE_ALIAS_DECL = CursorKind(36) # A Objective-C synthesize decl CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37) # A Objective-C dynamic decl CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38) # A C++ access specifier decl. CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39) ### # Reference Kinds CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40) CursorKind.OBJC_PROTOCOL_REF = CursorKind(41) CursorKind.OBJC_CLASS_REF = CursorKind(42) # A reference to a type declaration. # # A type reference occurs anywhere where a type is named but not # declared. For example, given: # typedef unsigned size_type; # size_type size; # # The typedef is a declaration of size_type (CXCursor_TypedefDecl), # while the type of the variable "size" is referenced. The cursor # referenced by the type of size is the typedef for size_type. CursorKind.TYPE_REF = CursorKind(43) CursorKind.CXX_BASE_SPECIFIER = CursorKind(44) # A reference to a class template, function template, template # template parameter, or class template partial specialization. CursorKind.TEMPLATE_REF = CursorKind(45) # A reference to a namespace or namepsace alias. CursorKind.NAMESPACE_REF = CursorKind(46) # A reference to a member of a struct, union, or class that occurs in # some non-expression context, e.g., a designated initializer. CursorKind.MEMBER_REF = CursorKind(47) # A reference to a labeled statement. CursorKind.LABEL_REF = CursorKind(48) # A reference toa a set of overloaded functions or function templates # that has not yet been resolved to a specific function or function template. CursorKind.OVERLOADED_DECL_REF = CursorKind(49) ### # Invalid/Error Kinds CursorKind.INVALID_FILE = CursorKind(70) CursorKind.NO_DECL_FOUND = CursorKind(71) CursorKind.NOT_IMPLEMENTED = CursorKind(72) CursorKind.INVALID_CODE = CursorKind(73) ### # Expression Kinds # An expression whose specific kind is not exposed via this interface. # # Unexposed expressions have the same operations as any other kind of # expression; one can extract their location information, spelling, children, # etc. However, the specific kind of the expression is not reported. CursorKind.UNEXPOSED_EXPR = CursorKind(100) # An expression that refers to some value declaration, such as a function, # varible, or enumerator. CursorKind.DECL_REF_EXPR = CursorKind(101) # An expression that refers to a member of a struct, union, class, Objective-C # class, etc. CursorKind.MEMBER_REF_EXPR = CursorKind(102) # An expression that calls a function. CursorKind.CALL_EXPR = CursorKind(103) # An expression that sends a message to an Objective-C object or class. CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104) # An expression that represents a block literal. CursorKind.BLOCK_EXPR = CursorKind(105) # An integer literal. CursorKind.INTEGER_LITERAL = CursorKind(106) # A floating point number literal. CursorKind.FLOATING_LITERAL = CursorKind(107) # An imaginary number literal. CursorKind.IMAGINARY_LITERAL = CursorKind(108) # A string literal. CursorKind.STRING_LITERAL = CursorKind(109) # A character literal. CursorKind.CHARACTER_LITERAL = CursorKind(110) # A parenthesized expression, e.g. "(1)". # # This AST node is only formed if full location information is requested. CursorKind.PAREN_EXPR = CursorKind(111) # This represents the unary-expression's (except sizeof and # alignof). CursorKind.UNARY_OPERATOR = CursorKind(112) # [C99 6.5.2.1] Array Subscripting. CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113) # A builtin binary operation expression such as "x + y" or # "x <= y". CursorKind.BINARY_OPERATOR = CursorKind(114) # Compound assignment such as "+=". CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) # The ?: ternary operator. CursorKind.CONDITONAL_OPERATOR = CursorKind(116) # An explicit cast in C (C99 6.5.4) or a C-style cast in C++ # (C++ [expr.cast]), which uses the syntax (Type)expr. # # For example: (int)f. CursorKind.CSTYLE_CAST_EXPR = CursorKind(117) # [C99 6.5.2.5] CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118) # Describes an C or C++ initializer list. CursorKind.INIT_LIST_EXPR = CursorKind(119) # The GNU address of label extension, representing &&label. CursorKind.ADDR_LABEL_EXPR = CursorKind(120) # This is the GNU Statement Expression extension: ({int X=4; X;}) CursorKind.StmtExpr = CursorKind(121) # Represents a C1X generic selection. CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122) # Implements the GNU __null extension, which is a name for a null # pointer constant that has integral type (e.g., int or long) and is the same # size and alignment as a pointer. # # The __null extension is typically only used by system headers, which define # NULL as __null in C++ rather than using 0 (which is an integer that may not # match the size of a pointer). CursorKind.GNU_NULL_EXPR = CursorKind(123) # C++'s static_cast<> expression. CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124) # C++'s dynamic_cast<> expression. CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125) # C++'s reinterpret_cast<> expression. CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126) # C++'s const_cast<> expression. CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127) # Represents an explicit C++ type conversion that uses "functional" # notion (C++ [expr.type.conv]). # # Example: # \code # x = int(0.5); # \endcode CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128) # A C++ typeid expression (C++ [expr.typeid]). CursorKind.CXX_TYPEID_EXPR = CursorKind(129) # [C++ 2.13.5] C++ Boolean Literal. CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130) # [C++0x 2.14.7] C++ Pointer Literal. CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131) # Represents the "this" expression in C++ CursorKind.CXX_THIS_EXPR = CursorKind(132) # [C++ 15] C++ Throw Expression. # # This handles 'throw' and 'throw' assignment-expression. When # assignment-expression isn't present, Op will be null. CursorKind.CXX_THROW_EXPR = CursorKind(133) # A new expression for memory allocation and constructor calls, e.g: # "new CXXNewExpr(foo)". CursorKind.CXX_NEW_EXPR = CursorKind(134) # A delete expression for memory deallocation and destructor calls, # e.g. "delete[] pArray". CursorKind.CXX_DELETE_EXPR = CursorKind(135) # Represents a unary expression. CursorKind.CXX_UNARY_EXPR = CursorKind(136) # ObjCStringLiteral, used for Objective-C string literals i.e. "foo". CursorKind.OBJC_STRING_LITERAL = CursorKind(137) # ObjCEncodeExpr, used for in Objective-C. CursorKind.OBJC_ENCODE_EXPR = CursorKind(138) # ObjCSelectorExpr used for in Objective-C. CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139) # Objective-C's protocol expression. CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140) # An Objective-C "bridged" cast expression, which casts between # Objective-C pointers and C pointers, transferring ownership in the process. # # \code # NSString *str = (__bridge_transfer NSString *)CFCreateString(); # \endcode CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141) # Represents a C++0x pack expansion that produces a sequence of # expressions. # # A pack expansion expression contains a pattern (which itself is an # expression) followed by an ellipsis. For example: CursorKind.PACK_EXPANSION_EXPR = CursorKind(142) # Represents an expression that computes the length of a parameter # pack. CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143) # A statement whose specific kind is not exposed via this interface. # # Unexposed statements have the same operations as any other kind of statement; # one can extract their location information, spelling, children, etc. However, # the specific kind of the statement is not reported. CursorKind.UNEXPOSED_STMT = CursorKind(200) # A labelled statement in a function. CursorKind.LABEL_STMT = CursorKind(201) # A compound statement CursorKind.COMPOUND_STMT = CursorKind(202) # A case statement. CursorKind.CASE_STMT = CursorKind(203) # A default statement. CursorKind.DEFAULT_STMT = CursorKind(204) # An if statement. CursorKind.IF_STMT = CursorKind(205) # A switch statement. CursorKind.SWITCH_STMT = CursorKind(206) # A while statement. CursorKind.WHILE_STMT = CursorKind(207) # A do statement. CursorKind.DO_STMT = CursorKind(208) # A for statement. CursorKind.FOR_STMT = CursorKind(209) # A goto statement. CursorKind.GOTO_STMT = CursorKind(210) # An indirect goto statement. CursorKind.INDIRECT_GOTO_STMT = CursorKind(211) # A continue statement. CursorKind.CONTINUE_STMT = CursorKind(212) # A break statement. CursorKind.BREAK_STMT = CursorKind(213) # A return statement. CursorKind.RETURN_STMT = CursorKind(214) # A GNU-style inline assembler statement. CursorKind.ASM_STMT = CursorKind(215) # Objective-C's overall @try-@catch-@finally statement. CursorKind.OBJC_AT_TRY_STMT = CursorKind(216) # Objective-C's @catch statement. CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217) # Objective-C's @finally statement. CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218) # Objective-C's @throw statement. CursorKind.OBJC_AT_THROW_STMT = CursorKind(219) # Objective-C's @synchronized statement. CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220) # Objective-C's autorealease pool statement. CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221) # Objective-C's for collection statement. CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222) # C++'s catch statement. CursorKind.CXX_CATCH_STMT = CursorKind(223) # C++'s try statement. CursorKind.CXX_TRY_STMT = CursorKind(224) # C++'s for (* : *) statement. CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225) # Windows Structured Exception Handling's try statement. CursorKind.SEH_TRY_STMT = CursorKind(226) # Windows Structured Exception Handling's except statement. CursorKind.SEH_EXCEPT_STMT = CursorKind(227) # Windows Structured Exception Handling's finally statement. CursorKind.SEH_FINALLY_STMT = CursorKind(228) # The null statement. CursorKind.NULL_STMT = CursorKind(230) # Adaptor class for mixing declarations with statements and expressions. CursorKind.DECL_STMT = CursorKind(231) ### # Other Kinds # Cursor that represents the translation unit itself. # # The translation unit cursor exists primarily to act as the root cursor for # traversing the contents of a translation unit. CursorKind.TRANSLATION_UNIT = CursorKind(300) ### # Attributes # An attribute whoe specific kind is note exposed via this interface CursorKind.UNEXPOSED_ATTR = CursorKind(400) CursorKind.IB_ACTION_ATTR = CursorKind(401) CursorKind.IB_OUTLET_ATTR = CursorKind(402) CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403) ### # Preprocessing CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500) CursorKind.MACRO_DEFINITION = CursorKind(501) CursorKind.MACRO_INSTANTIATION = CursorKind(502) CursorKind.INCLUSION_DIRECTIVE = CursorKind(503) ### Cursors ### class Cursor(Structure): """ The Cursor class represents a reference to an element within the AST. It acts as a kind of iterator. """ _fields_ = [("_kind_id", c_int), ("data", c_void_p * 3)] def __eq__(self, other): return Cursor_eq(self, other) def __ne__(self, other): return not Cursor_eq(self, other) def is_definition(self): """ Returns true if the declaration pointed at by the cursor is also a definition of that entity. """ return Cursor_is_def(self) def get_definition(self): """ If the cursor is a reference to a declaration or a declaration of some entity, return a cursor that points to the definition of that entity. """ # TODO: Should probably check that this is either a reference or # declaration prior to issuing the lookup. return Cursor_def(self) def get_usr(self): """Return the Unified Symbol Resultion (USR) for the entity referenced by the given cursor (or None). A Unified Symbol Resolution (USR) is a string that identifies a particular entity (function, class, variable, etc.) within a program. USRs can be compared across translation units to determine, e.g., when references in one translation refer to an entity defined in another translation unit.""" return Cursor_usr(self) @property def kind(self): """Return the kind of this cursor.""" return CursorKind.from_id(self._kind_id) @property def spelling(self): """Return the spelling of the entity pointed at by the cursor.""" if not self.kind.is_declaration(): # FIXME: clang_getCursorSpelling should be fixed to not assert on # this, for consistency with clang_getCursorUSR. return None if not hasattr(self, '_spelling'): self._spelling = Cursor_spelling(self) return self._spelling @property def displayname(self): """ Return the display name for the entity referenced by this cursor. The display name contains extra information that helps identify the cursor, such as the parameters of a function or template or the arguments of a class template specialization. """ if not hasattr(self, '_displayname'): self._displayname = Cursor_displayname(self) return self._displayname @property def location(self): """ Return the source location (the starting character) of the entity pointed at by the cursor. """ if not hasattr(self, '_loc'): self._loc = Cursor_loc(self) return self._loc @property def extent(self): """ Return the source range (the range of text) occupied by the entity pointed at by the cursor. """ if not hasattr(self, '_extent'): self._extent = Cursor_extent(self) return self._extent @property def type(self): """ Retrieve the type (if any) of of the entity pointed at by the cursor. """ if not hasattr(self, '_type'): self._type = Cursor_type(self) return self._type def get_children(self): """Return an iterator for accessing the children of this cursor.""" # FIXME: Expose iteration from CIndex, PR6125. def visitor(child, parent, children): # FIXME: Document this assertion in API. # FIXME: There should just be an isNull method. assert child != Cursor_null() children.append(child) return 1 # continue children = [] Cursor_visit(self, Cursor_visit_callback(visitor), children) return iter(children) @staticmethod def from_result(res, fn, args): assert isinstance(res, Cursor) # FIXME: There should just be an isNull method. if res == Cursor_null(): return None return res ### Type Kinds ### class TypeKind(object): """ Describes the kind of type. """ # The unique kind objects, indexed by id. _kinds = [] _name_map = None def __init__(self, value): if value >= len(TypeKind._kinds): TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1) if TypeKind._kinds[value] is not None: raise ValueError,'TypeKind already loaded' self.value = value TypeKind._kinds[value] = self TypeKind._name_map = None def from_param(self): return self.value @property def name(self): """Get the enumeration name of this cursor kind.""" if self._name_map is None: self._name_map = {} for key,value in TypeKind.__dict__.items(): if isinstance(value,TypeKind): self._name_map[value] = key return self._name_map[self] @staticmethod def from_id(id): if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None: raise ValueError,'Unknown cursor kind' return TypeKind._kinds[id] def __repr__(self): return 'TypeKind.%s' % (self.name,) TypeKind.INVALID = TypeKind(0) TypeKind.UNEXPOSED = TypeKind(1) TypeKind.VOID = TypeKind(2) TypeKind.BOOL = TypeKind(3) TypeKind.CHAR_U = TypeKind(4) TypeKind.UCHAR = TypeKind(5) TypeKind.CHAR16 = TypeKind(6) TypeKind.CHAR32 = TypeKind(7) TypeKind.USHORT = TypeKind(8) TypeKind.UINT = TypeKind(9) TypeKind.ULONG = TypeKind(10) TypeKind.ULONGLONG = TypeKind(11) TypeKind.UINT128 = TypeKind(12) TypeKind.CHAR_S = TypeKind(13) TypeKind.SCHAR = TypeKind(14) TypeKind.WCHAR = TypeKind(15) TypeKind.SHORT = TypeKind(16) TypeKind.INT = TypeKind(17) TypeKind.LONG = TypeKind(18) TypeKind.LONGLONG = TypeKind(19) TypeKind.INT128 = TypeKind(20) TypeKind.FLOAT = TypeKind(21) TypeKind.DOUBLE = TypeKind(22) TypeKind.LONGDOUBLE = TypeKind(23) TypeKind.NULLPTR = TypeKind(24) TypeKind.OVERLOAD = TypeKind(25) TypeKind.DEPENDENT = TypeKind(26) TypeKind.OBJCID = TypeKind(27) TypeKind.OBJCCLASS = TypeKind(28) TypeKind.OBJCSEL = TypeKind(29) TypeKind.COMPLEX = TypeKind(100) TypeKind.POINTER = TypeKind(101) TypeKind.BLOCKPOINTER = TypeKind(102) TypeKind.LVALUEREFERENCE = TypeKind(103) TypeKind.RVALUEREFERENCE = TypeKind(104) TypeKind.RECORD = TypeKind(105) TypeKind.ENUM = TypeKind(106) TypeKind.TYPEDEF = TypeKind(107) TypeKind.OBJCINTERFACE = TypeKind(108) TypeKind.OBJCOBJECTPOINTER = TypeKind(109) TypeKind.FUNCTIONNOPROTO = TypeKind(110) TypeKind.FUNCTIONPROTO = TypeKind(111) class Type(Structure): """ The type of an element in the abstract syntax tree. """ _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] @property def kind(self): """Return the kind of this type.""" return TypeKind.from_id(self._kind_id) @staticmethod def from_result(res, fn, args): assert isinstance(res, Type) return res def get_canonical(self): """ Return the canonical type for a Type. Clang's type system explicitly models typedefs and all the ways a specific type can be represented. The canonical type is the underlying type with all the "sugar" removed. For example, if 'T' is a typedef for 'int', the canonical type for 'T' would be 'int'. """ return Type_get_canonical(self) def is_const_qualified(self): """ Determine whether a Type has the "const" qualifier set, without looking through typedefs that may have added "const" at a different level. """ return Type_is_const_qualified(self) def is_volatile_qualified(self): """ Determine whether a Type has the "volatile" qualifier set, without looking through typedefs that may have added "volatile" at a different level. """ return Type_is_volatile_qualified(self) def is_restrict_qualified(self): """ Determine whether a Type has the "restrict" qualifier set, without looking through typedefs that may have added "restrict" at a different level. """ return Type_is_restrict_qualified(self) def get_pointee(self): """ For pointer types, returns the type of the pointee. """ return Type_get_pointee(self) def get_declaration(self): """ Return the cursor for the declaration of the given type. """ return Type_get_declaration(self) def get_result(self): """ Retrieve the result type associated with a function type. """ return Type_get_result(self) ## CIndex Objects ## # CIndex objects (derived from ClangObject) are essentially lightweight # wrappers attached to some underlying object, which is exposed via CIndex as # a void*. class ClangObject(object): """ A helper for Clang objects. This class helps act as an intermediary for the ctypes library and the Clang CIndex library. """ def __init__(self, obj): assert isinstance(obj, c_object_p) and obj self.obj = self._as_parameter_ = obj def from_param(self): return self._as_parameter_ class _CXUnsavedFile(Structure): """Helper for passing unsaved file arguments.""" _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] ## Diagnostic Conversion ## _clang_getNumDiagnostics = lib.clang_getNumDiagnostics _clang_getNumDiagnostics.argtypes = [c_object_p] _clang_getNumDiagnostics.restype = c_uint _clang_getDiagnostic = lib.clang_getDiagnostic _clang_getDiagnostic.argtypes = [c_object_p, c_uint] _clang_getDiagnostic.restype = c_object_p _clang_disposeDiagnostic = lib.clang_disposeDiagnostic _clang_disposeDiagnostic.argtypes = [Diagnostic] _clang_getDiagnosticSeverity = lib.clang_getDiagnosticSeverity _clang_getDiagnosticSeverity.argtypes = [Diagnostic] _clang_getDiagnosticSeverity.restype = c_int _clang_getDiagnosticLocation = lib.clang_getDiagnosticLocation _clang_getDiagnosticLocation.argtypes = [Diagnostic] _clang_getDiagnosticLocation.restype = SourceLocation _clang_getDiagnosticSpelling = lib.clang_getDiagnosticSpelling _clang_getDiagnosticSpelling.argtypes = [Diagnostic] _clang_getDiagnosticSpelling.restype = _CXString _clang_getDiagnosticSpelling.errcheck = _CXString.from_result _clang_getDiagnosticNumRanges = lib.clang_getDiagnosticNumRanges _clang_getDiagnosticNumRanges.argtypes = [Diagnostic] _clang_getDiagnosticNumRanges.restype = c_uint _clang_getDiagnosticRange = lib.clang_getDiagnosticRange _clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint] _clang_getDiagnosticRange.restype = SourceRange _clang_getDiagnosticNumFixIts = lib.clang_getDiagnosticNumFixIts _clang_getDiagnosticNumFixIts.argtypes = [Diagnostic] _clang_getDiagnosticNumFixIts.restype = c_uint _clang_getDiagnosticFixIt = lib.clang_getDiagnosticFixIt _clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint, POINTER(SourceRange)] _clang_getDiagnosticFixIt.restype = _CXString _clang_getDiagnosticFixIt.errcheck = _CXString.from_result ### class CompletionChunk: class Kind: def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return "<ChunkKind: %s>" % self def __init__(self, completionString, key): self.cs = completionString self.key = key def __repr__(self): return "{'" + self.spelling + "', " + str(self.kind) + "}" @property def spelling(self): return _clang_getCompletionChunkText(self.cs, self.key).spelling @property def kind(self): res = _clang_getCompletionChunkKind(self.cs, self.key) return completionChunkKindMap[res] @property def string(self): res = _clang_getCompletionChunkCompletionString(self.cs, self.key) if (res): return CompletionString(res) else: None def isKindOptional(self): return self.kind == completionChunkKindMap[0] def isKindTypedText(self): return self.kind == completionChunkKindMap[1] def isKindPlaceHolder(self): return self.kind == completionChunkKindMap[3] def isKindInformative(self): return self.kind == completionChunkKindMap[4] def isKindResultType(self): return self.kind == completionChunkKindMap[15] completionChunkKindMap = { 0: CompletionChunk.Kind("Optional"), 1: CompletionChunk.Kind("TypedText"), 2: CompletionChunk.Kind("Text"), 3: CompletionChunk.Kind("Placeholder"), 4: CompletionChunk.Kind("Informative"), 5: CompletionChunk.Kind("CurrentParameter"), 6: CompletionChunk.Kind("LeftParen"), 7: CompletionChunk.Kind("RightParen"), 8: CompletionChunk.Kind("LeftBracket"), 9: CompletionChunk.Kind("RightBracket"), 10: CompletionChunk.Kind("LeftBrace"), 11: CompletionChunk.Kind("RightBrace"), 12: CompletionChunk.Kind("LeftAngle"), 13: CompletionChunk.Kind("RightAngle"), 14: CompletionChunk.Kind("Comma"), 15: CompletionChunk.Kind("ResultType"), 16: CompletionChunk.Kind("Colon"), 17: CompletionChunk.Kind("SemiColon"), 18: CompletionChunk.Kind("Equal"), 19: CompletionChunk.Kind("HorizontalSpace"), 20: CompletionChunk.Kind("VerticalSpace")} class CompletionString(ClangObject): class Availability: def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return "<Availability: %s>" % self def __len__(self): return _clang_getNumCompletionChunks(self.obj) def __getitem__(self, key): if len(self) <= key: raise IndexError return CompletionChunk(self.obj, key) @property def priority(self): return _clang_getCompletionPriority(self.obj) @property def availability(self): res = _clang_getCompletionAvailability(self.obj) return availabilityKinds[res] def __repr__(self): return " | ".join([str(a) for a in self]) \ + " || Priority: " + str(self.priority) \ + " || Availability: " + str(self.availability) availabilityKinds = { 0: CompletionChunk.Kind("Available"), 1: CompletionChunk.Kind("Deprecated"), 2: CompletionChunk.Kind("NotAvailable")} class CodeCompletionResult(Structure): _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] def __repr__(self): return str(CompletionString(self.completionString)) @property def kind(self): return CursorKind.from_id(self.cursorKind) @property def string(self): return CompletionString(self.completionString) class CCRStructure(Structure): _fields_ = [('results', POINTER(CodeCompletionResult)), ('numResults', c_int)] def __len__(self): return self.numResults def __getitem__(self, key): if len(self) <= key: raise IndexError return self.results[key] class CodeCompletionResults(ClangObject): def __init__(self, ptr): assert isinstance(ptr, POINTER(CCRStructure)) and ptr self.ptr = self._as_parameter_ = ptr def from_param(self): return self._as_parameter_ def __del__(self): CodeCompletionResults_dispose(self) @property def results(self): return self.ptr.contents @property def diagnostics(self): class DiagnosticsItr: def __init__(self, ccr): self.ccr= ccr def __len__(self): return int(_clang_codeCompleteGetNumDiagnostics(self.ccr)) def __getitem__(self, key): return _clang_codeCompleteGetDiagnostic(self.ccr, key) return DiagnosticsItr(self) class Index(ClangObject): """ The Index type provides the primary interface to the Clang CIndex library, primarily by providing an interface for reading and parsing translation units. """ @staticmethod def create(excludeDecls=False): """ Create a new Index. Parameters: excludeDecls -- Exclude local declarations from translation units. """ return Index(Index_create(excludeDecls, 0)) def __del__(self): Index_dispose(self) def read(self, path): """Load the translation unit from the given AST file.""" ptr = TranslationUnit_read(self, path) return TranslationUnit(ptr) if ptr else None def parse(self, path, args = [], unsaved_files = [], options = 0): """ Load the translation unit from the given source code file by running clang and generating the AST before loading. Additional command line parameters can be passed to clang via the args parameter. In-memory contents for files can be provided by passing a list of pairs to as unsaved_files, the first item should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ arg_array = 0 if len(args): arg_array = (c_char_p * len(args))(* args) unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print value if not isinstance(value, str): raise TypeError,'Unexpected unsaved file contents.' unsaved_files_array[i].name = name unsaved_files_array[i].contents = value unsaved_files_array[i].length = len(value) ptr = TranslationUnit_parse(self, path, arg_array, len(args), unsaved_files_array, len(unsaved_files), options) return TranslationUnit(ptr) if ptr else None class TranslationUnit(ClangObject): """ The TranslationUnit class represents a source code translation unit and provides read-only access to its top-level declarations. """ def __init__(self, ptr): ClangObject.__init__(self, ptr) def __del__(self): TranslationUnit_dispose(self) @property def cursor(self): """Retrieve the cursor that represents the given translation unit.""" return TranslationUnit_cursor(self) @property def spelling(self): """Get the original translation unit source file name.""" return TranslationUnit_spelling(self) def get_includes(self): """ Return an iterable sequence of FileInclusion objects that describe the sequence of inclusions in a translation unit. The first object in this sequence is always the input file. Note that this method will not recursively iterate over header files included through precompiled headers. """ def visitor(fobj, lptr, depth, includes): if depth > 0: loc = lptr.contents includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) # Automatically adapt CIndex/ctype pointers to python objects includes = [] TranslationUnit_includes(self, TranslationUnit_includes_callback(visitor), includes) return iter(includes) @property def diagnostics(self): """ Return an iterable (and indexable) object containing the diagnostics. """ class DiagIterator: def __init__(self, tu): self.tu = tu def __len__(self): return int(_clang_getNumDiagnostics(self.tu)) def __getitem__(self, key): diag = _clang_getDiagnostic(self.tu, key) if not diag: raise IndexError return Diagnostic(diag) return DiagIterator(self) def reparse(self, unsaved_files = [], options = 0): """ Reparse an already parsed translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print value if not isinstance(value, str): raise TypeError,'Unexpected unsaved file contents.' unsaved_files_array[i].name = name unsaved_files_array[i].contents = value unsaved_files_array[i].length = len(value) ptr = TranslationUnit_reparse(self, len(unsaved_files), unsaved_files_array, options) def codeComplete(self, path, line, column, unsaved_files = [], options = 0): """ Code complete in this translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print value if not isinstance(value, str): raise TypeError,'Unexpected unsaved file contents.' unsaved_files_array[i].name = name unsaved_files_array[i].contents = value unsaved_files_array[i].length = len(value) ptr = TranslationUnit_codeComplete(self, path, line, column, unsaved_files_array, len(unsaved_files), options) return CodeCompletionResults(ptr) if ptr else None class File(ClangObject): """ The File class represents a particular source file that is part of a translation unit. """ @property def name(self): """Return the complete file and path name of the file.""" return _CXString_getCString(File_name(self)) @property def time(self): """Return the last modification time of the file.""" return File_time(self) class FileInclusion(object): """ The FileInclusion class represents the inclusion of one source file by another via a '#include' directive or as the input file for the translation unit. This class provides information about the included file, the including file, the location of the '#include' directive and the depth of the included file in the stack. Note that the input file has depth 0. """ def __init__(self, src, tgt, loc, depth): self.source = src self.include = tgt self.location = loc self.depth = depth @property def is_input_file(self): """True if the included file is the input file.""" return self.depth == 0 # Additional Functions and Types # String Functions _CXString_dispose = lib.clang_disposeString _CXString_dispose.argtypes = [_CXString] _CXString_getCString = lib.clang_getCString _CXString_getCString.argtypes = [_CXString] _CXString_getCString.restype = c_char_p # Source Location Functions SourceLocation_loc = lib.clang_getInstantiationLocation SourceLocation_loc.argtypes = [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint)] # Source Range Functions SourceRange_getRange = lib.clang_getRange SourceRange_getRange.argtypes = [SourceLocation, SourceLocation] SourceRange_getRange.restype = SourceRange SourceRange_start = lib.clang_getRangeStart SourceRange_start.argtypes = [SourceRange] SourceRange_start.restype = SourceLocation SourceRange_end = lib.clang_getRangeEnd SourceRange_end.argtypes = [SourceRange] SourceRange_end.restype = SourceLocation # CursorKind Functions CursorKind_is_decl = lib.clang_isDeclaration CursorKind_is_decl.argtypes = [CursorKind] CursorKind_is_decl.restype = bool CursorKind_is_ref = lib.clang_isReference CursorKind_is_ref.argtypes = [CursorKind] CursorKind_is_ref.restype = bool CursorKind_is_expr = lib.clang_isExpression CursorKind_is_expr.argtypes = [CursorKind] CursorKind_is_expr.restype = bool CursorKind_is_stmt = lib.clang_isStatement CursorKind_is_stmt.argtypes = [CursorKind] CursorKind_is_stmt.restype = bool CursorKind_is_attribute = lib.clang_isAttribute CursorKind_is_attribute.argtypes = [CursorKind] CursorKind_is_attribute.restype = bool CursorKind_is_inv = lib.clang_isInvalid CursorKind_is_inv.argtypes = [CursorKind] CursorKind_is_inv.restype = bool # Cursor Functions # TODO: Implement this function Cursor_get = lib.clang_getCursor Cursor_get.argtypes = [TranslationUnit, SourceLocation] Cursor_get.restype = Cursor Cursor_null = lib.clang_getNullCursor Cursor_null.restype = Cursor Cursor_usr = lib.clang_getCursorUSR Cursor_usr.argtypes = [Cursor] Cursor_usr.restype = _CXString Cursor_usr.errcheck = _CXString.from_result Cursor_is_def = lib.clang_isCursorDefinition Cursor_is_def.argtypes = [Cursor] Cursor_is_def.restype = bool Cursor_def = lib.clang_getCursorDefinition Cursor_def.argtypes = [Cursor] Cursor_def.restype = Cursor Cursor_def.errcheck = Cursor.from_result Cursor_eq = lib.clang_equalCursors Cursor_eq.argtypes = [Cursor, Cursor] Cursor_eq.restype = c_uint Cursor_spelling = lib.clang_getCursorSpelling Cursor_spelling.argtypes = [Cursor] Cursor_spelling.restype = _CXString Cursor_spelling.errcheck = _CXString.from_result Cursor_displayname = lib.clang_getCursorDisplayName Cursor_displayname.argtypes = [Cursor] Cursor_displayname.restype = _CXString Cursor_displayname.errcheck = _CXString.from_result Cursor_loc = lib.clang_getCursorLocation Cursor_loc.argtypes = [Cursor] Cursor_loc.restype = SourceLocation Cursor_extent = lib.clang_getCursorExtent Cursor_extent.argtypes = [Cursor] Cursor_extent.restype = SourceRange Cursor_ref = lib.clang_getCursorReferenced Cursor_ref.argtypes = [Cursor] Cursor_ref.restype = Cursor Cursor_ref.errcheck = Cursor.from_result Cursor_type = lib.clang_getCursorType Cursor_type.argtypes = [Cursor] Cursor_type.restype = Type Cursor_type.errcheck = Type.from_result Cursor_visit_callback = CFUNCTYPE(c_int, Cursor, Cursor, py_object) Cursor_visit = lib.clang_visitChildren Cursor_visit.argtypes = [Cursor, Cursor_visit_callback, py_object] Cursor_visit.restype = c_uint # Type Functions Type_get_canonical = lib.clang_getCanonicalType Type_get_canonical.argtypes = [Type] Type_get_canonical.restype = Type Type_get_canonical.errcheck = Type.from_result Type_is_const_qualified = lib.clang_isConstQualifiedType Type_is_const_qualified.argtypes = [Type] Type_is_const_qualified.restype = bool Type_is_volatile_qualified = lib.clang_isVolatileQualifiedType Type_is_volatile_qualified.argtypes = [Type] Type_is_volatile_qualified.restype = bool Type_is_restrict_qualified = lib.clang_isRestrictQualifiedType Type_is_restrict_qualified.argtypes = [Type] Type_is_restrict_qualified.restype = bool Type_get_pointee = lib.clang_getPointeeType Type_get_pointee.argtypes = [Type] Type_get_pointee.restype = Type Type_get_pointee.errcheck = Type.from_result Type_get_declaration = lib.clang_getTypeDeclaration Type_get_declaration.argtypes = [Type] Type_get_declaration.restype = Cursor Type_get_declaration.errcheck = Cursor.from_result Type_get_result = lib.clang_getResultType Type_get_result.argtypes = [Type] Type_get_result.restype = Type Type_get_result.errcheck = Type.from_result # Index Functions Index_create = lib.clang_createIndex Index_create.argtypes = [c_int, c_int] Index_create.restype = c_object_p Index_dispose = lib.clang_disposeIndex Index_dispose.argtypes = [Index] # Translation Unit Functions TranslationUnit_read = lib.clang_createTranslationUnit TranslationUnit_read.argtypes = [Index, c_char_p] TranslationUnit_read.restype = c_object_p TranslationUnit_parse = lib.clang_parseTranslationUnit TranslationUnit_parse.argtypes = [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int] TranslationUnit_parse.restype = c_object_p TranslationUnit_reparse = lib.clang_reparseTranslationUnit TranslationUnit_reparse.argtypes = [TranslationUnit, c_int, c_void_p, c_int] TranslationUnit_reparse.restype = c_int TranslationUnit_codeComplete = lib.clang_codeCompleteAt TranslationUnit_codeComplete.argtypes = [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int] TranslationUnit_codeComplete.restype = POINTER(CCRStructure) TranslationUnit_cursor = lib.clang_getTranslationUnitCursor TranslationUnit_cursor.argtypes = [TranslationUnit] TranslationUnit_cursor.restype = Cursor TranslationUnit_cursor.errcheck = Cursor.from_result TranslationUnit_spelling = lib.clang_getTranslationUnitSpelling TranslationUnit_spelling.argtypes = [TranslationUnit] TranslationUnit_spelling.restype = _CXString TranslationUnit_spelling.errcheck = _CXString.from_result TranslationUnit_dispose = lib.clang_disposeTranslationUnit TranslationUnit_dispose.argtypes = [TranslationUnit] TranslationUnit_includes_callback = CFUNCTYPE(None, c_object_p, POINTER(SourceLocation), c_uint, py_object) TranslationUnit_includes = lib.clang_getInclusions TranslationUnit_includes.argtypes = [TranslationUnit, TranslationUnit_includes_callback, py_object] # File Functions File_name = lib.clang_getFileName File_name.argtypes = [File] File_name.restype = _CXString File_time = lib.clang_getFileTime File_time.argtypes = [File] File_time.restype = c_uint # Code completion CodeCompletionResults_dispose = lib.clang_disposeCodeCompleteResults CodeCompletionResults_dispose.argtypes = [CodeCompletionResults] _clang_codeCompleteGetNumDiagnostics = lib.clang_codeCompleteGetNumDiagnostics _clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults] _clang_codeCompleteGetNumDiagnostics.restype = c_int _clang_codeCompleteGetDiagnostic = lib.clang_codeCompleteGetDiagnostic _clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults, c_int] _clang_codeCompleteGetDiagnostic.restype = Diagnostic _clang_getCompletionChunkText = lib.clang_getCompletionChunkText _clang_getCompletionChunkText.argtypes = [c_void_p, c_int] _clang_getCompletionChunkText.restype = _CXString _clang_getCompletionChunkKind = lib.clang_getCompletionChunkKind _clang_getCompletionChunkKind.argtypes = [c_void_p, c_int] _clang_getCompletionChunkKind.restype = c_int _clang_getCompletionChunkCompletionString = lib.clang_getCompletionChunkCompletionString _clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int] _clang_getCompletionChunkCompletionString.restype = c_object_p _clang_getNumCompletionChunks = lib.clang_getNumCompletionChunks _clang_getNumCompletionChunks.argtypes = [c_void_p] _clang_getNumCompletionChunks.restype = c_int _clang_getCompletionAvailability = lib.clang_getCompletionAvailability _clang_getCompletionAvailability.argtypes = [c_void_p] _clang_getCompletionAvailability.restype = c_int _clang_getCompletionPriority = lib.clang_getCompletionPriority _clang_getCompletionPriority.argtypes = [c_void_p] _clang_getCompletionPriority.restype = c_int ### __all__ = ['Index', 'TranslationUnit', 'Cursor', 'CursorKind', 'Type', 'TypeKind', 'Diagnostic', 'FixIt', 'CodeCompletionResults', 'SourceRange', 'SourceLocation', 'File']
bsd-3-clause
Ariaban/Memoriz
node_modules/gulp-sass/node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
241
63805
# 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. """ This module contains classes that help to emulate xcodebuild behavior on top of other build systems, such as make and ninja. """ import copy import gyp.common import os import os.path import re import shlex import subprocess import sys import tempfile from gyp.common import GypError # Populated lazily by XcodeVersion, for efficiency, and to fix an issue when # "xcodebuild" is called too quickly (it has been found to return incorrect # version number). XCODE_VERSION_CACHE = None # Populated lazily by GetXcodeArchsDefault, to an |XcodeArchsDefault| instance # corresponding to the installed version of Xcode. XCODE_ARCHS_DEFAULT_CACHE = None def XcodeArchsVariableMapping(archs, archs_including_64_bit=None): """Constructs a dictionary with expansion for $(ARCHS_STANDARD) variable, and optionally for $(ARCHS_STANDARD_INCLUDING_64_BIT).""" mapping = {'$(ARCHS_STANDARD)': archs} if archs_including_64_bit: mapping['$(ARCHS_STANDARD_INCLUDING_64_BIT)'] = archs_including_64_bit return mapping class XcodeArchsDefault(object): """A class to resolve ARCHS variable from xcode_settings, resolving Xcode macros and implementing filtering by VALID_ARCHS. The expansion of macros depends on the SDKROOT used ("macosx", "iphoneos", "iphonesimulator") and on the version of Xcode. """ # Match variable like $(ARCHS_STANDARD). variable_pattern = re.compile(r'\$\([a-zA-Z_][a-zA-Z0-9_]*\)$') def __init__(self, default, mac, iphonesimulator, iphoneos): self._default = (default,) self._archs = {'mac': mac, 'ios': iphoneos, 'iossim': iphonesimulator} def _VariableMapping(self, sdkroot): """Returns the dictionary of variable mapping depending on the SDKROOT.""" sdkroot = sdkroot.lower() if 'iphoneos' in sdkroot: return self._archs['ios'] elif 'iphonesimulator' in sdkroot: return self._archs['iossim'] else: return self._archs['mac'] def _ExpandArchs(self, archs, sdkroot): """Expands variables references in ARCHS, and remove duplicates.""" variable_mapping = self._VariableMapping(sdkroot) expanded_archs = [] for arch in archs: if self.variable_pattern.match(arch): variable = arch try: variable_expansion = variable_mapping[variable] for arch in variable_expansion: if arch not in expanded_archs: expanded_archs.append(arch) except KeyError as e: print 'Warning: Ignoring unsupported variable "%s".' % variable elif arch not in expanded_archs: expanded_archs.append(arch) return expanded_archs def ActiveArchs(self, archs, valid_archs, sdkroot): """Expands variables references in ARCHS, and filter by VALID_ARCHS if it is defined (if not set, Xcode accept any value in ARCHS, otherwise, only values present in VALID_ARCHS are kept).""" expanded_archs = self._ExpandArchs(archs or self._default, sdkroot or '') if valid_archs: filtered_archs = [] for arch in expanded_archs: if arch in valid_archs: filtered_archs.append(arch) expanded_archs = filtered_archs return expanded_archs def GetXcodeArchsDefault(): """Returns the |XcodeArchsDefault| object to use to expand ARCHS for the installed version of Xcode. The default values used by Xcode for ARCHS and the expansion of the variables depends on the version of Xcode used. For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses $(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0 and deprecated with Xcode 5.1. For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit architecture as part of $(ARCHS_STANDARD) and default to only building it. For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they are also part of $(ARCHS_STANDARD). All thoses rules are coded in the construction of the |XcodeArchsDefault| object to use depending on the version of Xcode detected. The object is for performance reason.""" global XCODE_ARCHS_DEFAULT_CACHE if XCODE_ARCHS_DEFAULT_CACHE: return XCODE_ARCHS_DEFAULT_CACHE xcode_version, _ = XcodeVersion() if xcode_version < '0500': XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( '$(ARCHS_STANDARD)', XcodeArchsVariableMapping(['i386']), XcodeArchsVariableMapping(['i386']), XcodeArchsVariableMapping(['armv7'])) elif xcode_version < '0510': XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( '$(ARCHS_STANDARD_INCLUDING_64_BIT)', XcodeArchsVariableMapping(['x86_64'], ['x86_64']), XcodeArchsVariableMapping(['i386'], ['i386', 'x86_64']), XcodeArchsVariableMapping( ['armv7', 'armv7s'], ['armv7', 'armv7s', 'arm64'])) else: XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( '$(ARCHS_STANDARD)', XcodeArchsVariableMapping(['x86_64'], ['x86_64']), XcodeArchsVariableMapping(['i386', 'x86_64'], ['i386', 'x86_64']), XcodeArchsVariableMapping( ['armv7', 'armv7s', 'arm64'], ['armv7', 'armv7s', 'arm64'])) return XCODE_ARCHS_DEFAULT_CACHE class XcodeSettings(object): """A class that understands the gyp 'xcode_settings' object.""" # Populated lazily by _SdkPath(). Shared by all XcodeSettings, so cached # at class-level for efficiency. _sdk_path_cache = {} _sdk_root_cache = {} # Populated lazily by GetExtraPlistItems(). Shared by all XcodeSettings, so # cached at class-level for efficiency. _plist_cache = {} # Populated lazily by GetIOSPostbuilds. Shared by all XcodeSettings, so # cached at class-level for efficiency. _codesigning_key_cache = {} def __init__(self, spec): self.spec = spec self.isIOS = False # Per-target 'xcode_settings' are pushed down into configs earlier by gyp. # This means self.xcode_settings[config] always contains all settings # for that config -- the per-target settings as well. Settings that are # the same for all configs are implicitly per-target settings. self.xcode_settings = {} configs = spec['configurations'] for configname, config in configs.iteritems(): self.xcode_settings[configname] = config.get('xcode_settings', {}) self._ConvertConditionalKeys(configname) if self.xcode_settings[configname].get('IPHONEOS_DEPLOYMENT_TARGET', None): self.isIOS = True # This is only non-None temporarily during the execution of some methods. self.configname = None # Used by _AdjustLibrary to match .a and .dylib entries in libraries. self.library_re = re.compile(r'^lib([^/]+)\.(a|dylib)$') def _ConvertConditionalKeys(self, configname): """Converts or warns on conditional keys. Xcode supports conditional keys, such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation with some keys converted while the rest force a warning.""" settings = self.xcode_settings[configname] conditional_keys = [key for key in settings if key.endswith(']')] for key in conditional_keys: # If you need more, speak up at http://crbug.com/122592 if key.endswith("[sdk=iphoneos*]"): if configname.endswith("iphoneos"): new_key = key.split("[")[0] settings[new_key] = settings[key] else: print 'Warning: Conditional keys not implemented, ignoring:', \ ' '.join(conditional_keys) del settings[key] def _Settings(self): assert self.configname return self.xcode_settings[self.configname] def _Test(self, test_key, cond_key, default): return self._Settings().get(test_key, default) == cond_key def _Appendf(self, lst, test_key, format_str, default=None): if test_key in self._Settings(): lst.append(format_str % str(self._Settings()[test_key])) elif default: lst.append(format_str % str(default)) def _WarnUnimplemented(self, test_key): if test_key in self._Settings(): print 'Warning: Ignoring not yet implemented key "%s".' % test_key def IsBinaryOutputFormat(self, configname): default = "binary" if self.isIOS else "xml" format = self.xcode_settings[configname].get('INFOPLIST_OUTPUT_FORMAT', default) return format == "binary" def _IsBundle(self): return int(self.spec.get('mac_bundle', 0)) != 0 def _IsIosAppExtension(self): return int(self.spec.get('ios_app_extension', 0)) != 0 def _IsIosWatchKitExtension(self): return int(self.spec.get('ios_watchkit_extension', 0)) != 0 def _IsIosWatchApp(self): return int(self.spec.get('ios_watch_app', 0)) != 0 def GetFrameworkVersion(self): """Returns the framework version of the current target. Only valid for bundles.""" assert self._IsBundle() return self.GetPerTargetSetting('FRAMEWORK_VERSION', default='A') def GetWrapperExtension(self): """Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.""" assert self._IsBundle() if self.spec['type'] in ('loadable_module', 'shared_library'): default_wrapper_extension = { 'loadable_module': 'bundle', 'shared_library': 'framework', }[self.spec['type']] wrapper_extension = self.GetPerTargetSetting( 'WRAPPER_EXTENSION', default=default_wrapper_extension) return '.' + self.spec.get('product_extension', wrapper_extension) elif self.spec['type'] == 'executable': if self._IsIosAppExtension() or self._IsIosWatchKitExtension(): return '.' + self.spec.get('product_extension', 'appex') else: return '.' + self.spec.get('product_extension', 'app') else: assert False, "Don't know extension for '%s', target '%s'" % ( self.spec['type'], self.spec['target_name']) def GetProductName(self): """Returns PRODUCT_NAME.""" return self.spec.get('product_name', self.spec['target_name']) def GetFullProductName(self): """Returns FULL_PRODUCT_NAME.""" if self._IsBundle(): return self.GetWrapperName() else: return self._GetStandaloneBinaryPath() def GetWrapperName(self): """Returns the directory name of the bundle represented by this target. Only valid for bundles.""" assert self._IsBundle() return self.GetProductName() + self.GetWrapperExtension() def GetBundleContentsFolderPath(self): """Returns the qualified path to the bundle's contents folder. E.g. Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles.""" if self.isIOS: return self.GetWrapperName() assert self._IsBundle() if self.spec['type'] == 'shared_library': return os.path.join( self.GetWrapperName(), 'Versions', self.GetFrameworkVersion()) else: # loadable_modules have a 'Contents' folder like executables. return os.path.join(self.GetWrapperName(), 'Contents') def GetBundleResourceFolder(self): """Returns the qualified path to the bundle's resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.""" assert self._IsBundle() if self.isIOS: return self.GetBundleContentsFolderPath() return os.path.join(self.GetBundleContentsFolderPath(), 'Resources') def GetBundlePlistPath(self): """Returns the qualified path to the bundle's plist file. E.g. Chromium.app/Contents/Info.plist. Only valid for bundles.""" assert self._IsBundle() if self.spec['type'] in ('executable', 'loadable_module'): return os.path.join(self.GetBundleContentsFolderPath(), 'Info.plist') else: return os.path.join(self.GetBundleContentsFolderPath(), 'Resources', 'Info.plist') def GetProductType(self): """Returns the PRODUCT_TYPE of this target.""" if self._IsIosAppExtension(): assert self._IsBundle(), ('ios_app_extension flag requires mac_bundle ' '(target %s)' % self.spec['target_name']) return 'com.apple.product-type.app-extension' if self._IsIosWatchKitExtension(): assert self._IsBundle(), ('ios_watchkit_extension flag requires ' 'mac_bundle (target %s)' % self.spec['target_name']) return 'com.apple.product-type.watchkit-extension' if self._IsIosWatchApp(): assert self._IsBundle(), ('ios_watch_app flag requires mac_bundle ' '(target %s)' % self.spec['target_name']) return 'com.apple.product-type.application.watchapp' if self._IsBundle(): return { 'executable': 'com.apple.product-type.application', 'loadable_module': 'com.apple.product-type.bundle', 'shared_library': 'com.apple.product-type.framework', }[self.spec['type']] else: return { 'executable': 'com.apple.product-type.tool', 'loadable_module': 'com.apple.product-type.library.dynamic', 'shared_library': 'com.apple.product-type.library.dynamic', 'static_library': 'com.apple.product-type.library.static', }[self.spec['type']] def GetMachOType(self): """Returns the MACH_O_TYPE of this target.""" # Weird, but matches Xcode. if not self._IsBundle() and self.spec['type'] == 'executable': return '' return { 'executable': 'mh_execute', 'static_library': 'staticlib', 'shared_library': 'mh_dylib', 'loadable_module': 'mh_bundle', }[self.spec['type']] def _GetBundleBinaryPath(self): """Returns the name of the bundle binary of by this target. E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles.""" assert self._IsBundle() if self.spec['type'] in ('shared_library') or self.isIOS: path = self.GetBundleContentsFolderPath() elif self.spec['type'] in ('executable', 'loadable_module'): path = os.path.join(self.GetBundleContentsFolderPath(), 'MacOS') return os.path.join(path, self.GetExecutableName()) def _GetStandaloneExecutableSuffix(self): if 'product_extension' in self.spec: return '.' + self.spec['product_extension'] return { 'executable': '', 'static_library': '.a', 'shared_library': '.dylib', 'loadable_module': '.so', }[self.spec['type']] def _GetStandaloneExecutablePrefix(self): return self.spec.get('product_prefix', { 'executable': '', 'static_library': 'lib', 'shared_library': 'lib', # Non-bundled loadable_modules are called foo.so for some reason # (that is, .so and no prefix) with the xcode build -- match that. 'loadable_module': '', }[self.spec['type']]) def _GetStandaloneBinaryPath(self): """Returns the name of the non-bundle binary represented by this target. E.g. hello_world. Only valid for non-bundles.""" assert not self._IsBundle() assert self.spec['type'] in ( 'executable', 'shared_library', 'static_library', 'loadable_module'), ( 'Unexpected type %s' % self.spec['type']) target = self.spec['target_name'] if self.spec['type'] == 'static_library': if target[:3] == 'lib': target = target[3:] elif self.spec['type'] in ('loadable_module', 'shared_library'): if target[:3] == 'lib': target = target[3:] target_prefix = self._GetStandaloneExecutablePrefix() target = self.spec.get('product_name', target) target_ext = self._GetStandaloneExecutableSuffix() return target_prefix + target + target_ext def GetExecutableName(self): """Returns the executable name of the bundle represented by this target. E.g. Chromium.""" if self._IsBundle(): return self.spec.get('product_name', self.spec['target_name']) else: return self._GetStandaloneBinaryPath() def GetExecutablePath(self): """Returns the directory name of the bundle represented by this target. E.g. Chromium.app/Contents/MacOS/Chromium.""" if self._IsBundle(): return self._GetBundleBinaryPath() else: return self._GetStandaloneBinaryPath() def GetActiveArchs(self, configname): """Returns the architectures this target should be built for.""" config_settings = self.xcode_settings[configname] xcode_archs_default = GetXcodeArchsDefault() return xcode_archs_default.ActiveArchs( config_settings.get('ARCHS'), config_settings.get('VALID_ARCHS'), config_settings.get('SDKROOT')) def _GetSdkVersionInfoItem(self, sdk, infoitem): # xcodebuild requires Xcode and can't run on Command Line Tools-only # systems from 10.7 onward. # Since the CLT has no SDK paths anyway, returning None is the # most sensible route and should still do the right thing. try: return GetStdout(['xcodebuild', '-version', '-sdk', sdk, infoitem]) except: pass def _SdkRoot(self, configname): if configname is None: configname = self.configname return self.GetPerConfigSetting('SDKROOT', configname, default='') def _SdkPath(self, configname=None): sdk_root = self._SdkRoot(configname) if sdk_root.startswith('/'): return sdk_root return self._XcodeSdkPath(sdk_root) def _XcodeSdkPath(self, sdk_root): if sdk_root not in XcodeSettings._sdk_path_cache: sdk_path = self._GetSdkVersionInfoItem(sdk_root, 'Path') XcodeSettings._sdk_path_cache[sdk_root] = sdk_path if sdk_root: XcodeSettings._sdk_root_cache[sdk_path] = sdk_root return XcodeSettings._sdk_path_cache[sdk_root] def _AppendPlatformVersionMinFlags(self, lst): self._Appendf(lst, 'MACOSX_DEPLOYMENT_TARGET', '-mmacosx-version-min=%s') if 'IPHONEOS_DEPLOYMENT_TARGET' in self._Settings(): # TODO: Implement this better? sdk_path_basename = os.path.basename(self._SdkPath()) if sdk_path_basename.lower().startswith('iphonesimulator'): self._Appendf(lst, 'IPHONEOS_DEPLOYMENT_TARGET', '-mios-simulator-version-min=%s') else: self._Appendf(lst, 'IPHONEOS_DEPLOYMENT_TARGET', '-miphoneos-version-min=%s') def GetCflags(self, configname, arch=None): """Returns flags that need to be added to .c, .cc, .m, and .mm compilations.""" # This functions (and the similar ones below) do not offer complete # emulation of all xcode_settings keys. They're implemented on demand. self.configname = configname cflags = [] sdk_root = self._SdkPath() if 'SDKROOT' in self._Settings() and sdk_root: cflags.append('-isysroot %s' % sdk_root) if self._Test('CLANG_WARN_CONSTANT_CONVERSION', 'YES', default='NO'): cflags.append('-Wconstant-conversion') if self._Test('GCC_CHAR_IS_UNSIGNED_CHAR', 'YES', default='NO'): cflags.append('-funsigned-char') if self._Test('GCC_CW_ASM_SYNTAX', 'YES', default='YES'): cflags.append('-fasm-blocks') if 'GCC_DYNAMIC_NO_PIC' in self._Settings(): if self._Settings()['GCC_DYNAMIC_NO_PIC'] == 'YES': cflags.append('-mdynamic-no-pic') else: pass # TODO: In this case, it depends on the target. xcode passes # mdynamic-no-pic by default for executable and possibly static lib # according to mento if self._Test('GCC_ENABLE_PASCAL_STRINGS', 'YES', default='YES'): cflags.append('-mpascal-strings') self._Appendf(cflags, 'GCC_OPTIMIZATION_LEVEL', '-O%s', default='s') if self._Test('GCC_GENERATE_DEBUGGING_SYMBOLS', 'YES', default='YES'): dbg_format = self._Settings().get('DEBUG_INFORMATION_FORMAT', 'dwarf') if dbg_format == 'dwarf': cflags.append('-gdwarf-2') elif dbg_format == 'stabs': raise NotImplementedError('stabs debug format is not supported yet.') elif dbg_format == 'dwarf-with-dsym': cflags.append('-gdwarf-2') else: raise NotImplementedError('Unknown debug format %s' % dbg_format) if self._Settings().get('GCC_STRICT_ALIASING') == 'YES': cflags.append('-fstrict-aliasing') elif self._Settings().get('GCC_STRICT_ALIASING') == 'NO': cflags.append('-fno-strict-aliasing') if self._Test('GCC_SYMBOLS_PRIVATE_EXTERN', 'YES', default='NO'): cflags.append('-fvisibility=hidden') if self._Test('GCC_TREAT_WARNINGS_AS_ERRORS', 'YES', default='NO'): cflags.append('-Werror') if self._Test('GCC_WARN_ABOUT_MISSING_NEWLINE', 'YES', default='NO'): cflags.append('-Wnewline-eof') self._AppendPlatformVersionMinFlags(cflags) # TODO: if self._Test('COPY_PHASE_STRIP', 'YES', default='NO'): self._WarnUnimplemented('COPY_PHASE_STRIP') self._WarnUnimplemented('GCC_DEBUGGING_SYMBOLS') self._WarnUnimplemented('GCC_ENABLE_OBJC_EXCEPTIONS') # TODO: This is exported correctly, but assigning to it is not supported. self._WarnUnimplemented('MACH_O_TYPE') self._WarnUnimplemented('PRODUCT_TYPE') if arch is not None: archs = [arch] else: assert self.configname archs = self.GetActiveArchs(self.configname) if len(archs) != 1: # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented('ARCHS') archs = ['i386'] cflags.append('-arch ' + archs[0]) if archs[0] in ('i386', 'x86_64'): if self._Test('GCC_ENABLE_SSE3_EXTENSIONS', 'YES', default='NO'): cflags.append('-msse3') if self._Test('GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS', 'YES', default='NO'): cflags.append('-mssse3') # Note 3rd 's'. if self._Test('GCC_ENABLE_SSE41_EXTENSIONS', 'YES', default='NO'): cflags.append('-msse4.1') if self._Test('GCC_ENABLE_SSE42_EXTENSIONS', 'YES', default='NO'): cflags.append('-msse4.2') cflags += self._Settings().get('WARNING_CFLAGS', []) if sdk_root: framework_root = sdk_root else: framework_root = '' config = self.spec['configurations'][self.configname] framework_dirs = config.get('mac_framework_dirs', []) for directory in framework_dirs: cflags.append('-F' + directory.replace('$(SDKROOT)', framework_root)) self.configname = None return cflags def GetCflagsC(self, configname): """Returns flags that need to be added to .c, and .m compilations.""" self.configname = configname cflags_c = [] if self._Settings().get('GCC_C_LANGUAGE_STANDARD', '') == 'ansi': cflags_c.append('-ansi') else: self._Appendf(cflags_c, 'GCC_C_LANGUAGE_STANDARD', '-std=%s') cflags_c += self._Settings().get('OTHER_CFLAGS', []) self.configname = None return cflags_c def GetCflagsCC(self, configname): """Returns flags that need to be added to .cc, and .mm compilations.""" self.configname = configname cflags_cc = [] clang_cxx_language_standard = self._Settings().get( 'CLANG_CXX_LANGUAGE_STANDARD') # Note: Don't make c++0x to c++11 so that c++0x can be used with older # clangs that don't understand c++11 yet (like Xcode 4.2's). if clang_cxx_language_standard: cflags_cc.append('-std=%s' % clang_cxx_language_standard) self._Appendf(cflags_cc, 'CLANG_CXX_LIBRARY', '-stdlib=%s') if self._Test('GCC_ENABLE_CPP_RTTI', 'NO', default='YES'): cflags_cc.append('-fno-rtti') if self._Test('GCC_ENABLE_CPP_EXCEPTIONS', 'NO', default='YES'): cflags_cc.append('-fno-exceptions') if self._Test('GCC_INLINES_ARE_PRIVATE_EXTERN', 'YES', default='NO'): cflags_cc.append('-fvisibility-inlines-hidden') if self._Test('GCC_THREADSAFE_STATICS', 'NO', default='YES'): cflags_cc.append('-fno-threadsafe-statics') # Note: This flag is a no-op for clang, it only has an effect for gcc. if self._Test('GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO', 'NO', default='YES'): cflags_cc.append('-Wno-invalid-offsetof') other_ccflags = [] for flag in self._Settings().get('OTHER_CPLUSPLUSFLAGS', ['$(inherited)']): # TODO: More general variable expansion. Missing in many other places too. if flag in ('$inherited', '$(inherited)', '${inherited}'): flag = '$OTHER_CFLAGS' if flag in ('$OTHER_CFLAGS', '$(OTHER_CFLAGS)', '${OTHER_CFLAGS}'): other_ccflags += self._Settings().get('OTHER_CFLAGS', []) else: other_ccflags.append(flag) cflags_cc += other_ccflags self.configname = None return cflags_cc def _AddObjectiveCGarbageCollectionFlags(self, flags): gc_policy = self._Settings().get('GCC_ENABLE_OBJC_GC', 'unsupported') if gc_policy == 'supported': flags.append('-fobjc-gc') elif gc_policy == 'required': flags.append('-fobjc-gc-only') def _AddObjectiveCARCFlags(self, flags): if self._Test('CLANG_ENABLE_OBJC_ARC', 'YES', default='NO'): flags.append('-fobjc-arc') def _AddObjectiveCMissingPropertySynthesisFlags(self, flags): if self._Test('CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS', 'YES', default='NO'): flags.append('-Wobjc-missing-property-synthesis') def GetCflagsObjC(self, configname): """Returns flags that need to be added to .m compilations.""" self.configname = configname cflags_objc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objc) self._AddObjectiveCARCFlags(cflags_objc) self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objc) self.configname = None return cflags_objc def GetCflagsObjCC(self, configname): """Returns flags that need to be added to .mm compilations.""" self.configname = configname cflags_objcc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objcc) self._AddObjectiveCARCFlags(cflags_objcc) self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objcc) if self._Test('GCC_OBJC_CALL_CXX_CDTORS', 'YES', default='NO'): cflags_objcc.append('-fobjc-call-cxx-cdtors') self.configname = None return cflags_objcc def GetInstallNameBase(self): """Return DYLIB_INSTALL_NAME_BASE for this target.""" # Xcode sets this for shared_libraries, and for nonbundled loadable_modules. if (self.spec['type'] != 'shared_library' and (self.spec['type'] != 'loadable_module' or self._IsBundle())): return None install_base = self.GetPerTargetSetting( 'DYLIB_INSTALL_NAME_BASE', default='/Library/Frameworks' if self._IsBundle() else '/usr/local/lib') return install_base def _StandardizePath(self, path): """Do :standardizepath processing for path.""" # I'm not quite sure what :standardizepath does. Just call normpath(), # but don't let @executable_path/../foo collapse to foo. if '/' in path: prefix, rest = '', path if path.startswith('@'): prefix, rest = path.split('/', 1) rest = os.path.normpath(rest) # :standardizepath path = os.path.join(prefix, rest) return path def GetInstallName(self): """Return LD_DYLIB_INSTALL_NAME for this target.""" # Xcode sets this for shared_libraries, and for nonbundled loadable_modules. if (self.spec['type'] != 'shared_library' and (self.spec['type'] != 'loadable_module' or self._IsBundle())): return None default_install_name = \ '$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)' install_name = self.GetPerTargetSetting( 'LD_DYLIB_INSTALL_NAME', default=default_install_name) # Hardcode support for the variables used in chromium for now, to # unblock people using the make build. if '$' in install_name: assert install_name in ('$(DYLIB_INSTALL_NAME_BASE:standardizepath)/' '$(WRAPPER_NAME)/$(PRODUCT_NAME)', default_install_name), ( 'Variables in LD_DYLIB_INSTALL_NAME are not generally supported ' 'yet in target \'%s\' (got \'%s\')' % (self.spec['target_name'], install_name)) install_name = install_name.replace( '$(DYLIB_INSTALL_NAME_BASE:standardizepath)', self._StandardizePath(self.GetInstallNameBase())) if self._IsBundle(): # These are only valid for bundles, hence the |if|. install_name = install_name.replace( '$(WRAPPER_NAME)', self.GetWrapperName()) install_name = install_name.replace( '$(PRODUCT_NAME)', self.GetProductName()) else: assert '$(WRAPPER_NAME)' not in install_name assert '$(PRODUCT_NAME)' not in install_name install_name = install_name.replace( '$(EXECUTABLE_PATH)', self.GetExecutablePath()) return install_name def _MapLinkerFlagFilename(self, ldflag, gyp_to_build_path): """Checks if ldflag contains a filename and if so remaps it from gyp-directory-relative to build-directory-relative.""" # This list is expanded on demand. # They get matched as: # -exported_symbols_list file # -Wl,exported_symbols_list file # -Wl,exported_symbols_list,file LINKER_FILE = r'(\S+)' WORD = r'\S+' linker_flags = [ ['-exported_symbols_list', LINKER_FILE], # Needed for NaCl. ['-unexported_symbols_list', LINKER_FILE], ['-reexported_symbols_list', LINKER_FILE], ['-sectcreate', WORD, WORD, LINKER_FILE], # Needed for remoting. ] for flag_pattern in linker_flags: regex = re.compile('(?:-Wl,)?' + '[ ,]'.join(flag_pattern)) m = regex.match(ldflag) if m: ldflag = ldflag[:m.start(1)] + gyp_to_build_path(m.group(1)) + \ ldflag[m.end(1):] # Required for ffmpeg (no idea why they don't use LIBRARY_SEARCH_PATHS, # TODO(thakis): Update ffmpeg.gyp): if ldflag.startswith('-L'): ldflag = '-L' + gyp_to_build_path(ldflag[len('-L'):]) return ldflag def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): """Returns flags that need to be passed to the linker. Args: configname: The name of the configuration to get ld flags for. product_dir: The directory where products such static and dynamic libraries are placed. This is added to the library search path. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build direcotry. """ self.configname = configname ldflags = [] # The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS # can contain entries that depend on this. Explicitly absolutify these. for ldflag in self._Settings().get('OTHER_LDFLAGS', []): ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path)) if self._Test('DEAD_CODE_STRIPPING', 'YES', default='NO'): ldflags.append('-Wl,-dead_strip') if self._Test('PREBINDING', 'YES', default='NO'): ldflags.append('-Wl,-prebind') self._Appendf( ldflags, 'DYLIB_COMPATIBILITY_VERSION', '-compatibility_version %s') self._Appendf( ldflags, 'DYLIB_CURRENT_VERSION', '-current_version %s') self._AppendPlatformVersionMinFlags(ldflags) if 'SDKROOT' in self._Settings() and self._SdkPath(): ldflags.append('-isysroot ' + self._SdkPath()) for library_path in self._Settings().get('LIBRARY_SEARCH_PATHS', []): ldflags.append('-L' + gyp_to_build_path(library_path)) if 'ORDER_FILE' in self._Settings(): ldflags.append('-Wl,-order_file ' + '-Wl,' + gyp_to_build_path( self._Settings()['ORDER_FILE'])) if arch is not None: archs = [arch] else: assert self.configname archs = self.GetActiveArchs(self.configname) if len(archs) != 1: # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented('ARCHS') archs = ['i386'] ldflags.append('-arch ' + archs[0]) # Xcode adds the product directory by default. ldflags.append('-L' + product_dir) install_name = self.GetInstallName() if install_name and self.spec['type'] != 'loadable_module': ldflags.append('-install_name ' + install_name.replace(' ', r'\ ')) for rpath in self._Settings().get('LD_RUNPATH_SEARCH_PATHS', []): ldflags.append('-Wl,-rpath,' + rpath) sdk_root = self._SdkPath() if not sdk_root: sdk_root = '' config = self.spec['configurations'][self.configname] framework_dirs = config.get('mac_framework_dirs', []) for directory in framework_dirs: ldflags.append('-F' + directory.replace('$(SDKROOT)', sdk_root)) is_extension = self._IsIosAppExtension() or self._IsIosWatchKitExtension() if sdk_root and is_extension: # Adds the link flags for extensions. These flags are common for all # extensions and provide loader and main function. # These flags reflect the compilation options used by xcode to compile # extensions. ldflags.append('-lpkstart') ldflags.append(sdk_root + '/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit') ldflags.append('-fapplication-extension') ldflags.append('-Xlinker -rpath ' '-Xlinker @executable_path/../../Frameworks') self._Appendf(ldflags, 'CLANG_CXX_LIBRARY', '-stdlib=%s') self.configname = None return ldflags def GetLibtoolflags(self, configname): """Returns flags that need to be passed to the static linker. Args: configname: The name of the configuration to get ld flags for. """ self.configname = configname libtoolflags = [] for libtoolflag in self._Settings().get('OTHER_LDFLAGS', []): libtoolflags.append(libtoolflag) # TODO(thakis): ARCHS? self.configname = None return libtoolflags def GetPerTargetSettings(self): """Gets a list of all the per-target settings. This will only fetch keys whose values are the same across all configurations.""" first_pass = True result = {} for configname in sorted(self.xcode_settings.keys()): if first_pass: result = dict(self.xcode_settings[configname]) first_pass = False else: for key, value in self.xcode_settings[configname].iteritems(): if key not in result: continue elif result[key] != value: del result[key] return result def GetPerConfigSetting(self, setting, configname, default=None): if configname in self.xcode_settings: return self.xcode_settings[configname].get(setting, default) else: return self.GetPerTargetSetting(setting, default) def GetPerTargetSetting(self, setting, default=None): """Tries to get xcode_settings.setting from spec. Assumes that the setting has the same value in all configurations and throws otherwise.""" is_first_pass = True result = None for configname in sorted(self.xcode_settings.keys()): if is_first_pass: result = self.xcode_settings[configname].get(setting, None) is_first_pass = False else: assert result == self.xcode_settings[configname].get(setting, None), ( "Expected per-target setting for '%s', got per-config setting " "(target %s)" % (setting, self.spec['target_name'])) if result is None: return default return result def _GetStripPostbuilds(self, configname, output_binary, quiet): """Returns a list of shell commands that contain the shell commands neccessary to strip this target's binary. These should be run as postbuilds before the actual postbuilds run.""" self.configname = configname result = [] if (self._Test('DEPLOYMENT_POSTPROCESSING', 'YES', default='NO') and self._Test('STRIP_INSTALLED_PRODUCT', 'YES', default='NO')): default_strip_style = 'debugging' if self.spec['type'] == 'loadable_module' and self._IsBundle(): default_strip_style = 'non-global' elif self.spec['type'] == 'executable': default_strip_style = 'all' strip_style = self._Settings().get('STRIP_STYLE', default_strip_style) strip_flags = { 'all': '', 'non-global': '-x', 'debugging': '-S', }[strip_style] explicit_strip_flags = self._Settings().get('STRIPFLAGS', '') if explicit_strip_flags: strip_flags += ' ' + _NormalizeEnvVarReferences(explicit_strip_flags) if not quiet: result.append('echo STRIP\\(%s\\)' % self.spec['target_name']) result.append('strip %s %s' % (strip_flags, output_binary)) self.configname = None return result def _GetDebugInfoPostbuilds(self, configname, output, output_binary, quiet): """Returns a list of shell commands that contain the shell commands neccessary to massage this target's debug information. These should be run as postbuilds before the actual postbuilds run.""" self.configname = configname # For static libraries, no dSYMs are created. result = [] if (self._Test('GCC_GENERATE_DEBUGGING_SYMBOLS', 'YES', default='YES') and self._Test( 'DEBUG_INFORMATION_FORMAT', 'dwarf-with-dsym', default='dwarf') and self.spec['type'] != 'static_library'): if not quiet: result.append('echo DSYMUTIL\\(%s\\)' % self.spec['target_name']) result.append('dsymutil %s -o %s' % (output_binary, output + '.dSYM')) self.configname = None return result def _GetTargetPostbuilds(self, configname, output, output_binary, quiet=False): """Returns a list of shell commands that contain the shell commands to run as postbuilds for this target, before the actual postbuilds.""" # dSYMs need to build before stripping happens. return ( self._GetDebugInfoPostbuilds(configname, output, output_binary, quiet) + self._GetStripPostbuilds(configname, output_binary, quiet)) def _GetIOSPostbuilds(self, configname, output_binary): """Return a shell command to codesign the iOS output binary so it can be deployed to a device. This should be run as the very last step of the build.""" if not (self.isIOS and self.spec['type'] == 'executable'): return [] settings = self.xcode_settings[configname] key = self._GetIOSCodeSignIdentityKey(settings) if not key: return [] # Warn for any unimplemented signing xcode keys. unimpl = ['OTHER_CODE_SIGN_FLAGS'] unimpl = set(unimpl) & set(self.xcode_settings[configname].keys()) if unimpl: print 'Warning: Some codesign keys not implemented, ignoring: %s' % ( ', '.join(sorted(unimpl))) return ['%s code-sign-bundle "%s" "%s" "%s" "%s"' % ( os.path.join('${TARGET_BUILD_DIR}', 'gyp-mac-tool'), key, settings.get('CODE_SIGN_RESOURCE_RULES_PATH', ''), settings.get('CODE_SIGN_ENTITLEMENTS', ''), settings.get('PROVISIONING_PROFILE', '')) ] def _GetIOSCodeSignIdentityKey(self, settings): identity = settings.get('CODE_SIGN_IDENTITY') if not identity: return None if identity not in XcodeSettings._codesigning_key_cache: output = subprocess.check_output( ['security', 'find-identity', '-p', 'codesigning', '-v']) for line in output.splitlines(): if identity in line: fingerprint = line.split()[1] cache = XcodeSettings._codesigning_key_cache assert identity not in cache or fingerprint == cache[identity], ( "Multiple codesigning fingerprints for identity: %s" % identity) XcodeSettings._codesigning_key_cache[identity] = fingerprint return XcodeSettings._codesigning_key_cache.get(identity, '') def AddImplicitPostbuilds(self, configname, output, output_binary, postbuilds=[], quiet=False): """Returns a list of shell commands that should run before and after |postbuilds|.""" assert output_binary is not None pre = self._GetTargetPostbuilds(configname, output, output_binary, quiet) post = self._GetIOSPostbuilds(configname, output_binary) return pre + postbuilds + post def _AdjustLibrary(self, library, config_name=None): if library.endswith('.framework'): l = '-framework ' + os.path.splitext(os.path.basename(library))[0] else: m = self.library_re.match(library) if m: l = '-l' + m.group(1) else: l = library sdk_root = self._SdkPath(config_name) if not sdk_root: sdk_root = '' return l.replace('$(SDKROOT)', sdk_root) def AdjustLibraries(self, libraries, config_name=None): """Transforms entries like 'Cocoa.framework' in libraries into entries like '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. """ libraries = [self._AdjustLibrary(library, config_name) for library in libraries] return libraries def _BuildMachineOSBuild(self): return GetStdout(['sw_vers', '-buildVersion']) def _XcodeIOSDeviceFamily(self, configname): family = self.xcode_settings[configname].get('TARGETED_DEVICE_FAMILY', '1') return [int(x) for x in family.split(',')] def GetExtraPlistItems(self, configname=None): """Returns a dictionary with extra items to insert into Info.plist.""" if configname not in XcodeSettings._plist_cache: cache = {} cache['BuildMachineOSBuild'] = self._BuildMachineOSBuild() xcode, xcode_build = XcodeVersion() cache['DTXcode'] = xcode cache['DTXcodeBuild'] = xcode_build sdk_root = self._SdkRoot(configname) if not sdk_root: sdk_root = self._DefaultSdkRoot() cache['DTSDKName'] = sdk_root if xcode >= '0430': cache['DTSDKBuild'] = self._GetSdkVersionInfoItem( sdk_root, 'ProductBuildVersion') else: cache['DTSDKBuild'] = cache['BuildMachineOSBuild'] if self.isIOS: cache['DTPlatformName'] = cache['DTSDKName'] if configname.endswith("iphoneos"): cache['DTPlatformVersion'] = self._GetSdkVersionInfoItem( sdk_root, 'ProductVersion') cache['CFBundleSupportedPlatforms'] = ['iPhoneOS'] else: cache['CFBundleSupportedPlatforms'] = ['iPhoneSimulator'] XcodeSettings._plist_cache[configname] = cache # Include extra plist items that are per-target, not per global # XcodeSettings. items = dict(XcodeSettings._plist_cache[configname]) if self.isIOS: items['UIDeviceFamily'] = self._XcodeIOSDeviceFamily(configname) return items def _DefaultSdkRoot(self): """Returns the default SDKROOT to use. Prior to version 5.0.0, if SDKROOT was not explicitly set in the Xcode project, then the environment variable was empty. Starting with this version, Xcode uses the name of the newest SDK installed. """ xcode_version, xcode_build = XcodeVersion() if xcode_version < '0500': return '' default_sdk_path = self._XcodeSdkPath('') default_sdk_root = XcodeSettings._sdk_root_cache.get(default_sdk_path) if default_sdk_root: return default_sdk_root try: all_sdks = GetStdout(['xcodebuild', '-showsdks']) except: # If xcodebuild fails, there will be no valid SDKs return '' for line in all_sdks.splitlines(): items = line.split() if len(items) >= 3 and items[-2] == '-sdk': sdk_root = items[-1] sdk_path = self._XcodeSdkPath(sdk_root) if sdk_path == default_sdk_path: return sdk_root return '' class MacPrefixHeader(object): """A class that helps with emulating Xcode's GCC_PREFIX_HEADER feature. This feature consists of several pieces: * If GCC_PREFIX_HEADER is present, all compilations in that project get an additional |-include path_to_prefix_header| cflag. * If GCC_PRECOMPILE_PREFIX_HEADER is present too, then the prefix header is instead compiled, and all other compilations in the project get an additional |-include path_to_compiled_header| instead. + Compiled prefix headers have the extension gch. There is one gch file for every language used in the project (c, cc, m, mm), since gch files for different languages aren't compatible. + gch files themselves are built with the target's normal cflags, but they obviously don't get the |-include| flag. Instead, they need a -x flag that describes their language. + All o files in the target need to depend on the gch file, to make sure it's built before any o file is built. This class helps with some of these tasks, but it needs help from the build system for writing dependencies to the gch files, for writing build commands for the gch files, and for figuring out the location of the gch files. """ def __init__(self, xcode_settings, gyp_path_to_build_path, gyp_path_to_build_output): """If xcode_settings is None, all methods on this class are no-ops. Args: gyp_path_to_build_path: A function that takes a gyp-relative path, and returns a path relative to the build directory. gyp_path_to_build_output: A function that takes a gyp-relative path and a language code ('c', 'cc', 'm', or 'mm'), and that returns a path to where the output of precompiling that path for that language should be placed (without the trailing '.gch'). """ # This doesn't support per-configuration prefix headers. Good enough # for now. self.header = None self.compile_headers = False if xcode_settings: self.header = xcode_settings.GetPerTargetSetting('GCC_PREFIX_HEADER') self.compile_headers = xcode_settings.GetPerTargetSetting( 'GCC_PRECOMPILE_PREFIX_HEADER', default='NO') != 'NO' self.compiled_headers = {} if self.header: if self.compile_headers: for lang in ['c', 'cc', 'm', 'mm']: self.compiled_headers[lang] = gyp_path_to_build_output( self.header, lang) self.header = gyp_path_to_build_path(self.header) def _CompiledHeader(self, lang, arch): assert self.compile_headers h = self.compiled_headers[lang] if arch: h += '.' + arch return h def GetInclude(self, lang, arch=None): """Gets the cflags to include the prefix header for language |lang|.""" if self.compile_headers and lang in self.compiled_headers: return '-include %s' % self._CompiledHeader(lang, arch) elif self.header: return '-include %s' % self.header else: return '' def _Gch(self, lang, arch): """Returns the actual file name of the prefix header for language |lang|.""" assert self.compile_headers return self._CompiledHeader(lang, arch) + '.gch' def GetObjDependencies(self, sources, objs, arch=None): """Given a list of source files and the corresponding object files, returns a list of (source, object, gch) tuples, where |gch| is the build-directory relative path to the gch file each object file depends on. |compilable[i]| has to be the source file belonging to |objs[i]|.""" if not self.header or not self.compile_headers: return [] result = [] for source, obj in zip(sources, objs): ext = os.path.splitext(source)[1] lang = { '.c': 'c', '.cpp': 'cc', '.cc': 'cc', '.cxx': 'cc', '.m': 'm', '.mm': 'mm', }.get(ext, None) if lang: result.append((source, obj, self._Gch(lang, arch))) return result def GetPchBuildCommands(self, arch=None): """Returns [(path_to_gch, language_flag, language, header)]. |path_to_gch| and |header| are relative to the build directory. """ if not self.header or not self.compile_headers: return [] return [ (self._Gch('c', arch), '-x c-header', 'c', self.header), (self._Gch('cc', arch), '-x c++-header', 'cc', self.header), (self._Gch('m', arch), '-x objective-c-header', 'm', self.header), (self._Gch('mm', arch), '-x objective-c++-header', 'mm', self.header), ] def XcodeVersion(): """Returns a tuple of version and build version of installed Xcode.""" # `xcodebuild -version` output looks like # Xcode 4.6.3 # Build version 4H1503 # or like # Xcode 3.2.6 # Component versions: DevToolsCore-1809.0; DevToolsSupport-1806.0 # BuildVersion: 10M2518 # Convert that to '0463', '4H1503'. global XCODE_VERSION_CACHE if XCODE_VERSION_CACHE: return XCODE_VERSION_CACHE try: version_list = GetStdout(['xcodebuild', '-version']).splitlines() # In some circumstances xcodebuild exits 0 but doesn't return # the right results; for example, a user on 10.7 or 10.8 with # a bogus path set via xcode-select # In that case this may be a CLT-only install so fall back to # checking that version. if len(version_list) < 2: raise GypError("xcodebuild returned unexpected results") except: version = CLTVersion() if version: version = re.match(r'(\d\.\d\.?\d*)', version).groups()[0] else: raise GypError("No Xcode or CLT version detected!") # The CLT has no build information, so we return an empty string. version_list = [version, ''] version = version_list[0] build = version_list[-1] # Be careful to convert "4.2" to "0420": version = version.split()[-1].replace('.', '') version = (version + '0' * (3 - len(version))).zfill(4) if build: build = build.split()[-1] XCODE_VERSION_CACHE = (version, build) return XCODE_VERSION_CACHE # This function ported from the logic in Homebrew's CLT version check def CLTVersion(): """Returns the version of command-line tools from pkgutil.""" # pkgutil output looks like # package-id: com.apple.pkg.CLTools_Executables # version: 5.0.1.0.1.1382131676 # volume: / # location: / # install-time: 1382544035 # groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo" FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI" MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables" regex = re.compile('version: (?P<version>.+)') for key in [MAVERICKS_PKG_ID, STANDALONE_PKG_ID, FROM_XCODE_PKG_ID]: try: output = GetStdout(['/usr/sbin/pkgutil', '--pkg-info', key]) return re.search(regex, output).groupdict()['version'] except: continue def GetStdout(cmdlist): """Returns the content of standard output returned by invoking |cmdlist|. Raises |GypError| if the command return with a non-zero return code.""" job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) out = job.communicate()[0] if job.returncode != 0: sys.stderr.write(out + '\n') raise GypError('Error %d running %s' % (job.returncode, cmdlist[0])) return out.rstrip('\n') def MergeGlobalXcodeSettingsToSpec(global_dict, spec): """Merges the global xcode_settings dictionary into each configuration of the target represented by spec. For keys that are both in the global and the local xcode_settings dict, the local key gets precendence. """ # The xcode generator special-cases global xcode_settings and does something # that amounts to merging in the global xcode_settings into each local # xcode_settings dict. global_xcode_settings = global_dict.get('xcode_settings', {}) for config in spec['configurations'].values(): if 'xcode_settings' in config: new_settings = global_xcode_settings.copy() new_settings.update(config['xcode_settings']) config['xcode_settings'] = new_settings def IsMacBundle(flavor, spec): """Returns if |spec| should be treated as a bundle. Bundles are directories with a certain subdirectory structure, instead of just a single file. Bundle rules do not produce a binary but also package resources into that directory.""" is_mac_bundle = (int(spec.get('mac_bundle', 0)) != 0 and flavor == 'mac') if is_mac_bundle: assert spec['type'] != 'none', ( 'mac_bundle targets cannot have type none (target "%s")' % spec['target_name']) return is_mac_bundle def GetMacBundleResources(product_dir, xcode_settings, resources): """Yields (output, resource) pairs for every resource in |resources|. Only call this for mac bundle targets. Args: product_dir: Path to the directory containing the output bundle, relative to the build directory. xcode_settings: The XcodeSettings of the current target. resources: A list of bundle resources, relative to the build directory. """ dest = os.path.join(product_dir, xcode_settings.GetBundleResourceFolder()) for res in resources: output = dest # The make generator doesn't support it, so forbid it everywhere # to keep the generators more interchangable. assert ' ' not in res, ( "Spaces in resource filenames not supported (%s)" % res) # Split into (path,file). res_parts = os.path.split(res) # Now split the path into (prefix,maybe.lproj). lproj_parts = os.path.split(res_parts[0]) # If the resource lives in a .lproj bundle, add that to the destination. if lproj_parts[1].endswith('.lproj'): output = os.path.join(output, lproj_parts[1]) output = os.path.join(output, res_parts[1]) # Compiled XIB files are referred to by .nib. if output.endswith('.xib'): output = os.path.splitext(output)[0] + '.nib' # Compiled storyboard files are referred to by .storyboardc. if output.endswith('.storyboard'): output = os.path.splitext(output)[0] + '.storyboardc' yield output, res def GetMacInfoPlist(product_dir, xcode_settings, gyp_path_to_build_path): """Returns (info_plist, dest_plist, defines, extra_env), where: * |info_plist| is the source plist path, relative to the build directory, * |dest_plist| is the destination plist path, relative to the build directory, * |defines| is a list of preprocessor defines (empty if the plist shouldn't be preprocessed, * |extra_env| is a dict of env variables that should be exported when invoking |mac_tool copy-info-plist|. Only call this for mac bundle targets. Args: product_dir: Path to the directory containing the output bundle, relative to the build directory. xcode_settings: The XcodeSettings of the current target. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build direcotry. """ info_plist = xcode_settings.GetPerTargetSetting('INFOPLIST_FILE') if not info_plist: return None, None, [], {} # The make generator doesn't support it, so forbid it everywhere # to keep the generators more interchangable. assert ' ' not in info_plist, ( "Spaces in Info.plist filenames not supported (%s)" % info_plist) info_plist = gyp_path_to_build_path(info_plist) # If explicitly set to preprocess the plist, invoke the C preprocessor and # specify any defines as -D flags. if xcode_settings.GetPerTargetSetting( 'INFOPLIST_PREPROCESS', default='NO') == 'YES': # Create an intermediate file based on the path. defines = shlex.split(xcode_settings.GetPerTargetSetting( 'INFOPLIST_PREPROCESSOR_DEFINITIONS', default='')) else: defines = [] dest_plist = os.path.join(product_dir, xcode_settings.GetBundlePlistPath()) extra_env = xcode_settings.GetPerTargetSettings() return info_plist, dest_plist, defines, extra_env def _GetXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None): """Return the environment variables that Xcode would set. See http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html#//apple_ref/doc/uid/TP40003931-CH3-SW153 for a full list. Args: xcode_settings: An XcodeSettings object. If this is None, this function returns an empty dict. built_products_dir: Absolute path to the built products dir. srcroot: Absolute path to the source root. configuration: The build configuration name. additional_settings: An optional dict with more values to add to the result. """ if not xcode_settings: return {} # This function is considered a friend of XcodeSettings, so let it reach into # its implementation details. spec = xcode_settings.spec # These are filled in on a as-needed basis. env = { 'BUILT_PRODUCTS_DIR' : built_products_dir, 'CONFIGURATION' : configuration, 'PRODUCT_NAME' : xcode_settings.GetProductName(), # See /Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Specifications/MacOSX\ Product\ Types.xcspec for FULL_PRODUCT_NAME 'SRCROOT' : srcroot, 'SOURCE_ROOT': '${SRCROOT}', # This is not true for static libraries, but currently the env is only # written for bundles: 'TARGET_BUILD_DIR' : built_products_dir, 'TEMP_DIR' : '${TMPDIR}', } if xcode_settings.GetPerConfigSetting('SDKROOT', configuration): env['SDKROOT'] = xcode_settings._SdkPath(configuration) else: env['SDKROOT'] = '' if spec['type'] in ( 'executable', 'static_library', 'shared_library', 'loadable_module'): env['EXECUTABLE_NAME'] = xcode_settings.GetExecutableName() env['EXECUTABLE_PATH'] = xcode_settings.GetExecutablePath() env['FULL_PRODUCT_NAME'] = xcode_settings.GetFullProductName() mach_o_type = xcode_settings.GetMachOType() if mach_o_type: env['MACH_O_TYPE'] = mach_o_type env['PRODUCT_TYPE'] = xcode_settings.GetProductType() if xcode_settings._IsBundle(): env['CONTENTS_FOLDER_PATH'] = \ xcode_settings.GetBundleContentsFolderPath() env['UNLOCALIZED_RESOURCES_FOLDER_PATH'] = \ xcode_settings.GetBundleResourceFolder() env['INFOPLIST_PATH'] = xcode_settings.GetBundlePlistPath() env['WRAPPER_NAME'] = xcode_settings.GetWrapperName() install_name = xcode_settings.GetInstallName() if install_name: env['LD_DYLIB_INSTALL_NAME'] = install_name install_name_base = xcode_settings.GetInstallNameBase() if install_name_base: env['DYLIB_INSTALL_NAME_BASE'] = install_name_base if XcodeVersion() >= '0500' and not env.get('SDKROOT'): sdk_root = xcode_settings._SdkRoot(configuration) if not sdk_root: sdk_root = xcode_settings._XcodeSdkPath('') if sdk_root is None: sdk_root = '' env['SDKROOT'] = sdk_root if not additional_settings: additional_settings = {} else: # Flatten lists to strings. for k in additional_settings: if not isinstance(additional_settings[k], str): additional_settings[k] = ' '.join(additional_settings[k]) additional_settings.update(env) for k in additional_settings: additional_settings[k] = _NormalizeEnvVarReferences(additional_settings[k]) return additional_settings def _NormalizeEnvVarReferences(str): """Takes a string containing variable references in the form ${FOO}, $(FOO), or $FOO, and returns a string with all variable references in the form ${FOO}. """ # $FOO -> ${FOO} str = re.sub(r'\$([a-zA-Z_][a-zA-Z0-9_]*)', r'${\1}', str) # $(FOO) -> ${FOO} matches = re.findall(r'(\$\(([a-zA-Z0-9\-_]+)\))', str) for match in matches: to_replace, variable = match assert '$(' not in match, '$($(FOO)) variables not supported: ' + match str = str.replace(to_replace, '${' + variable + '}') return str def ExpandEnvVars(string, expansions): """Expands ${VARIABLES}, $(VARIABLES), and $VARIABLES in string per the expansions list. If the variable expands to something that references another variable, this variable is expanded as well if it's in env -- until no variables present in env are left.""" for k, v in reversed(expansions): string = string.replace('${' + k + '}', v) string = string.replace('$(' + k + ')', v) string = string.replace('$' + k, v) return string def _TopologicallySortedEnvVarKeys(env): """Takes a dict |env| whose values are strings that can refer to other keys, for example env['foo'] = '$(bar) and $(baz)'. Returns a list L of all keys of env such that key2 is after key1 in L if env[key2] refers to env[key1]. Throws an Exception in case of dependency cycles. """ # Since environment variables can refer to other variables, the evaluation # order is important. Below is the logic to compute the dependency graph # and sort it. regex = re.compile(r'\$\{([a-zA-Z0-9\-_]+)\}') def GetEdges(node): # Use a definition of edges such that user_of_variable -> used_varible. # This happens to be easier in this case, since a variable's # definition contains all variables it references in a single string. # We can then reverse the result of the topological sort at the end. # Since: reverse(topsort(DAG)) = topsort(reverse_edges(DAG)) matches = set([v for v in regex.findall(env[node]) if v in env]) for dependee in matches: assert '${' not in dependee, 'Nested variables not supported: ' + dependee return matches try: # Topologically sort, and then reverse, because we used an edge definition # that's inverted from the expected result of this function (see comment # above). order = gyp.common.TopologicallySorted(env.keys(), GetEdges) order.reverse() return order except gyp.common.CycleError, e: raise GypError( 'Xcode environment variables are cyclically dependent: ' + str(e.nodes)) def GetSortedXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None): env = _GetXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration, additional_settings) return [(key, env[key]) for key in _TopologicallySortedEnvVarKeys(env)] def GetSpecPostbuildCommands(spec, quiet=False): """Returns the list of postbuilds explicitly defined on |spec|, in a form executable by a shell.""" postbuilds = [] for postbuild in spec.get('postbuilds', []): if not quiet: postbuilds.append('echo POSTBUILD\\(%s\\) %s' % ( spec['target_name'], postbuild['postbuild_name'])) postbuilds.append(gyp.common.EncodePOSIXShellList(postbuild['action'])) return postbuilds def _HasIOSTarget(targets): """Returns true if any target contains the iOS specific key IPHONEOS_DEPLOYMENT_TARGET.""" for target_dict in targets.values(): for config in target_dict['configurations'].values(): if config.get('xcode_settings', {}).get('IPHONEOS_DEPLOYMENT_TARGET'): return True return False def _AddIOSDeviceConfigurations(targets): """Clone all targets and append -iphoneos to the name. Configure these targets to build for iOS devices and use correct architectures for those builds.""" for target_dict in targets.itervalues(): toolset = target_dict['toolset'] configs = target_dict['configurations'] for config_name, config_dict in dict(configs).iteritems(): iphoneos_config_dict = copy.deepcopy(config_dict) configs[config_name + '-iphoneos'] = iphoneos_config_dict configs[config_name + '-iphonesimulator'] = config_dict if toolset == 'target': iphoneos_config_dict['xcode_settings']['SDKROOT'] = 'iphoneos' return targets def CloneConfigurationForDeviceAndEmulator(target_dicts): """If |target_dicts| contains any iOS targets, automatically create -iphoneos targets for iOS device builds.""" if _HasIOSTarget(target_dicts): return _AddIOSDeviceConfigurations(target_dicts) return target_dicts
artistic-2.0
wtorcasoGB/flask
flask/views.py
149
5644
# -*- coding: utf-8 -*- """ flask.views ~~~~~~~~~~~ This module provides class-based views inspired by the ones in Django. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from .globals import request from ._compat import with_metaclass http_method_funcs = frozenset(['get', 'post', 'head', 'options', 'delete', 'put', 'trace', 'patch']) class View(object): """Alternative way to use view functions. A subclass has to implement :meth:`dispatch_request` which is called with the view arguments from the URL routing system. If :attr:`methods` is provided the methods do not have to be passed to the :meth:`~flask.Flask.add_url_rule` method explicitly:: class MyView(View): methods = ['GET'] def dispatch_request(self, name): return 'Hello %s!' % name app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview')) When you want to decorate a pluggable view you will have to either do that when the view function is created (by wrapping the return value of :meth:`as_view`) or you can use the :attr:`decorators` attribute:: class SecretView(View): methods = ['GET'] decorators = [superuser_required] def dispatch_request(self): ... The decorators stored in the decorators list are applied one after another when the view function is created. Note that you can *not* use the class based decorators since those would decorate the view class and not the generated view function! """ #: A for which methods this pluggable view can handle. methods = None #: The canonical way to decorate class-based views is to decorate the #: return value of as_view(). However since this moves parts of the #: logic from the class declaration to the place where it's hooked #: into the routing system. #: #: You can place one or more decorators in this list and whenever the #: view function is created the result is automatically decorated. #: #: .. versionadded:: 0.8 decorators = () def dispatch_request(self): """Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule. """ raise NotImplementedError() @classmethod def as_view(cls, name, *class_args, **class_kwargs): """Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the :class:`View` on each request and call the :meth:`dispatch_request` method on it. The arguments passed to :meth:`as_view` are forwarded to the constructor of the class. """ def view(*args, **kwargs): self = view.view_class(*class_args, **class_kwargs) return self.dispatch_request(*args, **kwargs) if cls.decorators: view.__name__ = name view.__module__ = cls.__module__ for decorator in cls.decorators: view = decorator(view) # We attach the view class to the view function for two reasons: # first of all it allows us to easily figure out what class-based # view this thing came from, secondly it's also used for instantiating # the view class so you can actually replace it with something else # for testing purposes and debugging. view.view_class = cls view.__name__ = name view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.methods = cls.methods return view class MethodViewType(type): def __new__(cls, name, bases, d): rv = type.__new__(cls, name, bases, d) if 'methods' not in d: methods = set(rv.methods or []) for key in d: if key in http_method_funcs: methods.add(key.upper()) # If we have no method at all in there we don't want to # add a method list. (This is for instance the case for # the base class or another subclass of a base method view # that does not introduce new methods). if methods: rv.methods = sorted(methods) return rv class MethodView(with_metaclass(MethodViewType, View)): """Like a regular class-based view but that dispatches requests to particular methods. For instance if you implement a method called :meth:`get` it means you will response to ``'GET'`` requests and the :meth:`dispatch_request` implementation will automatically forward your request to that. Also :attr:`options` is set for you automatically:: class CounterAPI(MethodView): def get(self): return session.get('counter', 0) def post(self): session['counter'] = session.get('counter', 0) + 1 return 'OK' app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter')) """ def dispatch_request(self, *args, **kwargs): meth = getattr(self, request.method.lower(), None) # If the request method is HEAD and we don't have a handler for it # retry with GET. if meth is None and request.method == 'HEAD': meth = getattr(self, 'get', None) assert meth is not None, 'Unimplemented method %r' % request.method return meth(*args, **kwargs)
bsd-3-clause
justingrayston/jaikuengine
common/test/user.py
30
2821
# Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime from appengine_django.sessions.models import Session from django.conf import settings from google.appengine.ext import db from common import api from common.test.base import ViewTestCase from common.user import (generate_user_auth_token, lookup_user_auth_token, purge_expired_user_auth_token_keys) class SessionTest(ViewTestCase): users = ('popular@example.com', 'girlfriend@example.com') def test_sessions_should_be_cached(self): for user in self.users: token = generate_user_auth_token(user, 'password hash') auth_token = lookup_user_auth_token(user, token) self.assertEqual('password hash', auth_token) def test_look_up_nonexistent_sessions(self): for user in self.users: token = generate_user_auth_token(user, 'password hash') auth_token = lookup_user_auth_token('missing@example.com', 'password hash') self.assertEqual(None, auth_token) auth_token = lookup_user_auth_token(user, 'some other password hash') self.assertEqual(None, auth_token) def test_purge_expired_tokens(self): """ Generate tokens with current time as expiration date/time. That is, tokens are expired as soon as they are generated. """ for user in self.users: token = generate_user_auth_token(user, 'password hash', timeout=0) auth_token = lookup_user_auth_token(user, token) self.assertEqual(None, auth_token) # As expired tokens are purged from the DB just before # they are generated, the above should leave us with one # expired token in the DB query = Session.gql("WHERE expire_date <= :1", api.utcnow()) expired_tokens = query.count() self.assertEqual(1, expired_tokens) # Generate another token to trigger cache purging which # should leave us with no expired sessions in the DB (as # this token is generated with a future expiration date.) token = generate_user_auth_token('fake user', 'password hash') query = Session.gql("WHERE expire_date <= :1", api.utcnow()) expired_tokens = query.count() self.assertEqual(0, expired_tokens)
apache-2.0
ifcharming/voltdb2.1
tools/vis.py
1
5697
#!/usr/bin/env python # This is a visualizer which pulls TPC-C benchmark results from the MySQL # databases and visualizes them. Four graphs will be generated, latency graph on # sinigle node and multiple nodes, and throughput graph on single node and # multiple nodes. # # Run it without any arguments to see what arguments are needed. import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + os.sep + 'tests/scripts/') import time import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.ticker as ticker from voltdbclient import * STATS_SERVER = 'volt2' def COLORS(k): return (((k ** 3) % 255) / 255.0, ((k * 100) % 255) / 255.0, ((k * k) % 255) / 255.0) MARKERS = ['+', '*', '<', '>', '^', '_', 'D', 'H', 'd', 'h', 'o', 'p'] def get_stats(hostname, port, days): """Get statistics of all runs Example return value: { u'VoltKV': [ { 'lat95': 21, 'lat99': 35, 'nodes': 1, 'throughput': 104805, 'date': datetime object}], u'Voter': [ { 'lat95': 20, 'lat99': 47, 'nodes': 1, 'throughput': 66287, 'date': datetime object}]} """ conn = FastSerializer(hostname, port) proc = VoltProcedure(conn, 'BestOfPeriod', [FastSerializer.VOLTTYPE_SMALLINT]) resp = proc.call([days]) conn.close() # keyed on app name, value is a list of runs sorted chronologically stats = dict() run_stat_keys = ['nodes', 'date', 'tps', 'lat95', 'lat99'] for row in resp.tables[0].tuples: app_stats = [] if row[0] not in stats: stats[row[0]] = app_stats else: app_stats = stats[row[0]] run_stats = dict(zip(run_stat_keys, row[1:])) app_stats.append(run_stats) # sort each one for app_stats in stats.itervalues(): app_stats.sort(key=lambda x: x['date']) return stats class Plot: DPI = 100.0 def __init__(self, title, xlabel, ylabel, filename, w, h): self.filename = filename self.legends = {} w = w == None and 800 or w h = h == None and 300 or h fig = plt.figure(figsize=(w / self.DPI, h / self.DPI), dpi=self.DPI) self.ax = fig.add_subplot(111) self.ax.set_title(title) plt.xticks(fontsize=10) plt.yticks(fontsize=10) plt.ylabel(ylabel, fontsize=8) plt.xlabel(xlabel, fontsize=8) fig.autofmt_xdate() def plot(self, x, y, color, marker_shape, legend): self.ax.plot(x, y, linestyle="-", label=str(legend), marker=marker_shape, markerfacecolor=color, markersize=4) def close(self): formatter = matplotlib.dates.DateFormatter("%b %d") self.ax.xaxis.set_major_formatter(formatter) plt.legend(prop={'size': 10}, loc=0) plt.savefig(self.filename, format="png", transparent=False, bbox_inches="tight", pad_inches=0.2) def plot(title, xlabel, ylabel, filename, nodes, width, height, data, data_type): plot_data = dict() for app, runs in data.iteritems(): for v in runs: if v['nodes'] != nodes: continue if app not in plot_data: plot_data[app] = {'time': [], data_type: []} datenum = matplotlib.dates.date2num(v['date']) plot_data[app]['time'].append(datenum) if data_type == 'tps': value = v['tps']/v['nodes'] else: value = v[data_type] plot_data[app][data_type].append(value) if len(plot_data) == 0: return i = 0 pl = Plot(title, xlabel, ylabel, filename, width, height) sorted_data = sorted(plot_data.items(), key=lambda x: x[0]) for k, v in sorted_data: pl.plot(v['time'], v[data_type], COLORS(i), MARKERS[i], k) i += 3 pl.close() def usage(): print "Usage:" print "\t", sys.argv[0], "output_dir filename_base" \ " [width] [height]" print print "\t", "width in pixels" print "\t", "height in pixels" def main(): if len(sys.argv) < 3: usage() exit(-1) if not os.path.exists(sys.argv[1]): print sys.argv[2], "does not exist" exit(-1) path = os.path.join(sys.argv[1], sys.argv[2]) width = None height = None if len(sys.argv) >= 4: width = int(sys.argv[3]) if len(sys.argv) >= 5: height = int(sys.argv[4]) stats = get_stats(STATS_SERVER, 21212, 30) # Plot single node stats for all apps plot("Average Latency on Single Node", "Time", "Latency (ms)", path + "-latency-single.png", 1, width, height, stats, 'lat99') plot("Single Node Performance", "Time", "Throughput (txns/sec)", path + "-throughput-single.png", 1, width, height, stats, 'tps') # Plot 3 node stats for all apps plot("Average Latency on 3 Nodes", "Time", "Latency (ms)", path + "-latency-3.png", 3, width, height, stats, 'lat99') plot("3 Node Performance", "Time", "Throughput (txns/sec)", path + "-throughput-3.png", 3, width, height, stats, 'tps') # Plot 6 node stats for all apps plot("Average Latency on 6 Node", "Time", "Latency (ms)", path + "-latency-6.png", 6, width, height, stats, 'lat99') plot("6 Node Performance", "Time", "Throughput (txns/sec)", path + "-throughput-6.png", 6, width, height, stats, 'tps') if __name__ == "__main__": main()
gpl-3.0
klahnakoski/jx-sqlite
vendor/mo_collections/unique_index.py
1
5570
# encoding: utf-8 # # # 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/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, division, unicode_literals from mo_dots import is_data, is_sequence, tuplewrap, unwrap, wrap from mo_dots.objects import datawrap from mo_future import PY2, iteritems, Set, Mapping, Iterable from mo_logs import Log from mo_logs.exceptions import suppress_exception DEBUG = False class UniqueIndex(Set, Mapping): """ DEFINE A SET OF ATTRIBUTES THAT UNIQUELY IDENTIFIES EACH OBJECT IN A list. THIS ALLOWS set-LIKE COMPARISIONS (UNION, INTERSECTION, DIFFERENCE, ETC) WHILE STILL MAINTAINING list-LIKE FEATURES KEYS CAN BE DOT-DELIMITED PATHS TO DEEP INNER OBJECTS """ def __init__(self, keys, data=None, fail_on_dup=True): self._data = {} self._keys = tuplewrap(keys) self.count = 0 self.fail_on_dup = fail_on_dup if data: for d in data: self.add(d) def __getitem__(self, key): try: _key = value2key(self._keys, key) if len(self._keys) == 1 or len(_key) == len(self._keys): d = self._data.get(_key) return wrap(d) else: output = wrap([ d for d in self._data.values() if all(wrap(d)[k] == v for k, v in _key.items()) ]) return output except Exception as e: Log.error("something went wrong", e) def __setitem__(self, key, value): Log.error("Use add() to ad to an index") # try: # key = value2key(self._keys, key) # d = self._data.get(key) # if d != None: # Log.error("key already filled") # self._data[key] = unwrap(value) # self.count += 1 # # except Exception as e: # Log.error("something went wrong", e) def keys(self): return self._data.keys() def pop(self): output = iteritems(self._data).next()[1] self.remove(output) return wrap(output) def add(self, val): val = datawrap(val) key = value2key(self._keys, val) if key == None: Log.error("Expecting key to be not None") try: d = self._data.get(key) except Exception as e: key = value2key(self._keys, val) if d is None: self._data[key] = unwrap(val) self.count += 1 elif d is not val: if self.fail_on_dup: Log.error("{{new|json}} with key {{key|json}} already filled with {{old|json}}", key=key, new=val, old=self[val]) elif DEBUG: Log.warning("key {{key|json}} already filled\nExisting\n{{existing|json|indent}}\nValue\n{{value|json|indent}}", key=key, existing=d, value=val ) def extend(self, values): for v in values: self.add(v) def remove(self, val): key = value2key(self._keys, datawrap(val)) if key == None: Log.error("Expecting key to not be None") d = self._data.get(key) if d is None: # ALREADY GONE return else: del self._data[key] self.count -= 1 def __contains__(self, key): return self[key] != None if PY2: def __iter__(self): return (wrap(v) for v in self._data.itervalues()) else: def __iter__(self): return (wrap(v) for v in self._data.values()) def __sub__(self, other): output = UniqueIndex(self._keys, fail_on_dup=self.fail_on_dup) for v in self: if v not in other: output.add(v) return output def __and__(self, other): output = UniqueIndex(self._keys) for v in self: if v in other: output.add(v) return output def __or__(self, other): output = UniqueIndex(self._keys) for v in self: output.add(v) for v in other: with suppress_exception: output.add(v) return output def __ior__(self, other): for v in other: with suppress_exception: self.add(v) return self def __xor__(self, other): if not isinstance(other, Iterable): Log.error("Expecting other to be iterable") other = UniqueIndex(keys=self._keys, data=other, fail_on_dup=False) return (self-other) | (other-self) def __len__(self): if self.count == 0: for d in self: self.count += 1 return self.count def subtract(self, other): return self.__sub__(other) def intersect(self, other): return self.__and__(other) def value2key(keys, val): if len(keys) == 1: if is_data(val): return val[keys[0]] elif is_sequence(val): return val[0] else: return val else: if is_data(val): return datawrap({k: val[k] for k in keys}) elif is_sequence(val): return datawrap(dict(zip(keys, val))) else: Log.error("do not know what to do here")
mpl-2.0
NetEaseGame/AutomatorX
atx/__main__.py
3
7018
#!/usr/bin/env python # -*- coding: utf-8 -*- # USAGE # python -matx -s ESLKJXX gui from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import argparse import functools import json import sys import six import inspect from contextlib import contextmanager from atx.cmds import run from atx.cmds import iosdeveloper from atx.cmds import install def inject(func, kwargs): ''' This is a black techonology of python. like golang martini inject Usage: allargs = dict(name='foo', message='body') def func(name): print 'hi', name inject(func, allargs) # will output # hi foo ''' args = [] for name in inspect.getargspec(func).args: args.append(kwargs.get(name)) return func(*args) def load_main(module_name): def _inner(parser_args): module_path = 'atx.cmds.'+module_name __import__(module_path) mod = sys.modules[module_path] pargs = vars(parser_args) return inject(mod.main, pargs) return _inner def _apk_parse(args): if six.PY2: raise EnvironmentError( "Command \"apkparse\" only available in Python 3.4+") from atx import apkparse manifest = apkparse.parse_apkfile(args.filename) print(json.dumps({ 'package_name': manifest.package_name, 'main_activity': manifest.main_activity, 'version': { 'code': manifest.version_code, 'name': manifest.version_name, } }, indent=4)) def _version(args): import atx print(atx.version) def _deprecated(args): print('Deprecated') def main(): ap = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument("-s", "--serial", "--udid", required=False, help="Android serial or iOS unid") ap.add_argument("-H", "--host", required=False, default='127.0.0.1', help="Adb host") ap.add_argument("-P", "--port", required=False, type=int, default=5037, help="Adb port") subp = ap.add_subparsers() @contextmanager def add_parser(name): yield subp.add_parser(name, formatter_class=argparse.ArgumentDefaultsHelpFormatter) with add_parser('tcpproxy') as p: p.description = 'A very simple tcp proxy' p.add_argument('-l', '--listen', default=5555, type=int, help='Listen port') p.add_argument('-f', '--forward', default=26944, type=int, help='Forwarded port') p.add_argument('--host', default='127.0.0.1', type=str, help='Forwarded host') p.set_defaults(func=load_main('tcpproxy')) with add_parser('gui') as p: p.description = 'GUI tool to help write test script' p.add_argument('-p', '--platform', default='auto', choices=('auto', 'android', 'ios'), help='platform') p.add_argument('-s', '--serial', default=None, type=str, help='android serial or WDA device url') p.add_argument('--scale', default=0.5, type=float, help='scale size') p.set_defaults(func=load_main('tkgui')) # Remove because of unstable # with add_parser('record') as p: # p.add_argument('-d', '--workdir', default='.', help='workdir where case & frame files are saved.') # p.add_argument('-e', '--edit', action='store_true', dest='edit_mode', help='edit old records.') # p.add_argument('-a', '--nonui-activity', action='append', dest='nonui_activities', # required=False, help='nonui-activities for which the recorder will analyze screen image instead of uixml.') # p.set_defaults(func=load_main('record')) with add_parser('minicap') as p: p.description = 'install minicap to phone' p.set_defaults(func=load_main('minicap')) with add_parser('apkparse') as p: p.description = 'parse package-name and main-activity from apk' p.add_argument('filename', help='Apk filename') p.set_defaults(func=_apk_parse) with add_parser('monkey') as p: p.set_defaults(func=load_main('monkey')) with add_parser('install') as p: p.description = 'install apk to phone' p.add_argument( 'path', help='<apk file path | apk url path> (only support android for now)') p.add_argument('--start', action='store_true', help='Start app when app success installed') p.set_defaults(func=load_main('install')) with add_parser('screen') as p: p.add_argument('--scale', required=False, type=float, default=0.5, help='image scale') p.add_argument('--simple', action='store_true', help='disable interact controls') p.set_defaults(func=load_main('screen')) with add_parser('screencap') as p: p.description = 'take screenshot' p.add_argument('--scale', required=False, type=float, default=1.0, help='image scale') p.add_argument('-o', '--out', required=False, default='screenshot.png', help='output path') p.add_argument('-m', '--method', required=False, default='minicap', choices=('minicap', 'screencap'), help='screenshot method') p.set_defaults(func=load_main('screencap')) with add_parser('screenrecord') as p: p.description = 'record video (require minicap)' p.add_argument('-o', '--output', default='out.avi', help='video output path') p.add_argument('--overwrite', action='store_true', help='overwrite video output file.') p.add_argument('--scale', type=float, default=0.5, help='image scale for video') p.add_argument('-q', '--quiet', dest='verbose', action='store_false', help='display screen while recording.') p.add_argument('--portrait', action='store_true', help='set video framesize to portrait instead of landscape.') p.set_defaults(func=load_main('screenrecord')) with add_parser('web') as p: p.description = 'not maintained this func, try with: pip install atx-webide' p.set_defaults(func=_deprecated) with add_parser('run') as p: p.add_argument('-f', dest='config_file', default='atx.yml', help='config file') p.set_defaults(func=load_main('run')) with add_parser('version') as p: p.set_defaults(func=_version) with add_parser('info') as p: p.set_defaults(func=load_main('info')) with add_parser('doctor') as p: p.set_defaults(func=load_main('doctor')) args = ap.parse_args() if not hasattr(args, 'func'): print(' '.join(sys.argv) + ' -h for more help') return args.func(args) if __name__ == '__main__': main()
apache-2.0
mhils/mitmproxy
test/mitmproxy/test_flow.py
2
4799
import io import pytest import mitmproxy.io from mitmproxy import flow from mitmproxy import flowfilter from mitmproxy import options from mitmproxy.exceptions import FlowReadException from mitmproxy.io import tnetstring from mitmproxy.test import taddons, tflow from . import tservers class TestSerialize: def test_roundtrip(self): sio = io.BytesIO() f = tflow.tflow() f.marked = True f.request.content = bytes(range(256)) w = mitmproxy.io.FlowWriter(sio) w.add(f) sio.seek(0) r = mitmproxy.io.FlowReader(sio) l = list(r.stream()) assert len(l) == 1 f2 = l[0] assert f2.get_state() == f.get_state() assert f2.request.data == f.request.data assert f2.marked def test_filter(self): sio = io.BytesIO() flt = flowfilter.parse("~c 200") w = mitmproxy.io.FilteredFlowWriter(sio, flt) f = tflow.tflow(resp=True) f.response.status_code = 200 w.add(f) f = tflow.tflow(resp=True) f.response.status_code = 201 w.add(f) sio.seek(0) r = mitmproxy.io.FlowReader(sio) assert len(list(r.stream())) def test_error(self): sio = io.BytesIO() sio.write(b"bogus") sio.seek(0) r = mitmproxy.io.FlowReader(sio) with pytest.raises(FlowReadException, match='Invalid data format'): list(r.stream()) sio = io.BytesIO() f = tflow.tdummyflow() w = mitmproxy.io.FlowWriter(sio) w.add(f) sio.seek(0) r = mitmproxy.io.FlowReader(sio) with pytest.raises(FlowReadException, match='Unknown flow type'): list(r.stream()) f = FlowReadException("foo") assert str(f) == "foo" def test_versioncheck(self): f = tflow.tflow() d = f.get_state() d["version"] = (0, 0) sio = io.BytesIO() tnetstring.dump(d, sio) sio.seek(0) r = mitmproxy.io.FlowReader(sio) with pytest.raises(Exception, match="version"): list(r.stream()) def test_copy(self): """ _backup may be shared across instances. That should not raise errors. """ f = tflow.tflow() f.backup() f.request.path = "/foo" f2 = f.copy() f2.revert() f.revert() class TestFlowMaster: @pytest.mark.asyncio async def test_load_http_flow_reverse(self): opts = options.Options( mode="reverse:https://use-this-domain" ) s = tservers.TestState() with taddons.context(s, options=opts) as ctx: f = tflow.tflow(resp=True) await ctx.master.load_flow(f) assert s.flows[0].request.host == "use-this-domain" @pytest.mark.asyncio async def test_load_websocket_flow(self): opts = options.Options( mode="reverse:https://use-this-domain" ) s = tservers.TestState() with taddons.context(s, options=opts) as ctx: f = tflow.twebsocketflow() await ctx.master.load_flow(f.handshake_flow) await ctx.master.load_flow(f) assert s.flows[0].request.host == "use-this-domain" assert s.flows[1].handshake_flow == f.handshake_flow assert len(s.flows[1].messages) == len(f.messages) @pytest.mark.asyncio async def test_all(self): opts = options.Options( mode="reverse:https://use-this-domain" ) s = tservers.TestState() with taddons.context(s, options=opts) as ctx: f = tflow.tflow(req=None) await ctx.master.addons.handle_lifecycle("clientconnect", f.client_conn) f.request = mitmproxy.test.tutils.treq() await ctx.master.addons.handle_lifecycle("request", f) assert len(s.flows) == 1 f.response = mitmproxy.test.tutils.tresp() await ctx.master.addons.handle_lifecycle("response", f) assert len(s.flows) == 1 await ctx.master.addons.handle_lifecycle("clientdisconnect", f.client_conn) f.error = flow.Error("msg") await ctx.master.addons.handle_lifecycle("error", f) class TestError: def test_getset_state(self): e = flow.Error("Error") state = e.get_state() assert flow.Error.from_state(state).get_state() == e.get_state() assert e.copy() e2 = flow.Error("bar") assert not e == e2 e.set_state(e2.get_state()) assert e.get_state() == e2.get_state() e3 = e.copy() assert e3.get_state() == e.get_state() def test_repr(self): e = flow.Error("yay") assert repr(e) assert str(e)
mit
afonsinoguimaraes/repository.magellan
plugin.video.SportsDevil/lib/utils/xppod.py
17
2758
#!/usr/bin/env python2 # -*- coding: UTF-8 -*- # 2014 - Anonymous def decode(string): import base64 s = '' str = _reverse(string) for x in range(0,len(str)): s += _decode_char(str[x]) return base64.b64decode(s) def _reverse(s): string = '' length = len(s)-3 while length > 2: string += s[length] length = length - 1 length = len(string) num2 = int(s[1]+s[0])/2 if num2 < length: i = num2 while i < length: if len(string) <= i: return string if (i+1) < length: string = string[0:i] + string[i+1:] i += num2 return string def _decode_char(c): array1 = ["0", "1", "2", "3", "4", "5", "6", "7", "9", "H", "M", "D", "X", "V", "J", "Q", "U", "G", "E", "T", "N", "o", "v", "y", "w", "k"] array2 = ["c", "I", "W", "m", "8", "L", "l", "g", "R", "B", "a", "u", "s", "p", "z", "Z", "e", "d", "=", "x", "Y", "t", "n", "f", "b", "i"] for i in range(0,len(array1)): if c == array1[i]: return array2[i][0] if c == array2[i]: return array1[i][0] return c def decode_hls(file_url): def K12K(a, typ='b'): codec_a = ["p", "9", "U", "1", "b", "s", "y", "Z", "I", "H", "f", "8", "Y", "W", "g", "5", "G", "i", "J", "2", "T", "e", "k", "d", "7", "="] codec_b = ["0", "B", "w", "t", "x", "m", "c", "z", "u", "n", "M", "Q", "R", "6", "v", "V", "l", "N", "D", "3", "L", "X", "a", "4", "o", "A"] if 'd' == typ: tmp = codec_a codec_a = codec_b codec_b = tmp idx = 0 while idx < len(codec_a): a = a.replace(codec_a[idx], "___") a = a.replace(codec_b[idx], codec_a[idx]) a = a.replace("___", codec_b[idx]) idx += 1 return a def _xc13(_arg1): _lg27 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" _local2 = "" _local3 = [0, 0, 0, 0] _local4 = [0, 0, 0] _local5 = 0 while _local5 < len(_arg1): _local6 = 0 while _local6 < 4 and (_local5 + _local6) < len(_arg1): _local3[_local6] = _lg27.find(_arg1[_local5 + _local6]) _local6 += 1 _local4[0] = ((_local3[0] << 2) + ((_local3[1] & 48) >> 4)) _local4[1] = (((_local3[1] & 15) << 4) + ((_local3[2] & 60) >> 2)) _local4[2] = (((_local3[2] & 3) << 6) + _local3[3]) _local7 = 0 while _local7 < len(_local4): if _local3[_local7 + 1] == 64: break _local2 += chr(_local4[_local7]) _local7 += 1 _local5 += 4 return _local2 return _xc13(K12K(file_url, 'e'))
gpl-2.0
Brocade-OpenSource/OpenStack-DNRM-Nova
nova/api/openstack/compute/plugins/v3/flavor_rxtx.py
14
2990
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The Flavor Rxtx API extension.""" from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil ALIAS = 'os-flavor-rxtx' authorize = extensions.soft_extension_authorizer('compute', 'v3:' + ALIAS) class FlavorRxtxController(wsgi.Controller): def _extend_flavors(self, req, flavors): for flavor in flavors: db_flavor = req.get_db_flavor(flavor['id']) key = 'rxtx_factor' flavor[key] = db_flavor['rxtx_factor'] or "" def _show(self, req, resp_obj): if not authorize(req.environ['nova.context']): return if 'flavor' in resp_obj.obj: resp_obj.attach(xml=FlavorRxtxTemplate()) self._extend_flavors(req, [resp_obj.obj['flavor']]) @wsgi.extends def show(self, req, resp_obj, id): return self._show(req, resp_obj) @wsgi.extends(action='create') def create(self, req, resp_obj, body): return self._show(req, resp_obj) @wsgi.extends def detail(self, req, resp_obj): if not authorize(req.environ['nova.context']): return resp_obj.attach(xml=FlavorsRxtxTemplate()) self._extend_flavors(req, list(resp_obj.obj['flavors'])) class FlavorRxtx(extensions.V3APIExtensionBase): """Support to show the rxtx status of a flavor.""" name = "FlavorRxtx" alias = ALIAS namespace = "http://docs.openstack.org/compute/ext/%s/api/v3" % ALIAS version = 1 def get_controller_extensions(self): controller = FlavorRxtxController() extension = extensions.ControllerExtension(self, 'flavors', controller) return [extension] def get_resources(self): return [] def make_flavor(elem): # NOTE(vish): this was originally added without a namespace elem.set('rxtx_factor', xmlutil.EmptyStringSelector('rxtx_factor')) class FlavorRxtxTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('flavor', selector='flavor') make_flavor(root) return xmlutil.SlaveTemplate(root, 1) class FlavorsRxtxTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('flavors') elem = xmlutil.SubTemplateElement(root, 'flavor', selector='flavors') make_flavor(elem) return xmlutil.SlaveTemplate(root, 1)
apache-2.0
jamespcole/home-assistant
tests/util/test_yaml.py
1
17357
"""Test Home Assistant yaml loader.""" import io import os import unittest import logging from unittest.mock import patch import pytest from homeassistant.exceptions import HomeAssistantError from homeassistant.util import yaml from homeassistant.config import YAML_CONFIG_FILE, load_yaml_config_file from tests.common import get_test_config_dir, patch_yaml_files @pytest.fixture(autouse=True) def mock_credstash(): """Mock credstash so it doesn't connect to the internet.""" with patch.object(yaml, 'credstash') as mock_credstash: mock_credstash.getSecret.return_value = None yield mock_credstash class TestYaml(unittest.TestCase): """Test util.yaml loader.""" # pylint: disable=no-self-use, invalid-name def test_simple_list(self): """Test simple list.""" conf = "config:\n - simple\n - list" with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert doc['config'] == ["simple", "list"] def test_simple_dict(self): """Test simple dict.""" conf = "key: value" with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert doc['key'] == 'value' def test_unhashable_key(self): """Test an unhasable key.""" files = {YAML_CONFIG_FILE: 'message:\n {{ states.state }}'} with pytest.raises(HomeAssistantError), \ patch_yaml_files(files): load_yaml_config_file(YAML_CONFIG_FILE) def test_no_key(self): """Test item without a key.""" files = {YAML_CONFIG_FILE: 'a: a\nnokeyhere'} with pytest.raises(HomeAssistantError), \ patch_yaml_files(files): yaml.load_yaml(YAML_CONFIG_FILE) def test_environment_variable(self): """Test config file with environment variable.""" os.environ["PASSWORD"] = "secret_password" conf = "password: !env_var PASSWORD" with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert doc['password'] == "secret_password" del os.environ["PASSWORD"] def test_environment_variable_default(self): """Test config file with default value for environment variable.""" conf = "password: !env_var PASSWORD secret_password" with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert doc['password'] == "secret_password" def test_invalid_environment_variable(self): """Test config file with no environment variable sat.""" conf = "password: !env_var PASSWORD" with pytest.raises(HomeAssistantError): with io.StringIO(conf) as file: yaml.yaml.safe_load(file) def test_include_yaml(self): """Test include yaml.""" with patch_yaml_files({'test.yaml': 'value'}): conf = 'key: !include test.yaml' with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert doc["key"] == "value" with patch_yaml_files({'test.yaml': None}): conf = 'key: !include test.yaml' with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert doc["key"] == {} @patch('homeassistant.util.yaml.os.walk') def test_include_dir_list(self, mock_walk): """Test include dir list yaml.""" mock_walk.return_value = [ ['/tmp', [], ['two.yaml', 'one.yaml']], ] with patch_yaml_files({ '/tmp/one.yaml': 'one', '/tmp/two.yaml': 'two', }): conf = "key: !include_dir_list /tmp" with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert doc["key"] == sorted(["one", "two"]) @patch('homeassistant.util.yaml.os.walk') def test_include_dir_list_recursive(self, mock_walk): """Test include dir recursive list yaml.""" mock_walk.return_value = [ ['/tmp', ['tmp2', '.ignore', 'ignore'], ['zero.yaml']], ['/tmp/tmp2', [], ['one.yaml', 'two.yaml']], ['/tmp/ignore', [], ['.ignore.yaml']] ] with patch_yaml_files({ '/tmp/zero.yaml': 'zero', '/tmp/tmp2/one.yaml': 'one', '/tmp/tmp2/two.yaml': 'two' }): conf = "key: !include_dir_list /tmp" with io.StringIO(conf) as file: assert '.ignore' in mock_walk.return_value[0][1], \ "Expecting .ignore in here" doc = yaml.yaml.safe_load(file) assert 'tmp2' in mock_walk.return_value[0][1] assert '.ignore' not in mock_walk.return_value[0][1] assert sorted(doc["key"]) == sorted(["zero", "one", "two"]) @patch('homeassistant.util.yaml.os.walk') def test_include_dir_named(self, mock_walk): """Test include dir named yaml.""" mock_walk.return_value = [ ['/tmp', [], ['first.yaml', 'second.yaml']] ] with patch_yaml_files({ '/tmp/first.yaml': 'one', '/tmp/second.yaml': 'two' }): conf = "key: !include_dir_named /tmp" correct = {'first': 'one', 'second': 'two'} with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert doc["key"] == correct @patch('homeassistant.util.yaml.os.walk') def test_include_dir_named_recursive(self, mock_walk): """Test include dir named yaml.""" mock_walk.return_value = [ ['/tmp', ['tmp2', '.ignore', 'ignore'], ['first.yaml']], ['/tmp/tmp2', [], ['second.yaml', 'third.yaml']], ['/tmp/ignore', [], ['.ignore.yaml']] ] with patch_yaml_files({ '/tmp/first.yaml': 'one', '/tmp/tmp2/second.yaml': 'two', '/tmp/tmp2/third.yaml': 'three' }): conf = "key: !include_dir_named /tmp" correct = {'first': 'one', 'second': 'two', 'third': 'three'} with io.StringIO(conf) as file: assert '.ignore' in mock_walk.return_value[0][1], \ "Expecting .ignore in here" doc = yaml.yaml.safe_load(file) assert 'tmp2' in mock_walk.return_value[0][1] assert '.ignore' not in mock_walk.return_value[0][1] assert doc["key"] == correct @patch('homeassistant.util.yaml.os.walk') def test_include_dir_merge_list(self, mock_walk): """Test include dir merge list yaml.""" mock_walk.return_value = [['/tmp', [], ['first.yaml', 'second.yaml']]] with patch_yaml_files({ '/tmp/first.yaml': '- one', '/tmp/second.yaml': '- two\n- three' }): conf = "key: !include_dir_merge_list /tmp" with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert sorted(doc["key"]) == sorted(["one", "two", "three"]) @patch('homeassistant.util.yaml.os.walk') def test_include_dir_merge_list_recursive(self, mock_walk): """Test include dir merge list yaml.""" mock_walk.return_value = [ ['/tmp', ['tmp2', '.ignore', 'ignore'], ['first.yaml']], ['/tmp/tmp2', [], ['second.yaml', 'third.yaml']], ['/tmp/ignore', [], ['.ignore.yaml']] ] with patch_yaml_files({ '/tmp/first.yaml': '- one', '/tmp/tmp2/second.yaml': '- two', '/tmp/tmp2/third.yaml': '- three\n- four' }): conf = "key: !include_dir_merge_list /tmp" with io.StringIO(conf) as file: assert '.ignore' in mock_walk.return_value[0][1], \ "Expecting .ignore in here" doc = yaml.yaml.safe_load(file) assert 'tmp2' in mock_walk.return_value[0][1] assert '.ignore' not in mock_walk.return_value[0][1] assert sorted(doc["key"]) == sorted(["one", "two", "three", "four"]) @patch('homeassistant.util.yaml.os.walk') def test_include_dir_merge_named(self, mock_walk): """Test include dir merge named yaml.""" mock_walk.return_value = [['/tmp', [], ['first.yaml', 'second.yaml']]] files = { '/tmp/first.yaml': 'key1: one', '/tmp/second.yaml': 'key2: two\nkey3: three', } with patch_yaml_files(files): conf = "key: !include_dir_merge_named /tmp" with io.StringIO(conf) as file: doc = yaml.yaml.safe_load(file) assert doc["key"] == { "key1": "one", "key2": "two", "key3": "three" } @patch('homeassistant.util.yaml.os.walk') def test_include_dir_merge_named_recursive(self, mock_walk): """Test include dir merge named yaml.""" mock_walk.return_value = [ ['/tmp', ['tmp2', '.ignore', 'ignore'], ['first.yaml']], ['/tmp/tmp2', [], ['second.yaml', 'third.yaml']], ['/tmp/ignore', [], ['.ignore.yaml']] ] with patch_yaml_files({ '/tmp/first.yaml': 'key1: one', '/tmp/tmp2/second.yaml': 'key2: two', '/tmp/tmp2/third.yaml': 'key3: three\nkey4: four' }): conf = "key: !include_dir_merge_named /tmp" with io.StringIO(conf) as file: assert '.ignore' in mock_walk.return_value[0][1], \ "Expecting .ignore in here" doc = yaml.yaml.safe_load(file) assert 'tmp2' in mock_walk.return_value[0][1] assert '.ignore' not in mock_walk.return_value[0][1] assert doc["key"] == { "key1": "one", "key2": "two", "key3": "three", "key4": "four" } @patch('homeassistant.util.yaml.open', create=True) def test_load_yaml_encoding_error(self, mock_open): """Test raising a UnicodeDecodeError.""" mock_open.side_effect = UnicodeDecodeError('', b'', 1, 0, '') with pytest.raises(HomeAssistantError): yaml.load_yaml('test') def test_dump(self): """The that the dump method returns empty None values.""" assert yaml.dump({'a': None, 'b': 'b'}) == 'a:\nb: b\n' def test_dump_unicode(self): """The that the dump method returns empty None values.""" assert yaml.dump({'a': None, 'b': 'привет'}) == 'a:\nb: привет\n' FILES = {} def load_yaml(fname, string): """Write a string to file and return the parsed yaml.""" FILES[fname] = string with patch_yaml_files(FILES): return load_yaml_config_file(fname) class FakeKeyring(): """Fake a keyring class.""" def __init__(self, secrets_dict): """Store keyring dictionary.""" self._secrets = secrets_dict # pylint: disable=protected-access def get_password(self, domain, name): """Retrieve password.""" assert domain == yaml._SECRET_NAMESPACE return self._secrets.get(name) class TestSecrets(unittest.TestCase): """Test the secrets parameter in the yaml utility.""" # pylint: disable=protected-access,invalid-name def setUp(self): """Create & load secrets file.""" config_dir = get_test_config_dir() yaml.clear_secret_cache() self._yaml_path = os.path.join(config_dir, YAML_CONFIG_FILE) self._secret_path = os.path.join(config_dir, yaml.SECRET_YAML) self._sub_folder_path = os.path.join(config_dir, 'subFolder') self._unrelated_path = os.path.join(config_dir, 'unrelated') load_yaml(self._secret_path, 'http_pw: pwhttp\n' 'comp1_un: un1\n' 'comp1_pw: pw1\n' 'stale_pw: not_used\n' 'logger: debug\n') self._yaml = load_yaml(self._yaml_path, 'http:\n' ' api_password: !secret http_pw\n' 'component:\n' ' username: !secret comp1_un\n' ' password: !secret comp1_pw\n' '') def tearDown(self): """Clean up secrets.""" yaml.clear_secret_cache() FILES.clear() def test_secrets_from_yaml(self): """Did secrets load ok.""" expected = {'api_password': 'pwhttp'} assert expected == self._yaml['http'] expected = { 'username': 'un1', 'password': 'pw1'} assert expected == self._yaml['component'] def test_secrets_from_parent_folder(self): """Test loading secrets from parent foler.""" expected = {'api_password': 'pwhttp'} self._yaml = load_yaml(os.path.join(self._sub_folder_path, 'sub.yaml'), 'http:\n' ' api_password: !secret http_pw\n' 'component:\n' ' username: !secret comp1_un\n' ' password: !secret comp1_pw\n' '') assert expected == self._yaml['http'] def test_secret_overrides_parent(self): """Test loading current directory secret overrides the parent.""" expected = {'api_password': 'override'} load_yaml(os.path.join(self._sub_folder_path, yaml.SECRET_YAML), 'http_pw: override') self._yaml = load_yaml(os.path.join(self._sub_folder_path, 'sub.yaml'), 'http:\n' ' api_password: !secret http_pw\n' 'component:\n' ' username: !secret comp1_un\n' ' password: !secret comp1_pw\n' '') assert expected == self._yaml['http'] def test_secrets_from_unrelated_fails(self): """Test loading secrets from unrelated folder fails.""" load_yaml(os.path.join(self._unrelated_path, yaml.SECRET_YAML), 'test: failure') with pytest.raises(HomeAssistantError): load_yaml(os.path.join(self._sub_folder_path, 'sub.yaml'), 'http:\n' ' api_password: !secret test') def test_secrets_keyring(self): """Test keyring fallback & get_password.""" yaml.keyring = None # Ensure its not there yaml_str = 'http:\n api_password: !secret http_pw_keyring' with pytest.raises(yaml.HomeAssistantError): load_yaml(self._yaml_path, yaml_str) yaml.keyring = FakeKeyring({'http_pw_keyring': 'yeah'}) _yaml = load_yaml(self._yaml_path, yaml_str) assert {'http': {'api_password': 'yeah'}} == _yaml @patch.object(yaml, 'credstash') def test_secrets_credstash(self, mock_credstash): """Test credstash fallback & get_password.""" mock_credstash.getSecret.return_value = 'yeah' yaml_str = 'http:\n api_password: !secret http_pw_credstash' _yaml = load_yaml(self._yaml_path, yaml_str) log = logging.getLogger() log.error(_yaml['http']) assert {'api_password': 'yeah'} == _yaml['http'] def test_secrets_logger_removed(self): """Ensure logger: debug was removed.""" with pytest.raises(yaml.HomeAssistantError): load_yaml(self._yaml_path, 'api_password: !secret logger') @patch('homeassistant.util.yaml._LOGGER.error') def test_bad_logger_value(self, mock_error): """Ensure logger: debug was removed.""" yaml.clear_secret_cache() load_yaml(self._secret_path, 'logger: info\npw: abc') load_yaml(self._yaml_path, 'api_password: !secret pw') assert mock_error.call_count == 1, \ "Expected an error about logger: value" def test_secrets_are_not_dict(self): """Did secrets handle non-dict file.""" FILES[self._secret_path] = ( '- http_pw: pwhttp\n' ' comp1_un: un1\n' ' comp1_pw: pw1\n') yaml.clear_secret_cache() with pytest.raises(HomeAssistantError): load_yaml(self._yaml_path, 'http:\n' ' api_password: !secret http_pw\n' 'component:\n' ' username: !secret comp1_un\n' ' password: !secret comp1_pw\n' '') def test_representing_yaml_loaded_data(): """Test we can represent YAML loaded data.""" files = {YAML_CONFIG_FILE: 'key: [1, "2", 3]'} with patch_yaml_files(files): data = load_yaml_config_file(YAML_CONFIG_FILE) assert yaml.dump(data) == "key:\n- 1\n- '2'\n- 3\n" def test_duplicate_key(caplog): """Test duplicate dict keys.""" files = {YAML_CONFIG_FILE: 'key: thing1\nkey: thing2'} with patch_yaml_files(files): load_yaml_config_file(YAML_CONFIG_FILE) assert 'contains duplicate key' in caplog.text
apache-2.0
lmorchard/django
tests/auth_tests/test_decorators.py
279
4124
from django.conf import settings from django.contrib.auth import models from django.contrib.auth.decorators import login_required, permission_required from django.core.exceptions import PermissionDenied from django.http import HttpResponse from django.test import TestCase, override_settings from django.test.client import RequestFactory from .test_views import AuthViewsTestCase @override_settings(ROOT_URLCONF='auth_tests.urls') class LoginRequiredTestCase(AuthViewsTestCase): """ Tests the login_required decorators """ def testCallable(self): """ Check that login_required is assignable to callable objects. """ class CallableView(object): def __call__(self, *args, **kwargs): pass login_required(CallableView()) def testView(self): """ Check that login_required is assignable to normal views. """ def normal_view(request): pass login_required(normal_view) def testLoginRequired(self, view_url='/login_required/', login_url=None): """ Check that login_required works on a simple view wrapped in a login_required decorator. """ if login_url is None: login_url = settings.LOGIN_URL response = self.client.get(view_url) self.assertEqual(response.status_code, 302) self.assertIn(login_url, response.url) self.login() response = self.client.get(view_url) self.assertEqual(response.status_code, 200) def testLoginRequiredNextUrl(self): """ Check that login_required works on a simple view wrapped in a login_required decorator with a login_url set. """ self.testLoginRequired(view_url='/login_required_login_url/', login_url='/somewhere/') class PermissionsRequiredDecoratorTest(TestCase): """ Tests for the permission_required decorator """ def setUp(self): self.user = models.User.objects.create(username='joe', password='qwerty') self.factory = RequestFactory() # Add permissions auth.add_customuser and auth.change_customuser perms = models.Permission.objects.filter(codename__in=('add_customuser', 'change_customuser')) self.user.user_permissions.add(*perms) def test_many_permissions_pass(self): @permission_required(['auth.add_customuser', 'auth.change_customuser']) def a_view(request): return HttpResponse() request = self.factory.get('/rand') request.user = self.user resp = a_view(request) self.assertEqual(resp.status_code, 200) def test_many_permissions_in_set_pass(self): @permission_required({'auth.add_customuser', 'auth.change_customuser'}) def a_view(request): return HttpResponse() request = self.factory.get('/rand') request.user = self.user resp = a_view(request) self.assertEqual(resp.status_code, 200) def test_single_permission_pass(self): @permission_required('auth.add_customuser') def a_view(request): return HttpResponse() request = self.factory.get('/rand') request.user = self.user resp = a_view(request) self.assertEqual(resp.status_code, 200) def test_permissioned_denied_redirect(self): @permission_required(['auth.add_customuser', 'auth.change_customuser', 'non-existent-permission']) def a_view(request): return HttpResponse() request = self.factory.get('/rand') request.user = self.user resp = a_view(request) self.assertEqual(resp.status_code, 302) def test_permissioned_denied_exception_raised(self): @permission_required([ 'auth.add_customuser', 'auth.change_customuser', 'non-existent-permission' ], raise_exception=True) def a_view(request): return HttpResponse() request = self.factory.get('/rand') request.user = self.user self.assertRaises(PermissionDenied, a_view, request)
bsd-3-clause
patrickcurl/ztruck
dj/lib/python2.7/site-packages/django/templatetags/i18n.py
82
17673
from __future__ import unicode_literals import re import sys from django.conf import settings from django.template import Library, Node, TemplateSyntaxError, Variable from django.template.base import ( TOKEN_TEXT, TOKEN_VAR, TokenParser, render_value_in_context, ) from django.template.defaulttags import token_kwargs from django.utils import six, translation register = Library() class GetAvailableLanguagesNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES] return '' class GetLanguageInfoNode(Node): def __init__(self, lang_code, variable): self.lang_code = lang_code self.variable = variable def render(self, context): lang_code = self.lang_code.resolve(context) context[self.variable] = translation.get_language_info(lang_code) return '' class GetLanguageInfoListNode(Node): def __init__(self, languages, variable): self.languages = languages self.variable = variable def get_language_info(self, language): # ``language`` is either a language code string or a sequence # with the language code as its first item if len(language[0]) > 1: return translation.get_language_info(language[0]) else: return translation.get_language_info(str(language)) def render(self, context): langs = self.languages.resolve(context) context[self.variable] = [self.get_language_info(lang) for lang in langs] return '' class GetCurrentLanguageNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language() return '' class GetCurrentLanguageBidiNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language_bidi() return '' class TranslateNode(Node): def __init__(self, filter_expression, noop, asvar=None, message_context=None): self.noop = noop self.asvar = asvar self.message_context = message_context self.filter_expression = filter_expression if isinstance(self.filter_expression.var, six.string_types): self.filter_expression.var = Variable("'%s'" % self.filter_expression.var) def render(self, context): self.filter_expression.var.translate = not self.noop if self.message_context: self.filter_expression.var.message_context = ( self.message_context.resolve(context)) output = self.filter_expression.resolve(context) value = render_value_in_context(output, context) if self.asvar: context[self.asvar] = value return '' else: return value class BlockTranslateNode(Node): def __init__(self, extra_context, singular, plural=None, countervar=None, counter=None, message_context=None, trimmed=False): self.extra_context = extra_context self.singular = singular self.plural = plural self.countervar = countervar self.counter = counter self.message_context = message_context self.trimmed = trimmed def render_token_list(self, tokens): result = [] vars = [] for token in tokens: if token.token_type == TOKEN_TEXT: result.append(token.contents.replace('%', '%%')) elif token.token_type == TOKEN_VAR: result.append('%%(%s)s' % token.contents) vars.append(token.contents) msg = ''.join(result) if self.trimmed: msg = translation.trim_whitespace(msg) return msg, vars def render(self, context, nested=False): if self.message_context: message_context = self.message_context.resolve(context) else: message_context = None tmp_context = {} for var, val in self.extra_context.items(): tmp_context[var] = val.resolve(context) # Update() works like a push(), so corresponding context.pop() is at # the end of function context.update(tmp_context) singular, vars = self.render_token_list(self.singular) if self.plural and self.countervar and self.counter: count = self.counter.resolve(context) context[self.countervar] = count plural, plural_vars = self.render_token_list(self.plural) if message_context: result = translation.npgettext(message_context, singular, plural, count) else: result = translation.ungettext(singular, plural, count) vars.extend(plural_vars) else: if message_context: result = translation.pgettext(message_context, singular) else: result = translation.ugettext(singular) default_value = context.template.engine.string_if_invalid def render_value(key): if key in context: val = context[key] else: val = default_value % key if '%s' in default_value else default_value return render_value_in_context(val, context) data = {v: render_value(v) for v in vars} context.pop() try: result = result % data except (KeyError, ValueError): if nested: # Either string is malformed, or it's a bug raise TemplateSyntaxError("'blocktrans' is unable to format " "string returned by gettext: %r using %r" % (result, data)) with translation.override(None): result = self.render(context, nested=True) return result class LanguageNode(Node): def __init__(self, nodelist, language): self.nodelist = nodelist self.language = language def render(self, context): with translation.override(self.language.resolve(context)): output = self.nodelist.render(context) return output @register.tag("get_available_languages") def do_get_available_languages(parser, token): """ This will store a list of available languages in the context. Usage:: {% get_available_languages as languages %} {% for language in languages %} ... {% endfor %} This will just pull the LANGUAGES setting from your setting file (or the default settings) and put it into the named variable. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args) return GetAvailableLanguagesNode(args[2]) @register.tag("get_language_info") def do_get_language_info(parser, token): """ This will store the language information dictionary for the given language code in a context variable. Usage:: {% get_language_info for LANGUAGE_CODE as l %} {{ l.code }} {{ l.name }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} """ args = token.split_contents() if len(args) != 5 or args[1] != 'for' or args[3] != 'as': raise TemplateSyntaxError("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])) return GetLanguageInfoNode(parser.compile_filter(args[2]), args[4]) @register.tag("get_language_info_list") def do_get_language_info_list(parser, token): """ This will store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style tuple (or any sequence of sequences whose first items are language codes). Usage:: {% get_language_info_list for LANGUAGES as langs %} {% for l in langs %} {{ l.code }} {{ l.name }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} {% endfor %} """ args = token.split_contents() if len(args) != 5 or args[1] != 'for' or args[3] != 'as': raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:])) return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4]) @register.filter def language_name(lang_code): return translation.get_language_info(lang_code)['name'] @register.filter def language_name_local(lang_code): return translation.get_language_info(lang_code)['name_local'] @register.filter def language_bidi(lang_code): return translation.get_language_info(lang_code)['bidi'] @register.tag("get_current_language") def do_get_current_language(parser, token): """ This will store the current language in the context. Usage:: {% get_current_language as language %} This will fetch the currently active language and put it's value into the ``language`` context variable. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args) return GetCurrentLanguageNode(args[2]) @register.tag("get_current_language_bidi") def do_get_current_language_bidi(parser, token): """ This will store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This will fetch the currently active language's layout and put it's value into the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to-right """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args) return GetCurrentLanguageBidiNode(args[2]) @register.tag("trans") def do_translate(parser, token): """ This will mark a string for translation and will translate the string for the current language. Usage:: {% trans "this is a test" %} This will mark the string for translation so it will be pulled out by mark-messages.py into the .po files and will run the string through the translation engine. There is a second form:: {% trans "this is a test" noop %} This will only mark for translation, but will return the string unchanged. Use it when you need to store values into forms that should be translated later on. You can use variables instead of constant strings to translate stuff you marked somewhere else:: {% trans variable %} This will just try to translate the contents of the variable ``variable``. Make sure that the string in there is something that is in the .po file. It is possible to store the translated string into a variable:: {% trans "this is a test" as var %} {{ var }} Contextual translations are also supported:: {% trans "this is a test" context "greeting" %} This is equivalent to calling pgettext instead of (u)gettext. """ class TranslateParser(TokenParser): def top(self): value = self.value() # Backwards Compatibility fix: # FilterExpression does not support single-quoted strings, # so we make a cheap localized fix in order to maintain # backwards compatibility with existing uses of ``trans`` # where single quote use is supported. if value[0] == "'": m = re.match("^'([^']+)'(\|.*$)", value) if m: value = '"%s"%s' % (m.group(1).replace('"', '\\"'), m.group(2)) elif value[-1] == "'": value = '"%s"' % value[1:-1].replace('"', '\\"') noop = False asvar = None message_context = None while self.more(): tag = self.tag() if tag == 'noop': noop = True elif tag == 'context': message_context = parser.compile_filter(self.value()) elif tag == 'as': asvar = self.tag() else: raise TemplateSyntaxError( "Only options for 'trans' are 'noop', " "'context \"xxx\"', and 'as VAR'.") return value, noop, asvar, message_context value, noop, asvar, message_context = TranslateParser(token.contents).top() return TranslateNode(parser.compile_filter(value), noop, asvar, message_context) @register.tag("blocktrans") def do_block_translate(parser, token): """ This will translate a block of text with parameters. Usage:: {% blocktrans with bar=foo|filter boo=baz|filter %} This is {{ bar }} and {{ boo }}. {% endblocktrans %} Additionally, this supports pluralization:: {% blocktrans count count=var|length %} There is {{ count }} object. {% plural %} There are {{ count }} objects. {% endblocktrans %} This is much like ngettext, only in template syntax. The "var as value" legacy format is still supported:: {% blocktrans with foo|filter as bar and baz|filter as boo %} {% blocktrans count var|length as count %} Contextual translations are supported:: {% blocktrans with bar=foo|filter context "greeting" %} This is {{ bar }}. {% endblocktrans %} This is equivalent to calling pgettext/npgettext instead of (u)gettext/(u)ngettext. """ bits = token.split_contents() options = {} remaining_bits = bits[1:] while remaining_bits: option = remaining_bits.pop(0) if option in options: raise TemplateSyntaxError('The %r option was specified more ' 'than once.' % option) if option == 'with': value = token_kwargs(remaining_bits, parser, support_legacy=True) if not value: raise TemplateSyntaxError('"with" in %r tag needs at least ' 'one keyword argument.' % bits[0]) elif option == 'count': value = token_kwargs(remaining_bits, parser, support_legacy=True) if len(value) != 1: raise TemplateSyntaxError('"count" in %r tag expected exactly ' 'one keyword argument.' % bits[0]) elif option == "context": try: value = remaining_bits.pop(0) value = parser.compile_filter(value) except Exception: msg = ( '"context" in %r tag expected ' 'exactly one argument.') % bits[0] six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2]) elif option == "trimmed": value = True else: raise TemplateSyntaxError('Unknown argument for %r tag: %r.' % (bits[0], option)) options[option] = value if 'count' in options: countervar, counter = list(six.iteritems(options['count']))[0] else: countervar, counter = None, None if 'context' in options: message_context = options['context'] else: message_context = None extra_context = options.get('with', {}) trimmed = options.get("trimmed", False) singular = [] plural = [] while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): singular.append(token) else: break if countervar and counter: if token.contents.strip() != 'plural': raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags inside it") while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): plural.append(token) else: break if token.contents.strip() != 'endblocktrans': raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents) return BlockTranslateNode(extra_context, singular, plural, countervar, counter, message_context, trimmed=trimmed) @register.tag def language(parser, token): """ This will enable the given language just for this block. Usage:: {% language "de" %} This is {{ bar }} and {{ boo }}. {% endlanguage %} """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0]) language = parser.compile_filter(bits[1]) nodelist = parser.parse(('endlanguage',)) parser.delete_first_token() return LanguageNode(nodelist, language)
apache-2.0
GauriGNaik/servo
components/script/dom/bindings/codegen/parser/tests/test_distinguishability.py
134
5560
def firstArgType(method): return method.signatures()[0][1][0].type def WebIDLTest(parser, harness): parser.parse(""" dictionary Dict { }; callback interface Foo { }; interface Bar { // Bit of a pain to get things that have dictionary types void passDict(optional Dict arg); void passFoo(Foo arg); void passNullableUnion((object? or DOMString) arg); void passNullable(Foo? arg); }; """) results = parser.finish() iface = results[2] harness.ok(iface.isInterface(), "Should have interface") dictMethod = iface.members[0] ifaceMethod = iface.members[1] nullableUnionMethod = iface.members[2] nullableIfaceMethod = iface.members[3] dictType = firstArgType(dictMethod) ifaceType = firstArgType(ifaceMethod) harness.ok(dictType.isDictionary(), "Should have dictionary type"); harness.ok(ifaceType.isInterface(), "Should have interface type"); harness.ok(ifaceType.isCallbackInterface(), "Should have callback interface type"); harness.ok(not dictType.isDistinguishableFrom(ifaceType), "Dictionary not distinguishable from callback interface") harness.ok(not ifaceType.isDistinguishableFrom(dictType), "Callback interface not distinguishable from dictionary") nullableUnionType = firstArgType(nullableUnionMethod) nullableIfaceType = firstArgType(nullableIfaceMethod) harness.ok(nullableUnionType.isUnion(), "Should have union type"); harness.ok(nullableIfaceType.isInterface(), "Should have interface type"); harness.ok(nullableIfaceType.nullable(), "Should have nullable type"); harness.ok(not nullableUnionType.isDistinguishableFrom(nullableIfaceType), "Nullable type not distinguishable from union with nullable " "member type") harness.ok(not nullableIfaceType.isDistinguishableFrom(nullableUnionType), "Union with nullable member type not distinguishable from " "nullable type") parser = parser.reset() parser.parse(""" interface TestIface { void passKid(Kid arg); void passParent(Parent arg); void passGrandparent(Grandparent arg); void passImplemented(Implemented arg); void passImplementedParent(ImplementedParent arg); void passUnrelated1(Unrelated1 arg); void passUnrelated2(Unrelated2 arg); void passArrayBuffer(ArrayBuffer arg); void passArrayBuffer(ArrayBufferView arg); }; interface Kid : Parent {}; interface Parent : Grandparent {}; interface Grandparent {}; interface Implemented : ImplementedParent {}; Parent implements Implemented; interface ImplementedParent {}; interface Unrelated1 {}; interface Unrelated2 {}; """) results = parser.finish() iface = results[0] harness.ok(iface.isInterface(), "Should have interface") argTypes = [firstArgType(method) for method in iface.members] unrelatedTypes = [firstArgType(method) for method in iface.members[-3:]] for type1 in argTypes: for type2 in argTypes: distinguishable = (type1 is not type2 and (type1 in unrelatedTypes or type2 in unrelatedTypes)) harness.check(type1.isDistinguishableFrom(type2), distinguishable, "Type %s should %sbe distinguishable from type %s" % (type1, "" if distinguishable else "not ", type2)) harness.check(type2.isDistinguishableFrom(type1), distinguishable, "Type %s should %sbe distinguishable from type %s" % (type2, "" if distinguishable else "not ", type1)) parser = parser.reset() parser.parse(""" interface Dummy {}; interface TestIface { void method(long arg1, TestIface arg2); void method(long arg1, long arg2); void method(long arg1, Dummy arg2); void method(DOMString arg1, DOMString arg2, DOMString arg3); }; """) results = parser.finish() harness.check(len(results[1].members), 1, "Should look like we have one method") harness.check(len(results[1].members[0].signatures()), 4, "Should have four signatures") parser = parser.reset() threw = False try: parser.parse(""" interface Dummy {}; interface TestIface { void method(long arg1, TestIface arg2); void method(long arg1, long arg2); void method(any arg1, Dummy arg2); void method(DOMString arg1, DOMString arg2, DOMString arg3); }; """) results = parser.finish() except: threw = True harness.ok(threw, "Should throw when args before the distinguishing arg are not " "all the same type") parser = parser.reset() threw = False try: parser.parse(""" interface Dummy {}; interface TestIface { void method(long arg1, TestIface arg2); void method(long arg1, long arg2); void method(any arg1, DOMString arg2); void method(DOMString arg1, DOMString arg2, DOMString arg3); }; """) results = parser.finish() except: threw = True harness.ok(threw, "Should throw when there is no distinguishing index")
mpl-2.0
jiangjinjinyxt/vnpy
vnpy/api/ksgold/pyscript/generate_td_functions.py
40
10308
# encoding: UTF-8 __author__ = 'CHENXY' from string import join from ksgold_struct import structDict def processCallBack(line): orignalLine = line line = line.replace('\tvirtual void ', '') # 删除行首的无效内容 line = line.replace('{};\n', '') # 删除行尾的无效内容 content = line.split('(') cbName = content[0] # 回调函数名称 cbArgs = content[1] # 回调函数参数 if cbArgs[-1] == ' ': cbArgs = cbArgs.replace(') ', '') else: cbArgs = cbArgs.replace(')', '') cbArgsList = cbArgs.split(', ') # 将每个参数转化为列表 cbArgsTypeList = [] cbArgsValueList = [] for arg in cbArgsList: # 开始处理参数 content = arg.split(' ') if len(content) > 1: cbArgsTypeList.append(content[0]) # 参数类型列表 cbArgsValueList.append(content[1]) # 参数数据列表 createTask(cbName, cbArgsTypeList, cbArgsValueList, orignalLine) createProcess(cbName, cbArgsTypeList, cbArgsValueList) # 生成.h文件中的process部分 process_line = 'void process' + cbName[2:] + '(Task task);\n' fheaderprocess.write(process_line) fheaderprocess.write('\n') # 生成.h文件中的on部分 if 'OnRspError' in cbName: on_line = 'virtual void on' + cbName[2:] + '(dict error, int id, bool last) {};\n' elif 'OnRsp' in cbName: on_line = 'virtual void on' + cbName[2:] + '(dict data, dict error, int id, bool last) {};\n' elif 'OnRtn' in cbName: on_line = 'virtual void on' + cbName[2:] + '(dict data) {};\n' elif 'OnErrRtn' in cbName: on_line = 'virtual void on' + cbName[2:] + '(dict data, dict error) {};\n' else: on_line = '' fheaderon.write(on_line) fheaderon.write('\n') # 生成封装部分 createWrap(cbName) #---------------------------------------------------------------------- def createWrap(cbName): """在Python封装段代码中进行处理""" # 生成.h文件中的on部分 if 'OnRspError' in cbName: on_line = 'virtual void on' + cbName[2:] + '(dict error, int id, bool last)\n' override_line = '("on' + cbName[2:] + '")(error, id, last);\n' elif 'OnRsp' in cbName: on_line = 'virtual void on' + cbName[2:] + '(dict data, dict error, int id, bool last)\n' override_line = '("on' + cbName[2:] + '")(data, error, id, last);\n' elif 'OnRtn' in cbName: on_line = 'virtual void on' + cbName[2:] + '(dict data)\n' override_line = '("on' + cbName[2:] + '")(data);\n' elif 'OnErrRtn' in cbName: on_line = 'virtual void on' + cbName[2:] + '(dict data, dict error)\n' override_line = '("on' + cbName[2:] + '")(data, error);\n' else: on_line = '' if on_line is not '': fwrap.write(on_line) fwrap.write('{\n') fwrap.write('\ttry\n') fwrap.write('\t{\n') fwrap.write('\t\tthis->get_override'+override_line) fwrap.write('\t}\n') fwrap.write('\tcatch (error_already_set const &)\n') fwrap.write('\t{\n') fwrap.write('\t\tPyErr_Print();\n') fwrap.write('\t}\n') fwrap.write('};\n') fwrap.write('\n') def createTask(cbName, cbArgsTypeList, cbArgsValueList, orignalLine): # 从回调函数生成任务对象,并放入队列 funcline = orignalLine.replace('\tvirtual void ', 'void ' + apiName + '::') funcline = funcline.replace('{};', '') ftask.write(funcline) ftask.write('{\n') ftask.write("\tTask task = Task();\n") ftask.write("\ttask.task_name = " + cbName.upper() + ";\n") # define常量 global define_count fdefine.write("#define " + cbName.upper() + ' ' + str(define_count) + '\n') define_count = define_count + 1 # switch段代码 fswitch.write("case " + cbName.upper() + ':\n') fswitch.write("{\n") fswitch.write("\tthis->" + cbName.replace('On', 'process') + '(task);\n') fswitch.write("\tbreak;\n") fswitch.write("}\n") fswitch.write("\n") for i, type_ in enumerate(cbArgsTypeList): if type_ == 'int': ftask.write("\ttask.task_id = " + cbArgsValueList[i] + ";\n") elif type_ == 'bool': ftask.write("\ttask.task_last = " + cbArgsValueList[i] + ";\n") elif 'RspInfoField' in type_: ftask.write("\n") ftask.write("\tif (pRspInfo)\n") ftask.write("\t{\n") ftask.write("\t\ttask.task_error = " + cbArgsValueList[i] + ";\n") ftask.write("\t}\n") ftask.write("\telse\n") ftask.write("\t{\n") ftask.write("\t\tCThostFtdcRspInfoField empty_error = CThostFtdcRspInfoField();\n") ftask.write("\t\tmemset(&empty_error, 0, sizeof(empty_error));\n") ftask.write("\t\ttask.task_error = empty_error;\n") ftask.write("\t}\n") else: ftask.write("\n") ftask.write("\tif (" + cbArgsValueList[i][1:] + ")\n") ftask.write("\t{\n") ftask.write("\t\ttask.task_data = " + cbArgsValueList[i] + ";\n") ftask.write("\t}\n") ftask.write("\telse\n") ftask.write("\t{\n") ftask.write("\t\t" + type_ + " empty_data = " + type_ + "();\n") ftask.write("\t\tmemset(&empty_data, 0, sizeof(empty_data));\n") ftask.write("\t\ttask.task_data = empty_data;\n") ftask.write("\t}\n") ftask.write("\tthis->task_queue.push(task);\n") ftask.write("};\n") ftask.write("\n") def createProcess(cbName, cbArgsTypeList, cbArgsValueList): # 从队列中提取任务,并转化为python字典 fprocess.write("void " + apiName + '::' + cbName.replace('On', 'process') + '(Task task)' + "\n") fprocess.write("{\n") fprocess.write("\tPyLock lock;\n") onArgsList = [] for i, type_ in enumerate(cbArgsTypeList): if 'RspInfoField' in type_: fprocess.write("\t"+ type_ + ' task_error = any_cast<' + type_ + '>(task.task_error);\n') fprocess.write("\t"+ "dict error;\n") struct = structDict[type_] for key in struct.keys(): fprocess.write("\t"+ 'error["' + key + '"] = task_error.' + key + ';\n') fprocess.write("\n") onArgsList.append('error') elif type_ in structDict: fprocess.write("\t"+ type_ + ' task_data = any_cast<' + type_ + '>(task.task_data);\n') fprocess.write("\t"+ "dict data;\n") struct = structDict[type_] for key in struct.keys(): fprocess.write("\t"+ 'data["' + key + '"] = task_data.' + key + ';\n') fprocess.write("\n") onArgsList.append('data') elif type_ == 'bool': onArgsList.append('task.task_last') elif type_ == 'int': onArgsList.append('task.task_id') onArgs = join(onArgsList, ', ') fprocess.write('\tthis->' + cbName.replace('On', 'on') + '(' + onArgs +');\n') fprocess.write("};\n") fprocess.write("\n") def processFunction(line): line = line.replace('\tvirtual int ', '') # 删除行首的无效内容 line = line.replace(') = 0;\n', '') # 删除行尾的无效内容 content = line.split('(') fcName = content[0] # 回调函数名称 fcArgs = content[1] # 回调函数参数 fcArgs = fcArgs.replace(')', '') fcArgsList = fcArgs.split(', ') # 将每个参数转化为列表 fcArgsTypeList = [] fcArgsValueList = [] for arg in fcArgsList: # 开始处理参数 content = arg.split(' ') if len(content) > 1: fcArgsTypeList.append(content[0]) # 参数类型列表 fcArgsValueList.append(content[1]) # 参数数据列表 if len(fcArgsTypeList)>0 and fcArgsTypeList[0] in structDict: createFunction(fcName, fcArgsTypeList, fcArgsValueList) # 生成.h文件中的主动函数部分 if 'Req' in fcName: req_line = 'int req' + fcName[3:] + '(dict req, int nRequestID);\n' fheaderfunction.write(req_line) fheaderfunction.write('\n') def createFunction(fcName, fcArgsTypeList, fcArgsValueList): type_ = fcArgsTypeList[0] struct = structDict[type_] ffunction.write('int TdApi::req' + fcName[3:] + '(dict req, int nRequestID)\n') ffunction.write('{\n') ffunction.write('\t' + type_ +' myreq = ' + type_ + '();\n') ffunction.write('\tmemset(&myreq, 0, sizeof(myreq));\n') for key, value in struct.items(): if value == 'string': line = '\tgetChar(req, "' + key + '", myreq.' + key + ');\n' elif value == 'int': line = '\tgetInt(req, "' + key + '", &myreq.' + key + ');\n' elif value == 'double': line = '\tgetDouble(req, "' + key + '", &myreq.' + key + ');\n' ffunction.write(line) ffunction.write('\tint i = this->api->' + fcName + '(&myreq, nRequestID);\n') ffunction.write('\treturn i;\n') ffunction.write('};\n') ffunction.write('\n') ######################################################### apiName = 'TdApi' fcpp = open('GoldTradeApi.h', 'r') ftask = open('ksgold_td_task.cpp', 'w') fprocess = open('ksgold_td_process.cpp', 'w') ffunction = open('ksgold_td_function.cpp', 'w') fdefine = open('ksgold_td_define.cpp', 'w') fswitch = open('ksgold_td_switch.cpp', 'w') fheaderprocess = open('ksgold_td_header_process.h', 'w') fheaderon = open('ksgold_td_header_on.h', 'w') fheaderfunction = open('ksgold_td_header_function.h', 'w') fwrap = open('ksgold_td_wrap.cpp', 'w') define_count = 1 for line in fcpp: if "\tvirtual void On" in line: processCallBack(line) elif "\tvirtual int" in line: processFunction(line) fcpp.close() ftask.close() fprocess.close() ffunction.close() fswitch.close() fdefine.close() fheaderprocess.close() fheaderon.close() fheaderfunction.close() fwrap.close()
mit
Grirrane/odoo
addons/l10n_ae/__openerp__.py
8
1512
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2014 Tech Receptives (<http://techreceptives.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': 'U.A.E. - Accounting', 'version': '1.0', 'author': 'Tech Receptives', 'website': 'http://www.techreceptives.com', 'category': 'Localization/Account Charts', 'description': """ United Arab Emirates accounting chart and localization. ======================================================= """, 'depends': ['base', 'account', 'account_chart'], 'demo': [ ], 'data': [ 'l10n_ae_chart.xml', 'l10n_ae_wizard.xml', ], 'installable': True, }
agpl-3.0
tgcion/code-Tigercon
share/qt/make_spinner.py
4415
1035
#!/usr/bin/env python # W.J. van der Laan, 2011 # Make spinning .mng animation from a .png # Requires imagemagick 6.7+ from __future__ import division from os import path from PIL import Image from subprocess import Popen SRC='img/reload_scaled.png' DST='../../src/qt/res/movies/update_spinner.mng' TMPDIR='/tmp' TMPNAME='tmp-%03i.png' NUMFRAMES=35 FRAMERATE=10.0 CONVERT='convert' CLOCKWISE=True DSIZE=(16,16) im_src = Image.open(SRC) if CLOCKWISE: im_src = im_src.transpose(Image.FLIP_LEFT_RIGHT) def frame_to_filename(frame): return path.join(TMPDIR, TMPNAME % frame) frame_files = [] for frame in xrange(NUMFRAMES): rotation = (frame + 0.5) / NUMFRAMES * 360.0 if CLOCKWISE: rotation = -rotation im_new = im_src.rotate(rotation, Image.BICUBIC) im_new.thumbnail(DSIZE, Image.ANTIALIAS) outfile = frame_to_filename(frame) im_new.save(outfile, 'png') frame_files.append(outfile) p = Popen([CONVERT, "-delay", str(FRAMERATE), "-dispose", "2"] + frame_files + [DST]) p.communicate()
mit
soapy/soapy
soapy/pyqtgraph/opengl/shaders.py
51
16009
try: from OpenGL import NullFunctionError except ImportError: from OpenGL.error import NullFunctionError from OpenGL.GL import * from OpenGL.GL import shaders import re ## For centralizing and managing vertex/fragment shader programs. def initShaders(): global Shaders Shaders = [ ShaderProgram(None, []), ## increases fragment alpha as the normal turns orthogonal to the view ## this is useful for viewing shells that enclose a volume (such as isosurfaces) ShaderProgram('balloon', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_NormalMatrix * gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { vec4 color = gl_Color; color.w = min(color.w + 2.0 * color.w * pow(normal.x*normal.x + normal.y*normal.y, 5.0), 1.0); gl_FragColor = color; } """) ]), ## colors fragments based on face normals relative to view ## This means that the colors will change depending on how the view is rotated ShaderProgram('viewNormalColor', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_NormalMatrix * gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { vec4 color = gl_Color; color.x = (normal.x + 1.0) * 0.5; color.y = (normal.y + 1.0) * 0.5; color.z = (normal.z + 1.0) * 0.5; gl_FragColor = color; } """) ]), ## colors fragments based on absolute face normals. ShaderProgram('normalColor', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { vec4 color = gl_Color; color.x = (normal.x + 1.0) * 0.5; color.y = (normal.y + 1.0) * 0.5; color.z = (normal.z + 1.0) * 0.5; gl_FragColor = color; } """) ]), ## very simple simulation of lighting. ## The light source position is always relative to the camera. ShaderProgram('shaded', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_NormalMatrix * gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { float p = dot(normal, normalize(vec3(1.0, -1.0, -1.0))); p = p < 0. ? 0. : p * 0.8; vec4 color = gl_Color; color.x = color.x * (0.2 + p); color.y = color.y * (0.2 + p); color.z = color.z * (0.2 + p); gl_FragColor = color; } """) ]), ## colors get brighter near edges of object ShaderProgram('edgeHilight', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_NormalMatrix * gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { vec4 color = gl_Color; float s = pow(normal.x*normal.x + normal.y*normal.y, 2.0); color.x = color.x + s * (1.0-color.x); color.y = color.y + s * (1.0-color.y); color.z = color.z + s * (1.0-color.z); gl_FragColor = color; } """) ]), ## colors fragments by z-value. ## This is useful for coloring surface plots by height. ## This shader uses a uniform called "colorMap" to determine how to map the colors: ## red = pow(z * colorMap[0] + colorMap[1], colorMap[2]) ## green = pow(z * colorMap[3] + colorMap[4], colorMap[5]) ## blue = pow(z * colorMap[6] + colorMap[7], colorMap[8]) ## (set the values like this: shader['uniformMap'] = array([...]) ShaderProgram('heightColor', [ VertexShader(""" varying vec4 pos; void main() { gl_FrontColor = gl_Color; gl_BackColor = gl_Color; pos = gl_Vertex; gl_Position = ftransform(); } """), FragmentShader(""" uniform float colorMap[9]; varying vec4 pos; //out vec4 gl_FragColor; // only needed for later glsl versions //in vec4 gl_Color; void main() { vec4 color = gl_Color; color.x = colorMap[0] * (pos.z + colorMap[1]); if (colorMap[2] != 1.0) color.x = pow(color.x, colorMap[2]); color.x = color.x < 0. ? 0. : (color.x > 1. ? 1. : color.x); color.y = colorMap[3] * (pos.z + colorMap[4]); if (colorMap[5] != 1.0) color.y = pow(color.y, colorMap[5]); color.y = color.y < 0. ? 0. : (color.y > 1. ? 1. : color.y); color.z = colorMap[6] * (pos.z + colorMap[7]); if (colorMap[8] != 1.0) color.z = pow(color.z, colorMap[8]); color.z = color.z < 0. ? 0. : (color.z > 1. ? 1. : color.z); color.w = 1.0; gl_FragColor = color; } """), ], uniforms={'colorMap': [1, 1, 1, 1, 0.5, 1, 1, 0, 1]}), ShaderProgram('pointSprite', [ ## allows specifying point size using normal.x ## See: ## ## http://stackoverflow.com/questions/9609423/applying-part-of-a-texture-sprite-sheet-texture-map-to-a-point-sprite-in-ios ## http://stackoverflow.com/questions/3497068/textured-points-in-opengl-es-2-0 ## ## VertexShader(""" void main() { gl_FrontColor=gl_Color; gl_PointSize = gl_Normal.x; gl_Position = ftransform(); } """), #FragmentShader(""" ##version 120 #uniform sampler2D texture; #void main ( ) #{ #gl_FragColor = texture2D(texture, gl_PointCoord) * gl_Color; #} #""") ]), ] CompiledShaderPrograms = {} def getShaderProgram(name): return ShaderProgram.names[name] class Shader(object): def __init__(self, shaderType, code): self.shaderType = shaderType self.code = code self.compiled = None def shader(self): if self.compiled is None: try: self.compiled = shaders.compileShader(self.code, self.shaderType) except NullFunctionError: raise Exception("This OpenGL implementation does not support shader programs; many OpenGL features in pyqtgraph will not work.") except RuntimeError as exc: ## Format compile errors a bit more nicely if len(exc.args) == 3: err, code, typ = exc.args if not err.startswith('Shader compile failure'): raise code = code[0].decode('utf_8').split('\n') err, c, msgs = err.partition(':') err = err + '\n' msgs = re.sub('b\'','',msgs) msgs = re.sub('\'$','',msgs) msgs = re.sub('\\\\n','\n',msgs) msgs = msgs.split('\n') errNums = [()] * len(code) for i, msg in enumerate(msgs): msg = msg.strip() if msg == '': continue m = re.match(r'(\d+\:)?\d+\((\d+)\)', msg) if m is not None: line = int(m.groups()[1]) errNums[line-1] = errNums[line-1] + (str(i+1),) #code[line-1] = '%d\t%s' % (i+1, code[line-1]) err = err + "%d %s\n" % (i+1, msg) errNums = [','.join(n) for n in errNums] maxlen = max(map(len, errNums)) code = [errNums[i] + " "*(maxlen-len(errNums[i])) + line for i, line in enumerate(code)] err = err + '\n'.join(code) raise Exception(err) else: raise return self.compiled class VertexShader(Shader): def __init__(self, code): Shader.__init__(self, GL_VERTEX_SHADER, code) class FragmentShader(Shader): def __init__(self, code): Shader.__init__(self, GL_FRAGMENT_SHADER, code) class ShaderProgram(object): names = {} def __init__(self, name, shaders, uniforms=None): self.name = name ShaderProgram.names[name] = self self.shaders = shaders self.prog = None self.blockData = {} self.uniformData = {} ## parse extra options from the shader definition if uniforms is not None: for k,v in uniforms.items(): self[k] = v def setBlockData(self, blockName, data): if data is None: del self.blockData[blockName] else: self.blockData[blockName] = data def setUniformData(self, uniformName, data): if data is None: del self.uniformData[uniformName] else: self.uniformData[uniformName] = data def __setitem__(self, item, val): self.setUniformData(item, val) def __delitem__(self, item): self.setUniformData(item, None) def program(self): if self.prog is None: try: compiled = [s.shader() for s in self.shaders] ## compile all shaders self.prog = shaders.compileProgram(*compiled) ## compile program except: self.prog = -1 raise return self.prog def __enter__(self): if len(self.shaders) > 0 and self.program() != -1: glUseProgram(self.program()) try: ## load uniform values into program for uniformName, data in self.uniformData.items(): loc = self.uniform(uniformName) if loc == -1: raise Exception('Could not find uniform variable "%s"' % uniformName) glUniform1fv(loc, len(data), data) ### bind buffer data to program blocks #if len(self.blockData) > 0: #bindPoint = 1 #for blockName, data in self.blockData.items(): ### Program should have a uniform block declared: ### ### layout (std140) uniform blockName { ### vec4 diffuse; ### }; ### pick any-old binding point. (there are a limited number of these per-program #bindPoint = 1 ### get the block index for a uniform variable in the shader #blockIndex = glGetUniformBlockIndex(self.program(), blockName) ### give the shader block a binding point #glUniformBlockBinding(self.program(), blockIndex, bindPoint) ### create a buffer #buf = glGenBuffers(1) #glBindBuffer(GL_UNIFORM_BUFFER, buf) #glBufferData(GL_UNIFORM_BUFFER, size, data, GL_DYNAMIC_DRAW) ### also possible to use glBufferSubData to fill parts of the buffer ### bind buffer to the same binding point #glBindBufferBase(GL_UNIFORM_BUFFER, bindPoint, buf) except: glUseProgram(0) raise def __exit__(self, *args): if len(self.shaders) > 0: glUseProgram(0) def uniform(self, name): """Return the location integer for a uniform variable in this program""" return glGetUniformLocation(self.program(), name.encode('utf_8')) #def uniformBlockInfo(self, blockName): #blockIndex = glGetUniformBlockIndex(self.program(), blockName) #count = glGetActiveUniformBlockiv(self.program(), blockIndex, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS) #indices = [] #for i in range(count): #indices.append(glGetActiveUniformBlockiv(self.program(), blockIndex, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES)) class HeightColorShader(ShaderProgram): def __enter__(self): ## Program should have a uniform block declared: ## ## layout (std140) uniform blockName { ## vec4 diffuse; ## vec4 ambient; ## }; ## pick any-old binding point. (there are a limited number of these per-program bindPoint = 1 ## get the block index for a uniform variable in the shader blockIndex = glGetUniformBlockIndex(self.program(), "blockName") ## give the shader block a binding point glUniformBlockBinding(self.program(), blockIndex, bindPoint) ## create a buffer buf = glGenBuffers(1) glBindBuffer(GL_UNIFORM_BUFFER, buf) glBufferData(GL_UNIFORM_BUFFER, size, data, GL_DYNAMIC_DRAW) ## also possible to use glBufferSubData to fill parts of the buffer ## bind buffer to the same binding point glBindBufferBase(GL_UNIFORM_BUFFER, bindPoint, buf) initShaders()
gpl-3.0
gdetor/SI-RF-Structure
Statistics/clear_data.py
1
5369
# Copyright (c) 2014, Georgios Is. Detorakis (gdetor@gmail.com) and # Nicolas P. Rougier (nicolas.rougier@inria.fr) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder 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 HOLDER 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. # # This file is part of the source code accompany the peer-reviewed article: # [1] "Structure of Receptive Fields in a Computational Model of Area 3b of # Primary Sensory Cortex", Georgios Is. Detorakis and Nicolas P. Rougier, # Frontiers in Computational Neuroscience, 2014. # # This script applies all the filters and cleaning techniques to the ncRFs. You # have to use this script before any further statistical analysis to the data. import numpy as np from matplotlib import rc import matplotlib.pylab as plt from scipy.stats.stats import pearsonr from scipy.stats.mstats import gmean from scipy.ndimage import gaussian_filter def locate_noise( input ): n = input.shape[0] data = input.copy() count = 0 for i in range( 1,n-1 ): for j in range( 1,n-1 ): if data[i,j] != 0: if data[i+1,j] != 0 and np.sign(data[i+1,j])==np.sign(data[i,j]): count += 1 if data[i-1,j] != 0 and np.sign(data[i-1,j])==np.sign(data[i,j]): count += 1 if data[i,j-1] != 0 and np.sign(data[i,j-1])==np.sign(data[i,j]): count += 1 if data[i,j+1] != 0 and np.sign(data[i,j+1])==np.sign(data[i,j]): count += 1 if count < 2: data[i,j] = 0 count = 0 return data # Computing the area of the receptive fields according to Dicarlo's # protocol described in article "Structure of Receptive Fields in area 3b... def clear_data( RFs, n ): p = 25 Z, T = [], [] Noise = np.load( 'noise.npy' ).reshape(n*n,p,p) cRFs = np.zeros((n*n,p,p)) for i in range( n ): for j in range( n ): RF = RFs[i,j,...] # WARNING : Centering the RF s0,s1 = np.unravel_index(np.argmax(RF),RF.shape) RF = np.roll(RF,13-s0,axis=0) RF = np.roll(RF,13-s1,axis=1) # WARNING : Centering the RF # RF += Noise[i*n+j] # RF = gaussian_filter( RF, sigma=2.2 ) RF += 1.5*Noise[i*n+j] RF = gaussian_filter( RF, sigma=1.5 ) abs_max = np.max( np.abs( RF ) ) RF[np.where( ( ( RF < +0.10*abs_max ) & (RF>0) ) | ( ( RF > -0.10*abs_max ) & (RF < 0) ) ) ]=0 RF = locate_noise( RF ) cRFs[i*n+j,...] = RF exc = 50.0 * ( RF > 0).sum()/( p * p ) inh = 50.0 * ( RF < 0).sum()/( p * p ) Z.append([exc,inh]) Z = np.array(Z) np.nan_to_num(Z) print '------ Excitatory ------- Inhibitory -------' print 'Minimum :', Z[:,0].min(), Z[:,1].min() print 'Maximum :', Z[:,0].max(), Z[:,1].max() print 'Mean :', np.mean( Z[:,0] ), np.mean( Z[:,1] ) print 'Mean :', np.mean( np.log10(Z[:,0]) ), np.mean( np.log10(Z[:,1]) ) print 'SD : ', np.std( np.log10(Z[:,0]) ), np.std( np.log10(Z[:,1]) ) print 'GMean :', gmean( Z[:,0] ), gmean( Z[:,1] ) print "Pearson cor: ", pearsonr( Z[:,0], np.abs(Z[:,1]) ) return Z, cRFs # Computing the SNR of the receptive fields. def snr( signal, sigma ): k = signal.shape[0] # Filtering the input signal filtered_s = gaussian_filter( signal, sigma ) # Computing background noise noise = signal - filtered_s # Computing noise variance noise_var = np.var( noise ) # Computing signal and noise power signalPow = np.sum( signal**2 )/k noisePow = np.sum( noise**2 )/k # Computing snr and noise index snr = 10.0 * np.log10( signalPow/noisePow ) noise_index = noise_var/np.abs(signal).max() *100.0 return snr, noise_index, filtered_s # Main :p if __name__=='__main__': np.random.seed(137) RFs = np.load('real-rfs-ref.npy').reshape(32,32,25,25) n, size, bins = RFs.shape[0], RFs.shape[2], 70 Z, cRFs = clear_data( RFs, n ) np.save('areas-ref', Z) np.save('cleared-rfs', cRFs)
gpl-3.0
stewartsmith/bzr
bzrlib/_rio_py.py
2
2703
# Copyright (C) 2009 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 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 """Python implementation of _read_stanza_*.""" from __future__ import absolute_import import re from bzrlib.rio import ( Stanza, ) _tag_re = re.compile(r'^[-a-zA-Z0-9_]+$') def _valid_tag(tag): if type(tag) != str: raise TypeError(tag) return bool(_tag_re.match(tag)) def _read_stanza_utf8(line_iter): def iter_unicode_lines(): for line in line_iter: if type(line) != str: raise TypeError(line) yield line.decode('utf-8') return _read_stanza_unicode(iter_unicode_lines()) def _read_stanza_unicode(unicode_iter): stanza = Stanza() tag = None accum_value = None # TODO: jam 20060922 This code should raise real errors rather than # using 'assert' to process user input, or raising ValueError # rather than a more specific error. for line in unicode_iter: if line is None or line == u'': break # end of file if line == u'\n': break # end of stanza real_l = line if line[0] == u'\t': # continues previous value if tag is None: raise ValueError('invalid continuation line %r' % real_l) accum_value.append(u'\n' + line[1:-1]) else: # new tag:value line if tag is not None: stanza.add(tag, u''.join(accum_value)) try: colon_index = line.index(u': ') except ValueError: raise ValueError('tag/value separator not found in line %r' % real_l) tag = str(line[:colon_index]) if not _valid_tag(tag): raise ValueError("invalid rio tag %r" % (tag,)) accum_value = [line[colon_index+2:-1]] if tag is not None: # add last tag-value stanza.add(tag, u''.join(accum_value)) return stanza else: # didn't see any content return None
gpl-2.0
Vegasvikk/django-cms
cms/signals/apphook.py
12
3522
# -*- coding: utf-8 -*- import sys from django.core.management import color_style from django.core.urlresolvers import clear_url_caches from django.core.signals import request_finished from cms.models import Title DISPATCH_UID = 'cms-restart' def apphook_pre_title_checker(instance, **kwargs): """ Store the old application_urls and path on the instance """ if instance.publisher_is_draft: return try: instance._old_data = Title.objects.filter(pk=instance.pk).select_related('page')[0] except IndexError: instance._old_data = None def apphook_post_page_checker(page): old_page = page.old_page if (old_page and ( old_page.application_urls != page.application_urls or old_page.application_namespace != page.application_namespace)) or ( not old_page and page.application_urls): from cms.cache import invalidate_cms_page_cache invalidate_cms_page_cache() request_finished.connect(trigger_restart, dispatch_uid=DISPATCH_UID) def apphook_post_title_checker(instance, **kwargs): """ Check if applciation_urls and path changed on the instance """ if instance.publisher_is_draft: return old_title = getattr(instance, '_old_data', None) if not old_title: if instance.page.application_urls: request_finished.connect( trigger_restart, dispatch_uid=DISPATCH_UID ) else: old_values = ( old_title.published, old_title.page.application_urls, old_title.page.application_namespace, old_title.path, old_title.slug, ) new_values = ( instance.published, instance.page.application_urls, instance.page.application_namespace, instance.path, instance.slug, ) if old_values != new_values and (old_values[2] or new_values[2]): request_finished.connect(trigger_restart, dispatch_uid=DISPATCH_UID) def apphook_post_delete_title_checker(instance, **kwargs): """ Check if this was an apphook """ from cms.cache import invalidate_cms_page_cache invalidate_cms_page_cache() if instance.page.application_urls: request_finished.connect(trigger_restart, dispatch_uid=DISPATCH_UID) def apphook_post_delete_page_checker(instance, **kwargs): """ Check if this was an apphook """ if instance.application_urls: request_finished.connect(trigger_restart, dispatch_uid=DISPATCH_UID) # import the logging library import logging # Get an instance of a logger logger = logging.getLogger(__name__) def trigger_restart(**kwargs): from cms.signals import urls_need_reloading request_finished.disconnect(trigger_restart, dispatch_uid=DISPATCH_UID) urls_need_reloading.send(sender=None) def debug_server_restart(**kwargs): from cms.appresolver import clear_app_resolvers if 'runserver' in sys.argv or 'server' in sys.argv: clear_app_resolvers() clear_url_caches() import cms.urls try: reload(cms.urls) except NameError: #python3 from imp import reload reload(cms.urls) if not 'test' in sys.argv: msg = 'Application url changed and urls_need_reloading signal fired. Please reload the urls.py or restart the server\n' styles = color_style() msg = styles.NOTICE(msg) sys.stderr.write(msg)
bsd-3-clause
cheral/orange3
doc/development/source/orange-demo/orangedemo/OWLearningCurveB.py
2
13882
import sys from collections import OrderedDict from functools import reduce import numpy import sklearn.cross_validation from PyQt4.QtGui import QTableWidget, QTableWidgetItem import Orange.data import Orange.classification from Orange.widgets import widget, gui, settings from Orange.evaluation.testing import Results class OWLearningCurveB(widget.OWWidget): name = "Learning Curve (B)" description = ("Takes a data set and a set of learners and shows a " "learning curve in a table") icon = "icons/LearningCurve.svg" priority = 1010 # [start-snippet-1] inputs = [("Data", Orange.data.Table, "set_dataset", widget.Default), ("Test Data", Orange.data.Table, "set_testdataset"), ("Learner", Orange.classification.Learner, "set_learner", widget.Multiple + widget.Default)] # [end-snippet-1] #: cross validation folds folds = settings.Setting(5) #: points in the learning curve steps = settings.Setting(10) #: index of the selected scoring function scoringF = settings.Setting(0) #: compute curve on any change of parameters commitOnChange = settings.Setting(True) def __init__(self): super().__init__() # sets self.curvePoints, self.steps equidistant points from # 1/self.steps to 1 self.updateCurvePoints() self.scoring = [ ("Classification Accuracy", Orange.evaluation.scoring.CA), ("AUC", Orange.evaluation.scoring.AUC), ("Precision", Orange.evaluation.scoring.Precision), ("Recall", Orange.evaluation.scoring.Recall) ] #: input data on which to construct the learning curve self.data = None #: optional test data self.testdata = None #: A {input_id: Learner} mapping of current learners from input channel self.learners = OrderedDict() #: A {input_id: List[Results]} mapping of input id to evaluation #: results list, one for each curve point self.results = OrderedDict() #: A {input_id: List[float]} mapping of input id to learning curve #: point scores self.curves = OrderedDict() # GUI box = gui.widgetBox(self.controlArea, "Info") self.infoa = gui.widgetLabel(box, 'No data on input.') self.infob = gui.widgetLabel(box, 'No learners.') gui.separator(self.controlArea) box = gui.widgetBox(self.controlArea, "Evaluation Scores") gui.comboBox(box, self, "scoringF", items=[x[0] for x in self.scoring], callback=self._invalidate_curves) gui.separator(self.controlArea) box = gui.widgetBox(self.controlArea, "Options") gui.spin(box, self, 'folds', 2, 100, step=1, label='Cross validation folds: ', keyboardTracking=False, callback=lambda: self._invalidate_results() if self.commitOnChange else None ) gui.spin(box, self, 'steps', 2, 100, step=1, label='Learning curve points: ', keyboardTracking=False, callback=[self.updateCurvePoints, lambda: self._invalidate_results() if self.commitOnChange else None]) gui.checkBox(box, self, 'commitOnChange', 'Apply setting on any change') self.commitBtn = gui.button(box, self, "Apply Setting", callback=self._invalidate_results, disabled=True) gui.rubber(self.controlArea) # table widget self.table = gui.table(self.mainArea, selectionMode=QTableWidget.NoSelection) ########################################################################## # slots: handle input signals def set_dataset(self, data): """Set the input train dataset.""" # Clear all results/scores for id in list(self.results): self.results[id] = None for id in list(self.curves): self.curves[id] = None self.data = data if data is not None: self.infoa.setText('%d instances in input data set' % len(data)) else: self.infoa.setText('No data on input.') self.commitBtn.setEnabled(self.data is not None) def set_testdataset(self, testdata): """Set a separate test dataset.""" # Clear all results/scores for id in list(self.results): self.results[id] = None for id in list(self.curves): self.curves[id] = None self.testdata = testdata def set_learner(self, learner, id): """Set the input learner for channel id.""" if id in self.learners: if learner is None: # remove a learner and corresponding results del self.learners[id] del self.results[id] del self.curves[id] else: # update/replace a learner on a previously connected link self.learners[id] = learner # invalidate the cross-validation results and curve scores # (will be computed/updated in `_update`) self.results[id] = None self.curves[id] = None else: if learner is not None: self.learners[id] = learner # initialize the cross-validation results and curve scores # (will be computed/updated in `_update`) self.results[id] = None self.curves[id] = None if len(self.learners): self.infob.setText("%d learners on input." % len(self.learners)) else: self.infob.setText("No learners.") self.commitBtn.setEnabled(len(self.learners)) def handleNewSignals(self): if self.data is not None: self._update() self._update_curve_points() self._update_table() def _invalidate_curves(self): if self.data is not None: self._update_curve_points() self._update_table() def _invalidate_results(self): for id in self.learners: self.curves[id] = None self.results[id] = None if self.data is not None: self._update() self._update_curve_points() self._update_table() def _update(self): assert self.data is not None # collect all learners for which results have not yet been computed need_update = [(id, learner) for id, learner in self.learners.items() if self.results[id] is None] if not need_update: return learners = [learner for _, learner in need_update] self.progressBarInit() if self.testdata is None: # compute the learning curve result for all learners in one go results = learning_curve( learners, self.data, folds=self.folds, proportions=self.curvePoints, callback=lambda value: self.progressBarSet(100 * value) ) else: results = learning_curve_with_test_data( learners, self.data, self.testdata, times=self.folds, proportions=self.curvePoints, callback=lambda value: self.progressBarSet(100 * value) ) self.progressBarFinished() # split the combined result into per learner/model results results = [list(Results.split_by_model(p_results)) for p_results in results] for i, (id, learner) in enumerate(need_update): self.results[id] = [p_results[i] for p_results in results] def _update_curve_points(self): for id in self.learners: curve = [self.scoring[self.scoringF][1](x)[0] for x in self.results[id]] self.curves[id] = curve def _update_table(self): self.table.setRowCount(0) self.table.setRowCount(len(self.curvePoints)) self.table.setColumnCount(len(self.learners)) self.table.setHorizontalHeaderLabels( [learner.name for _, learner in self.learners.items()]) self.table.setVerticalHeaderLabels( ["{:.2f}".format(p) for p in self.curvePoints]) if self.data is None: return for column, curve in enumerate(self.curves.values()): for row, point in enumerate(curve): self.table.setItem( row, column, QTableWidgetItem("{:.5f}".format(point))) for i in range(len(self.learners)): sh = self.table.sizeHintForColumn(i) cwidth = self.table.columnWidth(i) self.table.setColumnWidth(i, max(sh, cwidth)) def updateCurvePoints(self): self.curvePoints = [(x + 1.)/self.steps for x in range(self.steps)] def learning_curve(learners, data, folds=10, proportions=None, random_state=None, callback=None): if proportions is None: proportions = numpy.linspace(0.0, 1.0, 10 + 1, endpoint=True)[1:] def select_proportion_preproc(data, p, rstate=None): assert 0 < p <= 1 rstate = numpy.random.RandomState(None) if rstate is None else rstate indices = rstate.permutation(len(data)) n = int(numpy.ceil(len(data) * p)) return data[indices[:n]] if callback is not None: parts_count = len(proportions) callback_wrapped = lambda part: \ lambda value: callback(value / parts_count + part / parts_count) else: callback_wrapped = lambda part: None results = [ Orange.evaluation.CrossValidation( data, learners, k=folds, preprocessor=lambda data, p=p: select_proportion_preproc(data, p), callback=callback_wrapped(i) ) for i, p in enumerate(proportions) ] return results def learning_curve_with_test_data(learners, traindata, testdata, times=10, proportions=None, random_state=None, callback=None): if proportions is None: proportions = numpy.linspace(0.0, 1.0, 10 + 1, endpoint=True)[1:] def select_proportion_preproc(data, p, rstate=None): assert 0 < p <= 1 rstate = numpy.random.RandomState(None) if rstate is None else rstate indices = rstate.permutation(len(data)) n = int(numpy.ceil(len(data) * p)) return data[indices[:n]] if callback is not None: parts_count = len(proportions) * times callback_wrapped = lambda part: \ lambda value: callback(value / parts_count + part / parts_count) else: callback_wrapped = lambda part: None results = [ [Orange.evaluation.TestOnTestData( traindata, testdata, learners, preprocessor=lambda data, p=p: select_proportion_preproc(data, p), callback=callback_wrapped(i * times + t)) for t in range(times)] for i, p in enumerate(proportions) ] results = [reduce(results_add, res, Orange.evaluation.Results()) for res in results] return results def results_add(x, y): def is_empty(res): return (getattr(res, "models", None) is None and getattr(res, "row_indices", None) is None) if is_empty(x): return y elif is_empty(y): return x assert x.data is y.data assert x.domain is y.domain assert x.predicted.shape[0] == y.predicted.shape[0] row_indices = numpy.hstack((x.row_indices, y.row_indices)) predicted = numpy.hstack((x.predicted, y.predicted)) actual = numpy.hstack((x.actual, y.actual)) xprob = getattr(x, "probabilities", None) yprob = getattr(y, "probabilities", None) if xprob is None and yprob is None: prob = None elif xprob is not None and yprob is not None: prob = numpy.concatenate((xprob, yprob), axis=1) else: raise ValueError() res = Orange.evaluation.Results() res.data = x.data res.domain = x.domain res.row_indices = row_indices res.actual = actual res.predicted = predicted res.folds = None if prob is not None: res.probabilities = prob if x.models is not None and y.models is not None: res.models = [xm + ym for xm, ym in zip(x.models, y.models)] nmodels = predicted.shape[0] xfailed = getattr(x, "failed", None) or [False] * nmodels yfailed = getattr(y, "failed", None) or [False] * nmodels assert len(xfailed) == len(yfailed) res.failed = [xe or ye for xe, ye in zip(xfailed, yfailed)] return res def main(argv=sys.argv): from PyQt4.QtGui import QApplication app = QApplication(argv) argv = app.argv() if len(argv) > 1: filename = argv[1] else: filename = "iris" data = Orange.data.Table(filename) indices = numpy.random.permutation(len(data)) traindata = data[indices[:-20]] testdata = data[indices[-20:]] ow = OWLearningCurveB() ow.show() ow.raise_() ow.set_dataset(traindata) ow.set_testdataset(testdata) l1 = Orange.classification.NaiveBayesLearner() l1.name = 'Naive Bayes' ow.set_learner(l1, 1) l2 = Orange.classification.LogisticRegressionLearner() l2.name = 'Logistic Regression' ow.set_learner(l2, 2) l4 = Orange.classification.SklTreeLearner() l4.name = "Decision Tree" ow.set_learner(l4, 3) ow.handleNewSignals() app.exec_() ow.set_dataset(None) ow.set_testdataset(None) ow.set_learner(None, 1) ow.set_learner(None, 2) ow.set_learner(None, 3) ow.handleNewSignals() return 0 if __name__=="__main__": sys.exit(main())
bsd-2-clause
josjevv/django-cms
cms/south_migrations/0054_new_publisher_data.py
63
20437
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): for page in orm['cms.Page'].objects.filter(publisher_is_draft=True): titles = page.title_set.all() languages = [] pub_page = page.publisher_public if pub_page: pub_titles = pub_page.title_set.all() else: pub_titles = [] for title in titles: title.published = page.published title.publisher_is_draft = page.publisher_is_draft for pub_title in pub_titles: if pub_title.language == title.language: title.publisher_public = pub_title pub_title.publisher_public = title title.publisher_state = page.publisher_state languages.append(title.language) title.save() pub_languages = [] for title in pub_titles: title.published = pub_page.published title.publisher_is_draft = pub_page.publisher_is_draft title.publisher_state = pub_page.publisher_state title.save() pub_languages.append(title.language) if page.published: page.published_languages = ",".join(languages) page.languages = ",".join(languages) page.save() if pub_page and pub_languages: pub_page.languages = ",".join(pub_languages) pub_page.save() def backwards(self, orm): for page in orm['cms.Page'].objects.filter(publisher_is_draft=True): titles = page.title_set.all() pub_page = page.publisher_public if pub_page: pub_titles = pub_page.title_set.all() else: pub_titles = [] for title in titles: page.published = title.published page.publisher_state = title.publisher_state page.save() break for title in pub_titles: pub_page.published = title.published pub_page.publisher_state = title.publisher_state pub_page.save() break models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'cms.cmsplugin': { 'Meta': {'object_name': 'CMSPlugin'}, 'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}), 'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}), 'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}), 'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.globalpagepermission': { 'Meta': {'object_name': 'GlobalPagePermission'}, 'can_add': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change_advanced_settings': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_change_permissions': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_delete': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_move_page': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_publish': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_recover_page': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_view': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'sites': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['sites.Site']", 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'cms.page': { 'Meta': {'ordering': "('tree_id', 'lft')", 'unique_together': "(('publisher_is_draft', 'application_namespace'),)", 'object_name': 'Page'}, 'application_namespace': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'application_urls': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'changed_by': ('django.db.models.fields.CharField', [], {'max_length': '70'}), 'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.CharField', [], {'max_length': '70'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_navigation': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'is_home': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'languages': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'limit_visibility_in_menu': ('django.db.models.fields.SmallIntegerField', [], {'default': 'None', 'null': 'True', 'db_index': 'True', 'blank': 'True'}), 'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'navigation_extenders': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '80', 'null': 'True', 'blank': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['cms.Page']"}), 'placeholders': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['cms.Placeholder']", 'symmetrical': 'False'}), 'publication_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'publication_end_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'published_languages': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'publisher_is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'publisher_public': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Page']"}), 'publisher_state': ('django.db.models.fields.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}), 'reverse_id': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '40', 'null': 'True', 'blank': 'True'}), 'revision_id': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'djangocms_pages'", 'to': u"orm['sites.Site']"}), 'soft_root': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'template': ('django.db.models.fields.CharField', [], {'default': "'INHERIT'", 'max_length': '100'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.pagemoderatorstate': { 'Meta': {'ordering': "('page', 'action', '-created')", 'object_name': 'PageModeratorState'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {'default': "''", 'max_length': '1000', 'blank': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Page']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True'}) }, 'cms.pagepermission': { 'Meta': {'object_name': 'PagePermission'}, 'can_add': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change_advanced_settings': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_change_permissions': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_delete': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_move_page': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_publish': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_view': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'grant_on': ('django.db.models.fields.IntegerField', [], {'default': '5'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Page']", 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'cms.pageuser': { 'Meta': {'object_name': 'PageUser', '_ormbases': [u'auth.User']}, 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_users'", 'to': u"orm['auth.User']"}), u'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}) }, 'cms.pageusergroup': { 'Meta': {'object_name': 'PageUserGroup', '_ormbases': [u'auth.Group']}, 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_usergroups'", 'to': u"orm['auth.User']"}), u'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}) }, 'cms.placeholder': { 'Meta': {'object_name': 'Placeholder'}, 'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}) }, 'cms.placeholderreference': { 'Meta': {'object_name': 'PlaceholderReference', 'db_table': "u'cmsplugin_placeholderreference'", '_ormbases': ['cms.CMSPlugin']}, u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'placeholder_ref': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}) }, 'cms.staticplaceholder': { 'Meta': {'object_name': 'StaticPlaceholder'}, 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'blank': 'True'}), 'creation_method': ('django.db.models.fields.CharField', [], {'default': "'code'", 'max_length': '20', 'blank': 'True'}), 'dirty': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'draft': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'static_draft'", 'null': 'True', 'to': "orm['cms.Placeholder']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), 'public': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'static_public'", 'null': 'True', 'to': "orm['cms.Placeholder']"}) }, 'cms.title': { 'Meta': {'unique_together': "(('language', 'page'),)", 'object_name': 'Title'}, 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'has_url_overwrite': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'menu_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'meta_description': ('django.db.models.fields.TextField', [], {'max_length': '155', 'null': 'True', 'blank': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'title_set'", 'to': "orm['cms.Page']"}), 'page_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'publisher_is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'publisher_public': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Title']"}), 'publisher_state': ('django.db.models.fields.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}), 'redirect': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'cms.usersettings': { 'Meta': {'object_name': 'UserSettings'}, 'clipboard': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'djangocms_usersettings'", 'to': u"orm['auth.User']"}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'sites.site': { 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['cms'] symmetrical = True
bsd-3-clause
hujiajie/pa-chromium
chrome/app/nibs/PRESUBMIT.py
126
3062
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script to verify that XIB changes are done with the right version. See http://dev.chromium.org/developers/design-documents/mac-xib-files for more information. """ import re # Minimum is Mac OS X 10.8.1 (12B19). HUMAN_DARWIN_VERSION = '10.8.x, x >= 1' ALLOWED_DARWIN_VERSION = 12 # Darwin 12 = 10.8. MINIMUM_DARWIN_RELEASE = 'B' # Release B = 10.8.1. MINIMUM_IB_VERSION = 2549 # Xcode 4.4.1. MAXIMUM_IB_VERSION = 3084 # Xcode 4.6.x. HUMAN_IB_VERSION = '>= 4.4.1, <= 4.6.x' SYSTEM_VERSION_RE = r'<string key="IBDocument\.SystemVersion">' + \ '([0-9]{,2})([A-Z])([0-9]+)</string>' IB_VERSION_RE = \ r'<string key="IBDocument\.InterfaceBuilderVersion">([0-9]+)</string>' def _CheckXIBSystemAndXcodeVersions(input_api, output_api, error_type): affected_xibs = [x for x in input_api.AffectedFiles() if x.LocalPath().endswith('.xib')] incorrect_system_versions = [] incorrect_ib_versions = [] for xib in affected_xibs: if len(xib.NewContents()) == 0: continue system_version = None ib_version = None new_contents = xib.NewContents() if not new_contents: # Deleting files is always fine. continue for line in new_contents: m = re.search(SYSTEM_VERSION_RE, line) if m: system_version = (m.group(1), m.group(2), m.group(3)) m = re.search(IB_VERSION_RE, line) if m: ib_version = m.group(1) if system_version is not None and ib_version is not None: break if system_version is None: incorrect_system_versions.append(xib.LocalPath()) continue if int(system_version[0]) != ALLOWED_DARWIN_VERSION: incorrect_system_versions.append(xib.LocalPath()) continue if system_version[1] < MINIMUM_DARWIN_RELEASE: incorrect_system_versions.append(xib.LocalPath()) continue if ib_version is None or int(ib_version) < MINIMUM_IB_VERSION or \ int(ib_version) > MAXIMUM_IB_VERSION: incorrect_ib_versions.append(xib.LocalPath()) continue problems = [] if incorrect_system_versions: problems.append(error_type( 'XIB files need to be saved on Mac OS X ' + HUMAN_DARWIN_VERSION, items=incorrect_system_versions)) if incorrect_ib_versions: problems.append(error_type( 'XIB files need to be saved using Xcode version ' + HUMAN_IB_VERSION, items=incorrect_ib_versions)) return problems def CheckChangeOnUpload(input_api, output_api): # Allow uploads to happen even if the presubmit fails, so that contributors # can ask their reviewer or another person to re-save the XIBs for them. return _CheckXIBSystemAndXcodeVersions(input_api, output_api, error_type=output_api.PresubmitPromptWarning) def CheckChangeOnCommit(input_api, output_api): return _CheckXIBSystemAndXcodeVersions(input_api, output_api, error_type=output_api.PresubmitError)
bsd-3-clause
liangjiaxing/sympy
sympy/vector/tests/test_coordsysrect.py
43
12190
from sympy.vector.coordsysrect import CoordSysCartesian from sympy.vector.scalar import BaseScalar from sympy import sin, cos, pi, ImmutableMatrix as Matrix, \ symbols, simplify, zeros from sympy.vector.functions import express from sympy.vector.point import Point from sympy.vector.vector import Vector from sympy.vector.orienters import (AxisOrienter, BodyOrienter, SpaceOrienter, QuaternionOrienter) a, b, c, q = symbols('a b c q') q1, q2, q3, q4 = symbols('q1 q2 q3 q4') def test_coordsyscartesian_equivalence(): A = CoordSysCartesian('A') A1 = CoordSysCartesian('A') assert A1 == A B = CoordSysCartesian('B') assert A != B assert A.locate_new('C1', A.i) == A.locate_new('C2', A.i) assert A.orient_new_axis('C1', a, A.i) == \ A.orient_new_axis('C2', a, A.i) def test_orienters(): A = CoordSysCartesian('A') axis_orienter = AxisOrienter(a, A.k) body_orienter = BodyOrienter(a, b, c, '123') space_orienter = SpaceOrienter(a, b, c, '123') q_orienter = QuaternionOrienter(q1, q2, q3, q4) assert axis_orienter.rotation_matrix(A) == Matrix([ [ cos(a), sin(a), 0], [-sin(a), cos(a), 0], [ 0, 0, 1]]) assert body_orienter.rotation_matrix() == Matrix([ [ cos(b)*cos(c), sin(a)*sin(b)*cos(c) + sin(c)*cos(a), sin(a)*sin(c) - sin(b)*cos(a)*cos(c)], [-sin(c)*cos(b), -sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(c) + sin(b)*sin(c)*cos(a)], [ sin(b), -sin(a)*cos(b), cos(a)*cos(b)]]) assert space_orienter.rotation_matrix() == Matrix([ [cos(b)*cos(c), sin(c)*cos(b), -sin(b)], [sin(a)*sin(b)*cos(c) - sin(c)*cos(a), sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(b)], [sin(a)*sin(c) + sin(b)*cos(a)*cos(c), -sin(a)*cos(c) + sin(b)*sin(c)*cos(a), cos(a)*cos(b)]]) assert q_orienter.rotation_matrix() == Matrix([ [q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4], [-2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4], [2*q1*q3 + 2*q2*q4, -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]]) def test_coordinate_vars(): """ Tests the coordinate variables functionality with respect to reorientation of coordinate systems. """ A = CoordSysCartesian('A') assert BaseScalar('Ax', 0, A, ' ', ' ') == A.x assert BaseScalar('Ay', 1, A, ' ', ' ') == A.y assert BaseScalar('Az', 2, A, ' ', ' ') == A.z assert BaseScalar('Ax', 0, A, ' ', ' ').__hash__() == A.x.__hash__() assert isinstance(A.x, BaseScalar) and \ isinstance(A.y, BaseScalar) and \ isinstance(A.z, BaseScalar) assert A.scalar_map(A) == {A.x: A.x, A.y: A.y, A.z: A.z} assert A.x.system == A B = A.orient_new_axis('B', q, A.k) assert B.scalar_map(A) == {B.z: A.z, B.y: -A.x*sin(q) + A.y*cos(q), B.x: A.x*cos(q) + A.y*sin(q)} assert A.scalar_map(B) == {A.x: B.x*cos(q) - B.y*sin(q), A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z} assert express(B.x, A, variables=True) == A.x*cos(q) + A.y*sin(q) assert express(B.y, A, variables=True) == -A.x*sin(q) + A.y*cos(q) assert express(B.z, A, variables=True) == A.z assert express(B.x*B.y*B.z, A, variables=True) == \ A.z*(-A.x*sin(q) + A.y*cos(q))*(A.x*cos(q) + A.y*sin(q)) assert express(B.x*B.i + B.y*B.j + B.z*B.k, A) == \ (B.x*cos(q) - B.y*sin(q))*A.i + (B.x*sin(q) + \ B.y*cos(q))*A.j + B.z*A.k assert simplify(express(B.x*B.i + B.y*B.j + B.z*B.k, A, \ variables=True)) == \ A.x*A.i + A.y*A.j + A.z*A.k assert express(A.x*A.i + A.y*A.j + A.z*A.k, B) == \ (A.x*cos(q) + A.y*sin(q))*B.i + \ (-A.x*sin(q) + A.y*cos(q))*B.j + A.z*B.k assert simplify(express(A.x*A.i + A.y*A.j + A.z*A.k, B, \ variables=True)) == \ B.x*B.i + B.y*B.j + B.z*B.k N = B.orient_new_axis('N', -q, B.k) assert N.scalar_map(A) == \ {N.x: A.x, N.z: A.z, N.y: A.y} C = A.orient_new_axis('C', q, A.i + A.j + A.k) mapping = A.scalar_map(C) assert mapping[A.x] == 2*C.x*cos(q)/3 + C.x/3 - \ 2*C.y*sin(q + pi/6)/3 + C.y/3 - 2*C.z*cos(q + pi/3)/3 + C.z/3 assert mapping[A.y] == -2*C.x*cos(q + pi/3)/3 + \ C.x/3 + 2*C.y*cos(q)/3 + C.y/3 - 2*C.z*sin(q + pi/6)/3 + C.z/3 assert mapping[A.z] == -2*C.x*sin(q + pi/6)/3 + C.x/3 - \ 2*C.y*cos(q + pi/3)/3 + C.y/3 + 2*C.z*cos(q)/3 + C.z/3 D = A.locate_new('D', a*A.i + b*A.j + c*A.k) assert D.scalar_map(A) == {D.z: A.z - c, D.x: A.x - a, D.y: A.y - b} E = A.orient_new_axis('E', a, A.k, a*A.i + b*A.j + c*A.k) assert A.scalar_map(E) == {A.z: E.z + c, A.x: E.x*cos(a) - E.y*sin(a) + a, A.y: E.x*sin(a) + E.y*cos(a) + b} assert E.scalar_map(A) == {E.x: (A.x - a)*cos(a) + (A.y - b)*sin(a), E.y: (-A.x + a)*sin(a) + (A.y - b)*cos(a), E.z: A.z - c} F = A.locate_new('F', Vector.zero) assert A.scalar_map(F) == {A.z: F.z, A.x: F.x, A.y: F.y} def test_rotation_matrix(): N = CoordSysCartesian('N') A = N.orient_new_axis('A', q1, N.k) B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) D = N.orient_new_axis('D', q4, N.j) E = N.orient_new_space('E', q1, q2, q3, '123') F = N.orient_new_quaternion('F', q1, q2, q3, q4) G = N.orient_new_body('G', q1, q2, q3, '123') assert N.rotation_matrix(C) == Matrix([ [- sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), - sin(q1) * cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1)], \ [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), \ cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * \ cos(q3)], [- sin(q3) * cos(q2), sin(q2), cos(q2) * cos(q3)]]) test_mat = D.rotation_matrix(C) - Matrix( [[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) * cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * \ (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], \ [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * \ cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], \ [sin(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + \ sin(q1) * sin(q2) * \ sin(q4)), sin(q2) * cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * \ sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + \ sin(q1) * sin(q2) * sin(q4))]]) assert test_mat.expand() == zeros(3, 3) assert E.rotation_matrix(N) == Matrix( [[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)], [sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), \ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], \ [sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - \ sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]]) assert F.rotation_matrix(N) == Matrix([[ q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4],[ -2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4], [2*q1*q3 + 2*q2*q4, -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]]) assert G.rotation_matrix(N) == Matrix([[ cos(q2)*cos(q3), sin(q1)*sin(q2)*cos(q3) + sin(q3)*cos(q1), sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)], [ -sin(q3)*cos(q2), -sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],[ sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]]) def test_vector(): """ Tests the effects of orientation of coordinate systems on basic vector operations. """ N = CoordSysCartesian('N') A = N.orient_new_axis('A', q1, N.k) B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) #Test to_matrix v1 = a*N.i + b*N.j + c*N.k assert v1.to_matrix(A) == Matrix([[ a*cos(q1) + b*sin(q1)], [-a*sin(q1) + b*cos(q1)], [ c]]) #Test dot assert N.i.dot(A.i) == cos(q1) assert N.i.dot(A.j) == -sin(q1) assert N.i.dot(A.k) == 0 assert N.j.dot(A.i) == sin(q1) assert N.j.dot(A.j) == cos(q1) assert N.j.dot(A.k) == 0 assert N.k.dot(A.i) == 0 assert N.k.dot(A.j) == 0 assert N.k.dot(A.k) == 1 assert N.i.dot(A.i + A.j) == -sin(q1) + cos(q1) == \ (A.i + A.j).dot(N.i) assert A.i.dot(C.i) == cos(q3) assert A.i.dot(C.j) == 0 assert A.i.dot(C.k) == sin(q3) assert A.j.dot(C.i) == sin(q2)*sin(q3) assert A.j.dot(C.j) == cos(q2) assert A.j.dot(C.k) == -sin(q2)*cos(q3) assert A.k.dot(C.i) == -cos(q2)*sin(q3) assert A.k.dot(C.j) == sin(q2) assert A.k.dot(C.k) == cos(q2)*cos(q3) #Test cross assert N.i.cross(A.i) == sin(q1)*A.k assert N.i.cross(A.j) == cos(q1)*A.k assert N.i.cross(A.k) == -sin(q1)*A.i - cos(q1)*A.j assert N.j.cross(A.i) == -cos(q1)*A.k assert N.j.cross(A.j) == sin(q1)*A.k assert N.j.cross(A.k) == cos(q1)*A.i - sin(q1)*A.j assert N.k.cross(A.i) == A.j assert N.k.cross(A.j) == -A.i assert N.k.cross(A.k) == Vector.zero assert N.i.cross(A.i) == sin(q1)*A.k assert N.i.cross(A.j) == cos(q1)*A.k assert N.i.cross(A.i + A.j) == sin(q1)*A.k + cos(q1)*A.k assert (A.i + A.j).cross(N.i) == (-sin(q1) - cos(q1))*N.k assert A.i.cross(C.i) == sin(q3)*C.j assert A.i.cross(C.j) == -sin(q3)*C.i + cos(q3)*C.k assert A.i.cross(C.k) == -cos(q3)*C.j assert C.i.cross(A.i) == (-sin(q3)*cos(q2))*A.j + \ (-sin(q2)*sin(q3))*A.k assert C.j.cross(A.i) == (sin(q2))*A.j + (-cos(q2))*A.k assert express(C.k.cross(A.i), C).trigsimp() == cos(q3)*C.j def test_orient_new_methods(): N = CoordSysCartesian('N') orienter1 = AxisOrienter(q4, N.j) orienter2 = SpaceOrienter(q1, q2, q3, '123') orienter3 = QuaternionOrienter(q1, q2, q3, q4) orienter4 = BodyOrienter(q1, q2, q3, '123') D = N.orient_new('D', (orienter1, )) E = N.orient_new('E', (orienter2, )) F = N.orient_new('F', (orienter3, )) G = N.orient_new('G', (orienter4, )) assert D == N.orient_new_axis('D', q4, N.j) assert E == N.orient_new_space('E', q1, q2, q3, '123') assert F == N.orient_new_quaternion('F', q1, q2, q3, q4) assert G == N.orient_new_body('G', q1, q2, q3, '123') def test_locatenew_point(): """ Tests Point class, and locate_new method in CoordSysCartesian. """ A = CoordSysCartesian('A') assert isinstance(A.origin, Point) v = a*A.i + b*A.j + c*A.k C = A.locate_new('C', v) assert C.origin.position_wrt(A) == \ C.position_wrt(A) == \ C.origin.position_wrt(A.origin) == v assert A.origin.position_wrt(C) == \ A.position_wrt(C) == \ A.origin.position_wrt(C.origin) == -v assert A.origin.express_coordinates(C) == (-a, -b, -c) p = A.origin.locate_new('p', -v) assert p.express_coordinates(A) == (-a, -b, -c) assert p.position_wrt(C.origin) == p.position_wrt(C) == \ -2 * v p1 = p.locate_new('p1', 2*v) assert p1.position_wrt(C.origin) == Vector.zero assert p1.express_coordinates(C) == (0, 0, 0) p2 = p.locate_new('p2', A.i) assert p1.position_wrt(p2) == 2*v - A.i assert p2.express_coordinates(C) == (-2*a + 1, -2*b, -2*c) def test_evalf(): A = CoordSysCartesian('A') v = 3*A.i + 4*A.j + a*A.k assert v.n() == v.evalf() assert v.evalf(subs={a:1}) == v.subs(a, 1).evalf()
bsd-3-clause
bolkedebruin/airflow
tests/providers/segment/hooks/test_segment.py
1
2017
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import unittest from unittest import mock from airflow import AirflowException from airflow.providers.segment.hooks.segment import SegmentHook TEST_CONN_ID = 'test_segment' WRITE_KEY = 'foo' class TestSegmentHook(unittest.TestCase): def setUp(self): super().setUp() self.conn = conn = mock.MagicMock() conn.write_key = WRITE_KEY self.expected_write_key = WRITE_KEY self.conn.extra_dejson = {'write_key': self.expected_write_key} class UnitTestSegmentHook(SegmentHook): def get_conn(self): return conn def get_connection(self, _): return conn self.test_hook = UnitTestSegmentHook(segment_conn_id=TEST_CONN_ID) def test_get_conn(self): expected_connection = self.test_hook.get_conn() self.assertEqual(expected_connection, self.conn) self.assertIsNotNone(expected_connection.write_key) self.assertEqual(expected_connection.write_key, self.expected_write_key) def test_on_error(self): with self.assertRaises(AirflowException): self.test_hook.on_error('error', ['items']) if __name__ == '__main__': unittest.main()
apache-2.0
vietpn/ghost-nodejs
node_modules/grunt-docker/node_modules/docker/node_modules/pygmentize-bundled/vendor/pygments/pygments/styles/autumn.py
364
2144
# -*- coding: utf-8 -*- """ pygments.styles.autumn ~~~~~~~~~~~~~~~~~~~~~~ A colorful style, inspired by the terminal highlighting style. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class AutumnStyle(Style): """ A colorful style, inspired by the terminal highlighting style. """ default_style = "" styles = { Whitespace: '#bbbbbb', Comment: 'italic #aaaaaa', Comment.Preproc: 'noitalic #4c8317', Comment.Special: 'italic #0000aa', Keyword: '#0000aa', Keyword.Type: '#00aaaa', Operator.Word: '#0000aa', Name.Builtin: '#00aaaa', Name.Function: '#00aa00', Name.Class: 'underline #00aa00', Name.Namespace: 'underline #00aaaa', Name.Variable: '#aa0000', Name.Constant: '#aa0000', Name.Entity: 'bold #800', Name.Attribute: '#1e90ff', Name.Tag: 'bold #1e90ff', Name.Decorator: '#888888', String: '#aa5500', String.Symbol: '#0000aa', String.Regex: '#009999', Number: '#009999', Generic.Heading: 'bold #000080', Generic.Subheading: 'bold #800080', Generic.Deleted: '#aa0000', Generic.Inserted: '#00aa00', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000', Error: '#F00 bg:#FAA' }
mit