repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
indictranstech/reciphergroup-erpnext
refs/heads/master
erpnext/patches/v5_4/__init__.py
12133432
hbutau/dzidzo
refs/heads/master
config/__init__.py
12133432
drewdru/bookExpert
refs/heads/master
bookExpert/__init__.py
12133432
henryfjordan/django
refs/heads/master
tests/timezones/__init__.py
12133432
nzavagli/UnrealPy
refs/heads/master
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Python-2.7.10/Lib/test/test_re.py
14
# -*- coding: utf-8 -*- from test.test_support import ( verbose, run_unittest, import_module, precisionbigmemtest, _2G, cpython_only, captured_stdout, have_unicode, requires_unicode, u, check_warnings) import locale import re from re import Scanner import sre_constants import sys import string import traceback from weakref import proxy # Misc tests from Tim Peters' re.doc # WARNING: Don't change details in these tests if you don't know # what you're doing. Some of these tests were carefully modeled to # cover most of the code. import unittest class ReTests(unittest.TestCase): def test_weakref(self): s = 'QabbbcR' x = re.compile('ab+c') y = proxy(x) self.assertEqual(x.findall('QabbbcR'), y.findall('QabbbcR')) def test_search_star_plus(self): self.assertEqual(re.search('x*', 'axx').span(0), (0, 0)) self.assertEqual(re.search('x*', 'axx').span(), (0, 0)) self.assertEqual(re.search('x+', 'axx').span(0), (1, 3)) self.assertEqual(re.search('x+', 'axx').span(), (1, 3)) self.assertIsNone(re.search('x', 'aaa')) self.assertEqual(re.match('a*', 'xxx').span(0), (0, 0)) self.assertEqual(re.match('a*', 'xxx').span(), (0, 0)) self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3)) self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3)) self.assertIsNone(re.match('a+', 'xxx')) def bump_num(self, matchobj): int_value = int(matchobj.group(0)) return str(int_value + 1) def test_basic_re_sub(self): self.assertEqual(re.sub("(?i)b+", "x", "bbbb BBBB"), 'x x') self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'), '9.3 -3 24x100y') self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3), '9.3 -3 23x99y') self.assertEqual(re.sub('.', lambda m: r"\n", 'x'), '\\n') self.assertEqual(re.sub('.', r"\n", 'x'), '\n') s = r"\1\1" self.assertEqual(re.sub('(.)', s, 'x'), 'xx') self.assertEqual(re.sub('(.)', re.escape(s), 'x'), s) self.assertEqual(re.sub('(.)', lambda m: s, 'x'), s) self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<a>', 'xx'), 'xxxx') self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<1>', 'xx'), 'xxxx') self.assertEqual(re.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx'), 'xxxx') self.assertEqual(re.sub('(?P<unk>x)', '\g<1>\g<1>', 'xx'), 'xxxx') self.assertEqual(re.sub('a',r'\t\n\v\r\f\a\b\B\Z\a\A\w\W\s\S\d\D','a'), '\t\n\v\r\f\a\b\\B\\Z\a\\A\\w\\W\\s\\S\\d\\D') self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'), '\t\n\v\r\f\a') self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'), (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7))) self.assertEqual(re.sub('^\s*', 'X', 'test'), 'Xtest') def test_bug_449964(self): # fails for group followed by other escape self.assertEqual(re.sub(r'(?P<unk>x)', '\g<1>\g<1>\\b', 'xx'), 'xx\bxx\b') def test_bug_449000(self): # Test for sub() on escaped characters self.assertEqual(re.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') self.assertEqual(re.sub('\r\n', r'\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') self.assertEqual(re.sub(r'\r\n', '\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') @requires_unicode def test_bug_1140(self): # re.sub(x, y, u'') should return u'', not '', and # re.sub(x, y, '') should return '', not u''. # Also: # re.sub(x, y, unicode(x)) should return unicode(y), and # re.sub(x, y, str(x)) should return # str(y) if isinstance(y, str) else unicode(y). for x in 'x', u'x': for y in 'y', u'y': z = re.sub(x, y, u'') self.assertEqual(z, u'') self.assertEqual(type(z), unicode) # z = re.sub(x, y, '') self.assertEqual(z, '') self.assertEqual(type(z), str) # z = re.sub(x, y, unicode(x)) self.assertEqual(z, y) self.assertEqual(type(z), unicode) # z = re.sub(x, y, str(x)) self.assertEqual(z, y) self.assertEqual(type(z), type(y)) def test_bug_1661(self): # Verify that flags do not get silently ignored with compiled patterns pattern = re.compile('.') self.assertRaises(ValueError, re.match, pattern, 'A', re.I) self.assertRaises(ValueError, re.search, pattern, 'A', re.I) self.assertRaises(ValueError, re.findall, pattern, 'A', re.I) self.assertRaises(ValueError, re.compile, pattern, re.I) def test_bug_3629(self): # A regex that triggered a bug in the sre-code validator re.compile("(?P<quote>)(?(quote))") def test_sub_template_numeric_escape(self): # bug 776311 and friends self.assertEqual(re.sub('x', r'\0', 'x'), '\0') self.assertEqual(re.sub('x', r'\000', 'x'), '\000') self.assertEqual(re.sub('x', r'\001', 'x'), '\001') self.assertEqual(re.sub('x', r'\008', 'x'), '\0' + '8') self.assertEqual(re.sub('x', r'\009', 'x'), '\0' + '9') self.assertEqual(re.sub('x', r'\111', 'x'), '\111') self.assertEqual(re.sub('x', r'\117', 'x'), '\117') self.assertEqual(re.sub('x', r'\1111', 'x'), '\1111') self.assertEqual(re.sub('x', r'\1111', 'x'), '\111' + '1') self.assertEqual(re.sub('x', r'\00', 'x'), '\x00') self.assertEqual(re.sub('x', r'\07', 'x'), '\x07') self.assertEqual(re.sub('x', r'\08', 'x'), '\0' + '8') self.assertEqual(re.sub('x', r'\09', 'x'), '\0' + '9') self.assertEqual(re.sub('x', r'\0a', 'x'), '\0' + 'a') self.assertEqual(re.sub('x', r'\400', 'x'), '\0') self.assertEqual(re.sub('x', r'\777', 'x'), '\377') self.assertRaises(re.error, re.sub, 'x', r'\1', 'x') self.assertRaises(re.error, re.sub, 'x', r'\8', 'x') self.assertRaises(re.error, re.sub, 'x', r'\9', 'x') self.assertRaises(re.error, re.sub, 'x', r'\11', 'x') self.assertRaises(re.error, re.sub, 'x', r'\18', 'x') self.assertRaises(re.error, re.sub, 'x', r'\1a', 'x') self.assertRaises(re.error, re.sub, 'x', r'\90', 'x') self.assertRaises(re.error, re.sub, 'x', r'\99', 'x') self.assertRaises(re.error, re.sub, 'x', r'\118', 'x') # r'\11' + '8' self.assertRaises(re.error, re.sub, 'x', r'\11a', 'x') self.assertRaises(re.error, re.sub, 'x', r'\181', 'x') # r'\18' + '1' self.assertRaises(re.error, re.sub, 'x', r'\800', 'x') # r'\80' + '0' # in python2.3 (etc), these loop endlessly in sre_parser.py self.assertEqual(re.sub('(((((((((((x)))))))))))', r'\11', 'x'), 'x') self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\118', 'xyz'), 'xz8') self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\11a', 'xyz'), 'xza') def test_qualified_re_sub(self): self.assertEqual(re.sub('a', 'b', 'aaaaa'), 'bbbbb') self.assertEqual(re.sub('a', 'b', 'aaaaa', 1), 'baaaa') def test_bug_114660(self): self.assertEqual(re.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello there'), 'hello there') def test_bug_462270(self): # Test for empty sub() behaviour, see SF bug #462270 self.assertEqual(re.sub('x*', '-', 'abxd'), '-a-b-d-') self.assertEqual(re.sub('x+', '-', 'abxd'), 'ab-d') def test_symbolic_groups(self): re.compile('(?P<a>x)(?P=a)(?(a)y)') re.compile('(?P<a1>x)(?P=a1)(?(a1)y)') self.assertRaises(re.error, re.compile, '(?P<a>)(?P<a>)') self.assertRaises(re.error, re.compile, '(?Px)') self.assertRaises(re.error, re.compile, '(?P=)') self.assertRaises(re.error, re.compile, '(?P=1)') self.assertRaises(re.error, re.compile, '(?P=a)') self.assertRaises(re.error, re.compile, '(?P=a1)') self.assertRaises(re.error, re.compile, '(?P=a.)') self.assertRaises(re.error, re.compile, '(?P<)') self.assertRaises(re.error, re.compile, '(?P<>)') self.assertRaises(re.error, re.compile, '(?P<1>)') self.assertRaises(re.error, re.compile, '(?P<a.>)') self.assertRaises(re.error, re.compile, '(?())') self.assertRaises(re.error, re.compile, '(?(a))') self.assertRaises(re.error, re.compile, '(?(1a))') self.assertRaises(re.error, re.compile, '(?(a.))') def test_symbolic_refs(self): self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a a>', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<>', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<1a1>', 'xx') self.assertRaises(IndexError, re.sub, '(?P<a>x)', '\g<ab>', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\g<b>', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\\2', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<-1>', 'xx') def test_re_subn(self): self.assertEqual(re.subn("(?i)b+", "x", "bbbb BBBB"), ('x x', 2)) self.assertEqual(re.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1)) self.assertEqual(re.subn("b+", "x", "xyz"), ('xyz', 0)) self.assertEqual(re.subn("b*", "x", "xyz"), ('xxxyxzx', 4)) self.assertEqual(re.subn("b*", "x", "xyz", 2), ('xxxyz', 2)) def test_re_split(self): self.assertEqual(re.split(":", ":a:b::c"), ['', 'a', 'b', '', 'c']) self.assertEqual(re.split(":*", ":a:b::c"), ['', 'a', 'b', 'c']) self.assertEqual(re.split("(:*)", ":a:b::c"), ['', ':', 'a', ':', 'b', '::', 'c']) self.assertEqual(re.split("(?::*)", ":a:b::c"), ['', 'a', 'b', 'c']) self.assertEqual(re.split("(:)*", ":a:b::c"), ['', ':', 'a', ':', 'b', ':', 'c']) self.assertEqual(re.split("([b:]+)", ":a:b::c"), ['', ':', 'a', ':b::', 'c']) self.assertEqual(re.split("(b)|(:+)", ":a:b::c"), ['', None, ':', 'a', None, ':', '', 'b', None, '', None, '::', 'c']) self.assertEqual(re.split("(?:b)|(?::+)", ":a:b::c"), ['', 'a', '', '', 'c']) def test_qualified_re_split(self): self.assertEqual(re.split(":", ":a:b::c", 2), ['', 'a', 'b::c']) self.assertEqual(re.split(':', 'a:b:c:d', 2), ['a', 'b', 'c:d']) self.assertEqual(re.split("(:)", ":a:b::c", 2), ['', ':', 'a', ':', 'b::c']) self.assertEqual(re.split("(:*)", ":a:b::c", 2), ['', ':', 'a', ':', 'b::c']) def test_re_findall(self): self.assertEqual(re.findall(":+", "abc"), []) self.assertEqual(re.findall(":+", "a:b::c:::d"), [":", "::", ":::"]) self.assertEqual(re.findall("(:+)", "a:b::c:::d"), [":", "::", ":::"]) self.assertEqual(re.findall("(:)(:*)", "a:b::c:::d"), [(":", ""), (":", ":"), (":", "::")]) def test_bug_117612(self): self.assertEqual(re.findall(r"(a|(b))", "aba"), [("a", ""),("b", "b"),("a", "")]) def test_re_match(self): self.assertEqual(re.match('a', 'a').groups(), ()) self.assertEqual(re.match('(a)', 'a').groups(), ('a',)) self.assertEqual(re.match(r'(a)', 'a').group(0), 'a') self.assertEqual(re.match(r'(a)', 'a').group(1), 'a') self.assertEqual(re.match(r'(a)', 'a').group(1, 1), ('a', 'a')) pat = re.compile('((a)|(b))(c)?') self.assertEqual(pat.match('a').groups(), ('a', 'a', None, None)) self.assertEqual(pat.match('b').groups(), ('b', None, 'b', None)) self.assertEqual(pat.match('ac').groups(), ('a', 'a', None, 'c')) self.assertEqual(pat.match('bc').groups(), ('b', None, 'b', 'c')) self.assertEqual(pat.match('bc').groups(""), ('b', "", 'b', 'c')) # A single group m = re.match('(a)', 'a') self.assertEqual(m.group(0), 'a') self.assertEqual(m.group(0), 'a') self.assertEqual(m.group(1), 'a') self.assertEqual(m.group(1, 1), ('a', 'a')) pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?') self.assertEqual(pat.match('a').group(1, 2, 3), ('a', None, None)) self.assertEqual(pat.match('b').group('a1', 'b2', 'c3'), (None, 'b', None)) self.assertEqual(pat.match('ac').group(1, 'b2', 3), ('a', None, 'c')) def test_re_groupref_exists(self): self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', '(a)').groups(), ('(', 'a')) self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', 'a').groups(), (None, 'a')) self.assertIsNone(re.match('^(\()?([^()]+)(?(1)\))$', 'a)')) self.assertIsNone(re.match('^(\()?([^()]+)(?(1)\))$', '(a')) self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'ab').groups(), ('a', 'b')) self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'cd').groups(), (None, 'd')) self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'cd').groups(), (None, 'd')) self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'a').groups(), ('a', '')) # Tests for bug #1177831: exercise groups other than the first group p = re.compile('(?P<g1>a)(?P<g2>b)?((?(g2)c|d))') self.assertEqual(p.match('abc').groups(), ('a', 'b', 'c')) self.assertEqual(p.match('ad').groups(), ('a', None, 'd')) self.assertIsNone(p.match('abd')) self.assertIsNone(p.match('ac')) def test_re_groupref(self): self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a|').groups(), ('|', 'a')) self.assertEqual(re.match(r'^(\|)?([^()]+)\1?$', 'a').groups(), (None, 'a')) self.assertIsNone(re.match(r'^(\|)?([^()]+)\1$', 'a|')) self.assertIsNone(re.match(r'^(\|)?([^()]+)\1$', '|a')) self.assertEqual(re.match(r'^(?:(a)|c)(\1)$', 'aa').groups(), ('a', 'a')) self.assertEqual(re.match(r'^(?:(a)|c)(\1)?$', 'c').groups(), (None, None)) def test_groupdict(self): self.assertEqual(re.match('(?P<first>first) (?P<second>second)', 'first second').groupdict(), {'first':'first', 'second':'second'}) def test_expand(self): self.assertEqual(re.match("(?P<first>first) (?P<second>second)", "first second") .expand(r"\2 \1 \g<second> \g<first>"), "second first second first") def test_repeat_minmax(self): self.assertIsNone(re.match("^(\w){1}$", "abc")) self.assertIsNone(re.match("^(\w){1}?$", "abc")) self.assertIsNone(re.match("^(\w){1,2}$", "abc")) self.assertIsNone(re.match("^(\w){1,2}?$", "abc")) self.assertEqual(re.match("^(\w){3}$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){1,3}$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){1,4}$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){3}?$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){1,3}?$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){1,4}?$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c") self.assertIsNone(re.match("^x{1}$", "xxx")) self.assertIsNone(re.match("^x{1}?$", "xxx")) self.assertIsNone(re.match("^x{1,2}$", "xxx")) self.assertIsNone(re.match("^x{1,2}?$", "xxx")) self.assertTrue(re.match("^x{3}$", "xxx")) self.assertTrue(re.match("^x{1,3}$", "xxx")) self.assertTrue(re.match("^x{1,4}$", "xxx")) self.assertTrue(re.match("^x{3,4}?$", "xxx")) self.assertTrue(re.match("^x{3}?$", "xxx")) self.assertTrue(re.match("^x{1,3}?$", "xxx")) self.assertTrue(re.match("^x{1,4}?$", "xxx")) self.assertTrue(re.match("^x{3,4}?$", "xxx")) self.assertIsNone(re.match("^x{}$", "xxx")) self.assertTrue(re.match("^x{}$", "x{}")) def test_getattr(self): self.assertEqual(re.match("(a)", "a").pos, 0) self.assertEqual(re.match("(a)", "a").endpos, 1) self.assertEqual(re.match("(a)", "a").string, "a") self.assertEqual(re.match("(a)", "a").regs, ((0, 1), (0, 1))) self.assertTrue(re.match("(a)", "a").re) def test_special_escapes(self): self.assertEqual(re.search(r"\b(b.)\b", "abcd abc bcd bx").group(1), "bx") self.assertEqual(re.search(r"\B(b.)\B", "abc bcd bc abxd").group(1), "bx") self.assertEqual(re.search(r"\b(b.)\b", "abcd abc bcd bx", re.LOCALE).group(1), "bx") self.assertEqual(re.search(r"\B(b.)\B", "abc bcd bc abxd", re.LOCALE).group(1), "bx") if have_unicode: self.assertEqual(re.search(r"\b(b.)\b", "abcd abc bcd bx", re.UNICODE).group(1), "bx") self.assertEqual(re.search(r"\B(b.)\B", "abc bcd bc abxd", re.UNICODE).group(1), "bx") self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc") self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc") self.assertIsNone(re.search(r"^\Aabc\Z$", "\nabc\n", re.M)) self.assertEqual(re.search(r"\b(b.)\b", u"abcd abc bcd bx").group(1), "bx") self.assertEqual(re.search(r"\B(b.)\B", u"abc bcd bc abxd").group(1), "bx") self.assertEqual(re.search(r"^abc$", u"\nabc\n", re.M).group(0), "abc") self.assertEqual(re.search(r"^\Aabc\Z$", u"abc", re.M).group(0), "abc") self.assertIsNone(re.search(r"^\Aabc\Z$", u"\nabc\n", re.M)) self.assertEqual(re.search(r"\d\D\w\W\s\S", "1aa! a").group(0), "1aa! a") self.assertEqual(re.search(r"\d\D\w\W\s\S", "1aa! a", re.LOCALE).group(0), "1aa! a") if have_unicode: self.assertEqual(re.search(r"\d\D\w\W\s\S", "1aa! a", re.UNICODE).group(0), "1aa! a") def test_string_boundaries(self): # See http://bugs.python.org/issue10713 self.assertEqual(re.search(r"\b(abc)\b", "abc").group(1), "abc") # There's a word boundary at the start of a string. self.assertTrue(re.match(r"\b", "abc")) # A non-empty string includes a non-boundary zero-length match. self.assertTrue(re.search(r"\B", "abc")) # There is no non-boundary match at the start of a string. self.assertFalse(re.match(r"\B", "abc")) # However, an empty string contains no word boundaries, and also no # non-boundaries. self.assertIsNone(re.search(r"\B", "")) # This one is questionable and different from the perlre behaviour, # but describes current behavior. self.assertIsNone(re.search(r"\b", "")) # A single word-character string has two boundaries, but no # non-boundary gaps. self.assertEqual(len(re.findall(r"\b", "a")), 2) self.assertEqual(len(re.findall(r"\B", "a")), 0) # If there are no words, there are no boundaries self.assertEqual(len(re.findall(r"\b", " ")), 0) self.assertEqual(len(re.findall(r"\b", " ")), 0) # Can match around the whitespace. self.assertEqual(len(re.findall(r"\B", " ")), 2) @requires_unicode def test_bigcharset(self): self.assertEqual(re.match(u(r"([\u2222\u2223])"), unichr(0x2222)).group(1), unichr(0x2222)) self.assertEqual(re.match(u(r"([\u2222\u2223])"), unichr(0x2222), re.UNICODE).group(1), unichr(0x2222)) r = u'[%s]' % u''.join(map(unichr, range(256, 2**16, 255))) self.assertEqual(re.match(r, unichr(0xff01), re.UNICODE).group(), unichr(0xff01)) def test_big_codesize(self): # Issue #1160 r = re.compile('|'.join(('%d'%x for x in range(10000)))) self.assertTrue(r.match('1000')) self.assertTrue(r.match('9999')) def test_anyall(self): self.assertEqual(re.match("a.b", "a\nb", re.DOTALL).group(0), "a\nb") self.assertEqual(re.match("a.*b", "a\n\nb", re.DOTALL).group(0), "a\n\nb") def test_lookahead(self): self.assertEqual(re.match("(a(?=\s[^a]))", "a b").group(1), "a") self.assertEqual(re.match("(a(?=\s[^a]*))", "a b").group(1), "a") self.assertEqual(re.match("(a(?=\s[abc]))", "a b").group(1), "a") self.assertEqual(re.match("(a(?=\s[abc]*))", "a bc").group(1), "a") self.assertEqual(re.match(r"(a)(?=\s\1)", "a a").group(1), "a") self.assertEqual(re.match(r"(a)(?=\s\1*)", "a aa").group(1), "a") self.assertEqual(re.match(r"(a)(?=\s(abc|a))", "a a").group(1), "a") self.assertEqual(re.match(r"(a(?!\s[^a]))", "a a").group(1), "a") self.assertEqual(re.match(r"(a(?!\s[abc]))", "a d").group(1), "a") self.assertEqual(re.match(r"(a)(?!\s\1)", "a b").group(1), "a") self.assertEqual(re.match(r"(a)(?!\s(abc|a))", "a b").group(1), "a") # Group reference. self.assertTrue(re.match(r'(a)b(?=\1)a', 'aba')) self.assertIsNone(re.match(r'(a)b(?=\1)c', 'abac')) # Named group reference. self.assertTrue(re.match(r'(?P<g>a)b(?=(?P=g))a', 'aba')) self.assertIsNone(re.match(r'(?P<g>a)b(?=(?P=g))c', 'abac')) # Conditional group reference. self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(2)x|c))c', 'abc')) self.assertIsNone(re.match(r'(?:(a)|(x))b(?=(?(2)c|x))c', 'abc')) self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(2)x|c))c', 'abc')) self.assertIsNone(re.match(r'(?:(a)|(x))b(?=(?(1)b|x))c', 'abc')) self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(1)c|x))c', 'abc')) # Group used before defined. self.assertTrue(re.match(r'(a)b(?=(?(2)x|c))(c)', 'abc')) self.assertIsNone(re.match(r'(a)b(?=(?(2)b|x))(c)', 'abc')) self.assertTrue(re.match(r'(a)b(?=(?(1)c|x))(c)', 'abc')) def test_lookbehind(self): self.assertTrue(re.match(r'ab(?<=b)c', 'abc')) self.assertIsNone(re.match(r'ab(?<=c)c', 'abc')) self.assertIsNone(re.match(r'ab(?<!b)c', 'abc')) self.assertTrue(re.match(r'ab(?<!c)c', 'abc')) # Group reference. with check_warnings(('', RuntimeWarning)): re.compile(r'(a)a(?<=\1)c') # Named group reference. with check_warnings(('', RuntimeWarning)): re.compile(r'(?P<g>a)a(?<=(?P=g))c') # Conditional group reference. with check_warnings(('', RuntimeWarning)): re.compile(r'(a)b(?<=(?(1)b|x))c') # Group used before defined. with check_warnings(('', RuntimeWarning)): re.compile(r'(a)b(?<=(?(2)b|x))(c)') def test_ignore_case(self): self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC") self.assertEqual(re.match("abc", u"ABC", re.I).group(0), "ABC") self.assertEqual(re.match(r"(a\s[^a])", "a b", re.I).group(1), "a b") self.assertEqual(re.match(r"(a\s[^a]*)", "a bb", re.I).group(1), "a bb") self.assertEqual(re.match(r"(a\s[abc])", "a b", re.I).group(1), "a b") self.assertEqual(re.match(r"(a\s[abc]*)", "a bb", re.I).group(1), "a bb") self.assertEqual(re.match(r"((a)\s\2)", "a a", re.I).group(1), "a a") self.assertEqual(re.match(r"((a)\s\2*)", "a aa", re.I).group(1), "a aa") self.assertEqual(re.match(r"((a)\s(abc|a))", "a a", re.I).group(1), "a a") self.assertEqual(re.match(r"((a)\s(abc|a)*)", "a aa", re.I).group(1), "a aa") if have_unicode: assert u(r'\u212a').lower() == u'k' # 'K' self.assertTrue(re.match(ur'K', u(r'\u212a'), re.U | re.I)) self.assertTrue(re.match(ur'k', u(r'\u212a'), re.U | re.I)) self.assertTrue(re.match(u(r'\u212a'), u'K', re.U | re.I)) self.assertTrue(re.match(u(r'\u212a'), u'k', re.U | re.I)) assert u(r'\u017f').upper() == u'S' # 'ſ' self.assertTrue(re.match(ur'S', u(r'\u017f'), re.U | re.I)) self.assertTrue(re.match(ur's', u(r'\u017f'), re.U | re.I)) self.assertTrue(re.match(u(r'\u017f'), u'S', re.U | re.I)) self.assertTrue(re.match(u(r'\u017f'), u's', re.U | re.I)) def test_ignore_case_set(self): self.assertTrue(re.match(r'[19A]', 'A', re.I)) self.assertTrue(re.match(r'[19a]', 'a', re.I)) self.assertTrue(re.match(r'[19a]', 'A', re.I)) self.assertTrue(re.match(r'[19A]', 'a', re.I)) if have_unicode: self.assertTrue(re.match(ur'[19A]', u'A', re.U | re.I)) self.assertTrue(re.match(ur'[19a]', u'a', re.U | re.I)) self.assertTrue(re.match(ur'[19a]', u'A', re.U | re.I)) self.assertTrue(re.match(ur'[19A]', u'a', re.U | re.I)) assert u(r'\u212a').lower() == u'k' # 'K' self.assertTrue(re.match(u(r'[19K]'), u(r'\u212a'), re.U | re.I)) self.assertTrue(re.match(u(r'[19k]'), u(r'\u212a'), re.U | re.I)) self.assertTrue(re.match(u(r'[19\u212a]'), u'K', re.U | re.I)) self.assertTrue(re.match(u(r'[19\u212a]'), u'k', re.U | re.I)) assert u(r'\u017f').upper() == u'S' # 'ſ' self.assertTrue(re.match(ur'[19S]', u(r'\u017f'), re.U | re.I)) self.assertTrue(re.match(ur'[19s]', u(r'\u017f'), re.U | re.I)) self.assertTrue(re.match(u(r'[19\u017f]'), u'S', re.U | re.I)) self.assertTrue(re.match(u(r'[19\u017f]'), u's', re.U | re.I)) def test_ignore_case_range(self): # Issues #3511, #17381. self.assertTrue(re.match(r'[9-a]', '_', re.I)) self.assertIsNone(re.match(r'[9-A]', '_', re.I)) self.assertTrue(re.match(r'[\xc0-\xde]', '\xd7', re.I)) self.assertIsNone(re.match(r'[\xc0-\xde]', '\xf7', re.I)) self.assertTrue(re.match(r'[\xe0-\xfe]', '\xf7',re.I)) self.assertIsNone(re.match(r'[\xe0-\xfe]', '\xd7', re.I)) if have_unicode: self.assertTrue(re.match(u(r'[9-a]'), u(r'_'), re.U | re.I)) self.assertIsNone(re.match(u(r'[9-A]'), u(r'_'), re.U | re.I)) self.assertTrue(re.match(u(r'[\xc0-\xde]'), u(r'\xd7'), re.U | re.I)) self.assertIsNone(re.match(u(r'[\xc0-\xde]'), u(r'\xf7'), re.U | re.I)) self.assertTrue(re.match(u(r'[\xe0-\xfe]'), u(r'\xf7'), re.U | re.I)) self.assertIsNone(re.match(u(r'[\xe0-\xfe]'), u(r'\xd7'), re.U | re.I)) self.assertTrue(re.match(u(r'[\u0430-\u045f]'), u(r'\u0450'), re.U | re.I)) self.assertTrue(re.match(u(r'[\u0430-\u045f]'), u(r'\u0400'), re.U | re.I)) self.assertTrue(re.match(u(r'[\u0400-\u042f]'), u(r'\u0450'), re.U | re.I)) self.assertTrue(re.match(u(r'[\u0400-\u042f]'), u(r'\u0400'), re.U | re.I)) if sys.maxunicode > 0xffff: self.assertTrue(re.match(u(r'[\U00010428-\U0001044f]'), u(r'\U00010428'), re.U | re.I)) self.assertTrue(re.match(u(r'[\U00010428-\U0001044f]'), u(r'\U00010400'), re.U | re.I)) self.assertTrue(re.match(u(r'[\U00010400-\U00010427]'), u(r'\U00010428'), re.U | re.I)) self.assertTrue(re.match(u(r'[\U00010400-\U00010427]'), u(r'\U00010400'), re.U | re.I)) assert u(r'\u212a').lower() == u'k' # 'K' self.assertTrue(re.match(ur'[J-M]', u(r'\u212a'), re.U | re.I)) self.assertTrue(re.match(ur'[j-m]', u(r'\u212a'), re.U | re.I)) self.assertTrue(re.match(u(r'[\u2129-\u212b]'), u'K', re.U | re.I)) self.assertTrue(re.match(u(r'[\u2129-\u212b]'), u'k', re.U | re.I)) assert u(r'\u017f').upper() == u'S' # 'ſ' self.assertTrue(re.match(ur'[R-T]', u(r'\u017f'), re.U | re.I)) self.assertTrue(re.match(ur'[r-t]', u(r'\u017f'), re.U | re.I)) self.assertTrue(re.match(u(r'[\u017e-\u0180]'), u'S', re.U | re.I)) self.assertTrue(re.match(u(r'[\u017e-\u0180]'), u's', re.U | re.I)) def test_category(self): self.assertEqual(re.match(r"(\s)", " ").group(1), " ") def test_getlower(self): import _sre self.assertEqual(_sre.getlower(ord('A'), 0), ord('a')) self.assertEqual(_sre.getlower(ord('A'), re.LOCALE), ord('a')) if have_unicode: self.assertEqual(_sre.getlower(ord('A'), re.UNICODE), ord('a')) self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC") self.assertEqual(re.match("abc", u"ABC", re.I).group(0), "ABC") def test_not_literal(self): self.assertEqual(re.search("\s([^a])", " b").group(1), "b") self.assertEqual(re.search("\s([^a]*)", " bb").group(1), "bb") def test_search_coverage(self): self.assertEqual(re.search("\s(b)", " b").group(1), "b") self.assertEqual(re.search("a\s", "a ").group(0), "a ") def assertMatch(self, pattern, text, match=None, span=None, matcher=re.match): if match is None and span is None: # the pattern matches the whole text match = text span = (0, len(text)) elif match is None or span is None: raise ValueError('If match is not None, span should be specified ' '(and vice versa).') m = matcher(pattern, text) self.assertTrue(m) self.assertEqual(m.group(), match) self.assertEqual(m.span(), span) @requires_unicode def test_re_escape(self): alnum_chars = unicode(string.ascii_letters + string.digits) p = u''.join(unichr(i) for i in range(256)) for c in p: if c in alnum_chars: self.assertEqual(re.escape(c), c) elif c == u'\x00': self.assertEqual(re.escape(c), u'\\000') else: self.assertEqual(re.escape(c), u'\\' + c) self.assertMatch(re.escape(c), c) self.assertMatch(re.escape(p), p) def test_re_escape_byte(self): alnum_chars = string.ascii_letters + string.digits p = ''.join(chr(i) for i in range(256)) for b in p: if b in alnum_chars: self.assertEqual(re.escape(b), b) elif b == b'\x00': self.assertEqual(re.escape(b), b'\\000') else: self.assertEqual(re.escape(b), b'\\' + b) self.assertMatch(re.escape(b), b) self.assertMatch(re.escape(p), p) @requires_unicode def test_re_escape_non_ascii(self): s = u(r'xxx\u2620\u2620\u2620xxx') s_escaped = re.escape(s) self.assertEqual(s_escaped, u(r'xxx\\\u2620\\\u2620\\\u2620xxx')) self.assertMatch(s_escaped, s) self.assertMatch(u'.%s+.' % re.escape(unichr(0x2620)), s, u(r'x\u2620\u2620\u2620x'), (2, 7), re.search) def test_re_escape_non_ascii_bytes(self): b = b'y\xe2\x98\xa0y\xe2\x98\xa0y' b_escaped = re.escape(b) self.assertEqual(b_escaped, b'y\\\xe2\\\x98\\\xa0y\\\xe2\\\x98\\\xa0y') self.assertMatch(b_escaped, b) res = re.findall(re.escape(b'\xe2\x98\xa0'), b) self.assertEqual(len(res), 2) def test_pickling(self): import pickle self.pickle_test(pickle) import cPickle self.pickle_test(cPickle) # old pickles expect the _compile() reconstructor in sre module import_module("sre", deprecated=True) from sre import _compile # current pickle expects the _compile() reconstructor in re module from re import _compile def pickle_test(self, pickle): oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)') for proto in range(pickle.HIGHEST_PROTOCOL + 1): pickled = pickle.dumps(oldpat, proto) newpat = pickle.loads(pickled) self.assertEqual(newpat, oldpat) def test_constants(self): self.assertEqual(re.I, re.IGNORECASE) self.assertEqual(re.L, re.LOCALE) self.assertEqual(re.M, re.MULTILINE) self.assertEqual(re.S, re.DOTALL) self.assertEqual(re.X, re.VERBOSE) def test_flags(self): for flag in [re.I, re.M, re.X, re.S, re.L]: self.assertTrue(re.compile('^pattern$', flag)) def test_sre_character_literals(self): for i in [0, 8, 16, 32, 64, 127, 128, 255]: self.assertTrue(re.match(r"\%03o" % i, chr(i))) self.assertTrue(re.match(r"\%03o0" % i, chr(i)+"0")) self.assertTrue(re.match(r"\%03o8" % i, chr(i)+"8")) self.assertTrue(re.match(r"\x%02x" % i, chr(i))) self.assertTrue(re.match(r"\x%02x0" % i, chr(i)+"0")) self.assertTrue(re.match(r"\x%02xz" % i, chr(i)+"z")) self.assertRaises(re.error, re.match, "\911", "") def test_sre_character_class_literals(self): for i in [0, 8, 16, 32, 64, 127, 128, 255]: self.assertTrue(re.match(r"[\%03o]" % i, chr(i))) self.assertTrue(re.match(r"[\%03o0]" % i, chr(i))) self.assertTrue(re.match(r"[\%03o8]" % i, chr(i))) self.assertTrue(re.match(r"[\x%02x]" % i, chr(i))) self.assertTrue(re.match(r"[\x%02x0]" % i, chr(i))) self.assertTrue(re.match(r"[\x%02xz]" % i, chr(i))) self.assertRaises(re.error, re.match, "[\911]", "") def test_bug_113254(self): self.assertEqual(re.match(r'(a)|(b)', 'b').start(1), -1) self.assertEqual(re.match(r'(a)|(b)', 'b').end(1), -1) self.assertEqual(re.match(r'(a)|(b)', 'b').span(1), (-1, -1)) def test_bug_527371(self): # bug described in patches 527371/672491 self.assertIsNone(re.match(r'(a)?a','a').lastindex) self.assertEqual(re.match(r'(a)(b)?b','ab').lastindex, 1) self.assertEqual(re.match(r'(?P<a>a)(?P<b>b)?b','ab').lastgroup, 'a') self.assertEqual(re.match("(?P<a>a(b))", "ab").lastgroup, 'a') self.assertEqual(re.match("((a))", "a").lastindex, 1) def test_bug_545855(self): # bug 545855 -- This pattern failed to cause a compile error as it # should, instead provoking a TypeError. self.assertRaises(re.error, re.compile, 'foo[a-') def test_bug_418626(self): # bugs 418626 at al. -- Testing Greg Chapman's addition of op code # SRE_OP_MIN_REPEAT_ONE for eliminating recursion on simple uses of # pattern '*?' on a long string. self.assertEqual(re.match('.*?c', 10000*'ab'+'cd').end(0), 20001) self.assertEqual(re.match('.*?cd', 5000*'ab'+'c'+5000*'ab'+'cde').end(0), 20003) self.assertEqual(re.match('.*?cd', 20000*'abc'+'de').end(0), 60001) # non-simple '*?' still used to hit the recursion limit, before the # non-recursive scheme was implemented. self.assertEqual(re.search('(a|b)*?c', 10000*'ab'+'cd').end(0), 20001) @requires_unicode def test_bug_612074(self): pat=u"["+re.escape(unichr(0x2039))+u"]" self.assertEqual(re.compile(pat) and 1, 1) def test_stack_overflow(self): # nasty cases that used to overflow the straightforward recursive # implementation of repeated groups. self.assertEqual(re.match('(x)*', 50000*'x').group(1), 'x') self.assertEqual(re.match('(x)*y', 50000*'x'+'y').group(1), 'x') self.assertEqual(re.match('(x)*?y', 50000*'x'+'y').group(1), 'x') def test_unlimited_zero_width_repeat(self): # Issue #9669 self.assertIsNone(re.match(r'(?:a?)*y', 'z')) self.assertIsNone(re.match(r'(?:a?)+y', 'z')) self.assertIsNone(re.match(r'(?:a?){2,}y', 'z')) self.assertIsNone(re.match(r'(?:a?)*?y', 'z')) self.assertIsNone(re.match(r'(?:a?)+?y', 'z')) self.assertIsNone(re.match(r'(?:a?){2,}?y', 'z')) def test_scanner(self): def s_ident(scanner, token): return token def s_operator(scanner, token): return "op%s" % token def s_float(scanner, token): return float(token) def s_int(scanner, token): return int(token) scanner = Scanner([ (r"[a-zA-Z_]\w*", s_ident), (r"\d+\.\d*", s_float), (r"\d+", s_int), (r"=|\+|-|\*|/", s_operator), (r"\s+", None), ]) self.assertTrue(scanner.scanner.scanner("").pattern) self.assertEqual(scanner.scan("sum = 3*foo + 312.50 + bar"), (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], '')) def test_bug_448951(self): # bug 448951 (similar to 429357, but with single char match) # (Also test greedy matches.) for op in '','?','*': self.assertEqual(re.match(r'((.%s):)?z'%op, 'z').groups(), (None, None)) self.assertEqual(re.match(r'((.%s):)?z'%op, 'a:z').groups(), ('a:', 'a')) def test_bug_725106(self): # capturing groups in alternatives in repeats self.assertEqual(re.match('^((a)|b)*', 'abc').groups(), ('b', 'a')) self.assertEqual(re.match('^(([ab])|c)*', 'abc').groups(), ('c', 'b')) self.assertEqual(re.match('^((d)|[ab])*', 'abc').groups(), ('b', None)) self.assertEqual(re.match('^((a)c|[ab])*', 'abc').groups(), ('b', None)) self.assertEqual(re.match('^((a)|b)*?c', 'abc').groups(), ('b', 'a')) self.assertEqual(re.match('^(([ab])|c)*?d', 'abcd').groups(), ('c', 'b')) self.assertEqual(re.match('^((d)|[ab])*?c', 'abc').groups(), ('b', None)) self.assertEqual(re.match('^((a)c|[ab])*?c', 'abc').groups(), ('b', None)) def test_bug_725149(self): # mark_stack_base restoring before restoring marks self.assertEqual(re.match('(a)(?:(?=(b)*)c)*', 'abb').groups(), ('a', None)) self.assertEqual(re.match('(a)((?!(b)*))*', 'abb').groups(), ('a', None, None)) @requires_unicode def test_bug_764548(self): # bug 764548, re.compile() barfs on str/unicode subclasses class my_unicode(unicode): pass pat = re.compile(my_unicode("abc")) self.assertIsNone(pat.match("xyz")) def test_finditer(self): iter = re.finditer(r":+", "a:b::c:::d") self.assertEqual([item.group(0) for item in iter], [":", "::", ":::"]) @requires_unicode def test_bug_926075(self): self.assertIsNot(re.compile('bug_926075'), re.compile(u'bug_926075')) @requires_unicode def test_bug_931848(self): pattern = u(r"[\u002E\u3002\uFF0E\uFF61]") self.assertEqual(re.compile(pattern).split("a.b.c"), ['a','b','c']) def test_bug_581080(self): iter = re.finditer(r"\s", "a b") self.assertEqual(iter.next().span(), (1,2)) self.assertRaises(StopIteration, iter.next) scanner = re.compile(r"\s").scanner("a b") self.assertEqual(scanner.search().span(), (1, 2)) self.assertIsNone(scanner.search()) def test_bug_817234(self): iter = re.finditer(r".*", "asdf") self.assertEqual(iter.next().span(), (0, 4)) self.assertEqual(iter.next().span(), (4, 4)) self.assertRaises(StopIteration, iter.next) @requires_unicode def test_bug_6561(self): # '\d' should match characters in Unicode category 'Nd' # (Number, Decimal Digit), but not those in 'Nl' (Number, # Letter) or 'No' (Number, Other). decimal_digits = [ unichr(0x0037), # '\N{DIGIT SEVEN}', category 'Nd' unichr(0x0e58), # '\N{THAI DIGIT SIX}', category 'Nd' unichr(0xff10), # '\N{FULLWIDTH DIGIT ZERO}', category 'Nd' ] for x in decimal_digits: self.assertEqual(re.match('^\d$', x, re.UNICODE).group(0), x) not_decimal_digits = [ unichr(0x2165), # '\N{ROMAN NUMERAL SIX}', category 'Nl' unichr(0x3039), # '\N{HANGZHOU NUMERAL TWENTY}', category 'Nl' unichr(0x2082), # '\N{SUBSCRIPT TWO}', category 'No' unichr(0x32b4), # '\N{CIRCLED NUMBER THIRTY NINE}', category 'No' ] for x in not_decimal_digits: self.assertIsNone(re.match('^\d$', x, re.UNICODE)) def test_empty_array(self): # SF buf 1647541 import array typecodes = 'cbBhHiIlLfd' if have_unicode: typecodes += 'u' for typecode in typecodes: a = array.array(typecode) self.assertIsNone(re.compile("bla").match(a)) self.assertEqual(re.compile("").match(a).groups(), ()) @requires_unicode def test_inline_flags(self): # Bug #1700 upper_char = unichr(0x1ea0) # Latin Capital Letter A with Dot Bellow lower_char = unichr(0x1ea1) # Latin Small Letter A with Dot Bellow p = re.compile(upper_char, re.I | re.U) q = p.match(lower_char) self.assertTrue(q) p = re.compile(lower_char, re.I | re.U) q = p.match(upper_char) self.assertTrue(q) p = re.compile('(?i)' + upper_char, re.U) q = p.match(lower_char) self.assertTrue(q) p = re.compile('(?i)' + lower_char, re.U) q = p.match(upper_char) self.assertTrue(q) p = re.compile('(?iu)' + upper_char) q = p.match(lower_char) self.assertTrue(q) p = re.compile('(?iu)' + lower_char) q = p.match(upper_char) self.assertTrue(q) def test_dollar_matches_twice(self): "$ matches the end of string, and just before the terminating \n" pattern = re.compile('$') self.assertEqual(pattern.sub('#', 'a\nb\n'), 'a\nb#\n#') self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a\nb\nc#') self.assertEqual(pattern.sub('#', '\n'), '#\n#') pattern = re.compile('$', re.MULTILINE) self.assertEqual(pattern.sub('#', 'a\nb\n' ), 'a#\nb#\n#' ) self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a#\nb#\nc#') self.assertEqual(pattern.sub('#', '\n'), '#\n#') def test_dealloc(self): # issue 3299: check for segfault in debug build import _sre # the overflow limit is different on wide and narrow builds and it # depends on the definition of SRE_CODE (see sre.h). # 2**128 should be big enough to overflow on both. For smaller values # a RuntimeError is raised instead of OverflowError. long_overflow = 2**128 self.assertRaises(TypeError, re.finditer, "a", {}) self.assertRaises(OverflowError, _sre.compile, "abc", 0, [long_overflow]) def test_compile(self): # Test return value when given string and pattern as parameter pattern = re.compile('random pattern') self.assertIsInstance(pattern, re._pattern_type) same_pattern = re.compile(pattern) self.assertIsInstance(same_pattern, re._pattern_type) self.assertIs(same_pattern, pattern) # Test behaviour when not given a string or pattern as parameter self.assertRaises(TypeError, re.compile, 0) def test_bug_13899(self): # Issue #13899: re pattern r"[\A]" should work like "A" but matches # nothing. Ditto B and Z. self.assertEqual(re.findall(r'[\A\B\b\C\Z]', 'AB\bCZ'), ['A', 'B', '\b', 'C', 'Z']) @precisionbigmemtest(size=_2G, memuse=1) def test_large_search(self, size): # Issue #10182: indices were 32-bit-truncated. s = 'a' * size m = re.search('$', s) self.assertIsNotNone(m) self.assertEqual(m.start(), size) self.assertEqual(m.end(), size) # The huge memuse is because of re.sub() using a list and a join() # to create the replacement result. @precisionbigmemtest(size=_2G, memuse=16 + 2) def test_large_subn(self, size): # Issue #10182: indices were 32-bit-truncated. s = 'a' * size r, n = re.subn('', '', s) self.assertEqual(r, s) self.assertEqual(n, size + 1) def test_repeat_minmax_overflow(self): # Issue #13169 string = "x" * 100000 self.assertEqual(re.match(r".{65535}", string).span(), (0, 65535)) self.assertEqual(re.match(r".{,65535}", string).span(), (0, 65535)) self.assertEqual(re.match(r".{65535,}?", string).span(), (0, 65535)) self.assertEqual(re.match(r".{65536}", string).span(), (0, 65536)) self.assertEqual(re.match(r".{,65536}", string).span(), (0, 65536)) self.assertEqual(re.match(r".{65536,}?", string).span(), (0, 65536)) # 2**128 should be big enough to overflow both SRE_CODE and Py_ssize_t. self.assertRaises(OverflowError, re.compile, r".{%d}" % 2**128) self.assertRaises(OverflowError, re.compile, r".{,%d}" % 2**128) self.assertRaises(OverflowError, re.compile, r".{%d,}?" % 2**128) self.assertRaises(OverflowError, re.compile, r".{%d,%d}" % (2**129, 2**128)) @cpython_only def test_repeat_minmax_overflow_maxrepeat(self): try: from _sre import MAXREPEAT except ImportError: self.skipTest('requires _sre.MAXREPEAT constant') string = "x" * 100000 self.assertIsNone(re.match(r".{%d}" % (MAXREPEAT - 1), string)) self.assertEqual(re.match(r".{,%d}" % (MAXREPEAT - 1), string).span(), (0, 100000)) self.assertIsNone(re.match(r".{%d,}?" % (MAXREPEAT - 1), string)) self.assertRaises(OverflowError, re.compile, r".{%d}" % MAXREPEAT) self.assertRaises(OverflowError, re.compile, r".{,%d}" % MAXREPEAT) self.assertRaises(OverflowError, re.compile, r".{%d,}?" % MAXREPEAT) def test_backref_group_name_in_exception(self): # Issue 17341: Poor error message when compiling invalid regex with self.assertRaisesRegexp(sre_constants.error, '<foo>'): re.compile('(?P=<foo>)') def test_group_name_in_exception(self): # Issue 17341: Poor error message when compiling invalid regex with self.assertRaisesRegexp(sre_constants.error, '\?foo'): re.compile('(?P<?foo>)') def test_issue17998(self): for reps in '*', '+', '?', '{1}': for mod in '', '?': pattern = '.' + reps + mod + 'yz' self.assertEqual(re.compile(pattern, re.S).findall('xyz'), ['xyz'], msg=pattern) if have_unicode: pattern = unicode(pattern) self.assertEqual(re.compile(pattern, re.S).findall(u'xyz'), [u'xyz'], msg=pattern) def test_bug_2537(self): # issue 2537: empty submatches for outer_op in ('{0,}', '*', '+', '{1,187}'): for inner_op in ('{0,}', '*', '?'): r = re.compile("^((x|y)%s)%s" % (inner_op, outer_op)) m = r.match("xyyzy") self.assertEqual(m.group(0), "xyy") self.assertEqual(m.group(1), "") self.assertEqual(m.group(2), "y") def test_debug_flag(self): pat = r'(\.)(?:[ch]|py)(?(1)$|: )' with captured_stdout() as out: re.compile(pat, re.DEBUG) dump = '''\ subpattern 1 literal 46 subpattern None branch in literal 99 literal 104 or literal 112 literal 121 subpattern None groupref_exists 1 at at_end else literal 58 literal 32 ''' self.assertEqual(out.getvalue(), dump) # Debug output is output again even a second time (bypassing # the cache -- issue #20426). with captured_stdout() as out: re.compile(pat, re.DEBUG) self.assertEqual(out.getvalue(), dump) def test_keyword_parameters(self): # Issue #20283: Accepting the string keyword parameter. pat = re.compile(r'(ab)') self.assertEqual( pat.match(string='abracadabra', pos=7, endpos=10).span(), (7, 9)) self.assertEqual( pat.search(string='abracadabra', pos=3, endpos=10).span(), (7, 9)) self.assertEqual( pat.findall(string='abracadabra', pos=3, endpos=10), ['ab']) self.assertEqual( pat.split(string='abracadabra', maxsplit=1), ['', 'ab', 'racadabra']) def test_match_group_takes_long(self): self.assertEqual(re.match("(foo)", "foo").group(1L), "foo") self.assertRaises(IndexError, re.match("", "").group, sys.maxint + 1) def test_locale_caching(self): # Issue #22410 oldlocale = locale.setlocale(locale.LC_CTYPE) self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) for loc in 'en_US.iso88591', 'en_US.utf8': try: locale.setlocale(locale.LC_CTYPE, loc) except locale.Error: # Unsupported locale on this system self.skipTest('test needs %s locale' % loc) re.purge() self.check_en_US_iso88591() self.check_en_US_utf8() re.purge() self.check_en_US_utf8() self.check_en_US_iso88591() def check_en_US_iso88591(self): locale.setlocale(locale.LC_CTYPE, 'en_US.iso88591') self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I)) self.assertTrue(re.match(b'\xc5', b'\xe5', re.L|re.I)) self.assertTrue(re.match(b'\xe5', b'\xc5', re.L|re.I)) self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5')) self.assertTrue(re.match(b'(?Li)\xc5', b'\xe5')) self.assertTrue(re.match(b'(?Li)\xe5', b'\xc5')) def check_en_US_utf8(self): locale.setlocale(locale.LC_CTYPE, 'en_US.utf8') self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I)) self.assertIsNone(re.match(b'\xc5', b'\xe5', re.L|re.I)) self.assertIsNone(re.match(b'\xe5', b'\xc5', re.L|re.I)) self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5')) self.assertIsNone(re.match(b'(?Li)\xc5', b'\xe5')) self.assertIsNone(re.match(b'(?Li)\xe5', b'\xc5')) def run_re_tests(): from test.re_tests import tests, SUCCEED, FAIL, SYNTAX_ERROR if verbose: print 'Running re_tests test suite' else: # To save time, only run the first and last 10 tests #tests = tests[:10] + tests[-10:] pass for t in tests: sys.stdout.flush() pattern = s = outcome = repl = expected = None if len(t) == 5: pattern, s, outcome, repl, expected = t elif len(t) == 3: pattern, s, outcome = t else: raise ValueError, ('Test tuples should have 3 or 5 fields', t) try: obj = re.compile(pattern) except re.error: if outcome == SYNTAX_ERROR: pass # Expected a syntax error else: print '=== Syntax error:', t except KeyboardInterrupt: raise KeyboardInterrupt except: print '*** Unexpected error ***', t if verbose: traceback.print_exc(file=sys.stdout) else: try: result = obj.search(s) except re.error, msg: print '=== Unexpected exception', t, repr(msg) if outcome == SYNTAX_ERROR: # This should have been a syntax error; forget it. pass elif outcome == FAIL: if result is None: pass # No match, as expected else: print '=== Succeeded incorrectly', t elif outcome == SUCCEED: if result is not None: # Matched, as expected, so now we compute the # result string and compare it to our expected result. start, end = result.span(0) vardict={'found': result.group(0), 'groups': result.group(), 'flags': result.re.flags} for i in range(1, 100): try: gi = result.group(i) # Special hack because else the string concat fails: if gi is None: gi = "None" except IndexError: gi = "Error" vardict['g%d' % i] = gi for i in result.re.groupindex.keys(): try: gi = result.group(i) if gi is None: gi = "None" except IndexError: gi = "Error" vardict[i] = gi repl = eval(repl, vardict) if repl != expected: print '=== grouping error', t, print repr(repl) + ' should be ' + repr(expected) else: print '=== Failed incorrectly', t # Try the match on a unicode string, and check that it # still succeeds. try: result = obj.search(unicode(s, "latin-1")) if result is None: print '=== Fails on unicode match', t except NameError: continue # 1.5.2 except TypeError: continue # unicode test case # Try the match on a unicode pattern, and check that it # still succeeds. obj=re.compile(unicode(pattern, "latin-1")) result = obj.search(s) if result is None: print '=== Fails on unicode pattern match', t # Try the match with the search area limited to the extent # of the match and see if it still succeeds. \B will # break (because it won't match at the end or start of a # string), so we'll ignore patterns that feature it. if pattern[:2] != '\\B' and pattern[-2:] != '\\B' \ and result is not None: obj = re.compile(pattern) result = obj.search(s, result.start(0), result.end(0) + 1) if result is None: print '=== Failed on range-limited match', t # Try the match with IGNORECASE enabled, and check that it # still succeeds. obj = re.compile(pattern, re.IGNORECASE) result = obj.search(s) if result is None: print '=== Fails on case-insensitive match', t # Try the match with LOCALE enabled, and check that it # still succeeds. obj = re.compile(pattern, re.LOCALE) result = obj.search(s) if result is None: print '=== Fails on locale-sensitive match', t # Try the match with UNICODE locale enabled, and check # that it still succeeds. obj = re.compile(pattern, re.UNICODE) result = obj.search(s) if result is None: print '=== Fails on unicode-sensitive match', t def test_main(): run_unittest(ReTests) run_re_tests() if __name__ == "__main__": test_main()
Distrotech/mozjs
refs/heads/mozjs-24
js/src/python/mozbuild/dumbmake/__init__.py
12133432
oberlin/django
refs/heads/master
tests/custom_migration_operations/__init__.py
12133432
overtherain/scriptfile
refs/heads/master
software/googleAppEngine/lib/django_1_3/tests/regressiontests/admin_scripts/app_with_import/__init__.py
12133432
groschovskiy/lerigos_music
refs/heads/master
Server/API/lib/google/api/__init__.py
12133432
Edraak/edx-platform
refs/heads/master
pavelib/paver_tests/__init__.py
12133432
th3sys/capsule
refs/heads/master
contracts.py
1
import logging import datetime from dateutil.relativedelta import relativedelta class Futures: VX = 'VX' class SecurityDefinition(object): def __init__(self): self.Logger = logging.getLogger() self.Logger.setLevel(logging.INFO) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s') self.Logger.info('Security Created.') self.__M = {1: "F", 2: "G", 3: "H", 4: "J", 5: "K", 6: "M", 7: "N", 8: "Q", 9: "U", 10: "V", 11: "X", 12: "Z"} self.__Supported = {'VX': 'VX'} # symbols and future prefix # lifted from https://github.com/conor10/examples/blob/master/python/expiries/vix.py @staticmethod def __get_vix_expiry_date(date): """ http://cfe.cboe.com/products/spec_vix.aspx TERMINATION OF TRADING: Trading hours for expiring VIX futures contracts end at 7:00 a.m. Chicago time on the final settlement date. FINAL SETTLEMENT DATE: The Wednesday that is thirty days prior to the third Friday of the calendar month immediately following the month in which the contract expires ("Final Settlement Date"). If the third Friday of the month subsequent to expiration of the applicable VIX futures contract is a CBOE holiday, the Final Settlement Date for the contract shall be thirty days prior to the CBOE business day immediately preceding that Friday. """ # Date of third friday of the following month if date.month == 12: third_friday_next_month = datetime.date(date.year + 1, 1, 15) else: third_friday_next_month = datetime.date(date.year, date.month + 1, 15) one_day = datetime.timedelta(days=1) thirty_days = datetime.timedelta(days=30) while third_friday_next_month.weekday() != 4: # Using += results in a timedelta object third_friday_next_month = third_friday_next_month + one_day # TODO: Incorporate check that it's a trading day, if so move the 3rd # Friday back by one day before subtracting return third_friday_next_month - thirty_days def __get_vix(self, date): return "%s%s%s" % (self.__Supported[Futures.VX], self.__M[date.month], str(date.year)[-1:]) def get_next_expiry_date(self, symbol, today): try: if symbol not in self.__Supported: raise Exception('Symbol %s not supported' % symbol) # TODO: add support for more contracts if symbol == Futures.VX: return self.__get_vix_expiry_date(today) except Exception as e: self.Logger.error(e) return None def get_next_expiry(self, symbol, today): try: if symbol not in self.__Supported: raise Exception('Symbol %s not supported' % symbol) # TODO: add support for more contracts if symbol == Futures.VX: expiry = self.__get_vix_expiry_date(today) return self.__get_vix(today if today < expiry else today + relativedelta(months=+1)) except Exception as e: self.Logger.error(e) return None def get_front_month_future(self, symbol): today = datetime.datetime.today().date() return self.get_next_expiry(symbol, today) def get_futures(self, symbol, n, date=None): try: if n < 2: raise Exception('Just use get_front_month_future if n < 2') if symbol not in self.__Supported: raise Exception('Symbol %s not supported' % symbol) today = datetime.datetime.today().date() if date is None else date futures = [] front = self.get_next_expiry(symbol, today) futures.append(front) # TODO: add support for more contracts if symbol == Futures.VX: expiry = self.__get_vix_expiry_date(today) else: expiry = today roll = 1 if today < expiry else 2 nextMonth = datetime.date(today.year, today.month, 1) + relativedelta(months=+roll) for i in range(1, n): future = self.get_next_expiry(symbol, nextMonth) futures.append(future) nextMonth += relativedelta(months=+1) return futures except Exception as e: self.Logger.error(e) return None
joymarquis/mscc
refs/heads/master
projects/swtec/utils/fwdl/lib-python/pyserial-3.0.1/serial/win32.py
11
#! python # # Constants and types for use with Windows API, used by serialwin32.py # # This file is part of pySerial. https://github.com/pyserial/pyserial # (C) 2001-2015 Chris Liechti <cliechti@gmx.net> # # SPDX-License-Identifier: BSD-3-Clause from ctypes import * from ctypes.wintypes import HANDLE from ctypes.wintypes import BOOL from ctypes.wintypes import LPCWSTR from ctypes.wintypes import DWORD from ctypes.wintypes import WORD from ctypes.wintypes import BYTE _stdcall_libraries = {} _stdcall_libraries['kernel32'] = WinDLL('kernel32') INVALID_HANDLE_VALUE = HANDLE(-1).value # some details of the windows API differ between 32 and 64 bit systems.. def is_64bit(): """Returns true when running on a 64 bit system""" return sizeof(c_ulong) != sizeof(c_void_p) # ULONG_PTR is a an ordinary number, not a pointer and contrary to the name it # is either 32 or 64 bits, depending on the type of windows... # so test if this a 32 bit windows... if is_64bit(): # assume 64 bits ULONG_PTR = c_int64 else: # 32 bits ULONG_PTR = c_ulong class _SECURITY_ATTRIBUTES(Structure): pass LPSECURITY_ATTRIBUTES = POINTER(_SECURITY_ATTRIBUTES) try: CreateEventW = _stdcall_libraries['kernel32'].CreateEventW except AttributeError: # Fallback to non wide char version for old OS... from ctypes.wintypes import LPCSTR CreateEventA = _stdcall_libraries['kernel32'].CreateEventA CreateEventA.restype = HANDLE CreateEventA.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCSTR] CreateEvent = CreateEventA CreateFileA = _stdcall_libraries['kernel32'].CreateFileA CreateFileA.restype = HANDLE CreateFileA.argtypes = [LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE] CreateFile = CreateFileA else: CreateEventW.restype = HANDLE CreateEventW.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] CreateEvent = CreateEventW # alias CreateFileW = _stdcall_libraries['kernel32'].CreateFileW CreateFileW.restype = HANDLE CreateFileW.argtypes = [LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE] CreateFile = CreateFileW # alias class _OVERLAPPED(Structure): pass OVERLAPPED = _OVERLAPPED class _COMSTAT(Structure): pass COMSTAT = _COMSTAT class _DCB(Structure): pass DCB = _DCB class _COMMTIMEOUTS(Structure): pass COMMTIMEOUTS = _COMMTIMEOUTS GetLastError = _stdcall_libraries['kernel32'].GetLastError GetLastError.restype = DWORD GetLastError.argtypes = [] LPOVERLAPPED = POINTER(_OVERLAPPED) LPDWORD = POINTER(DWORD) GetOverlappedResult = _stdcall_libraries['kernel32'].GetOverlappedResult GetOverlappedResult.restype = BOOL GetOverlappedResult.argtypes = [HANDLE, LPOVERLAPPED, LPDWORD, BOOL] ResetEvent = _stdcall_libraries['kernel32'].ResetEvent ResetEvent.restype = BOOL ResetEvent.argtypes = [HANDLE] LPCVOID = c_void_p WriteFile = _stdcall_libraries['kernel32'].WriteFile WriteFile.restype = BOOL WriteFile.argtypes = [HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED] LPVOID = c_void_p ReadFile = _stdcall_libraries['kernel32'].ReadFile ReadFile.restype = BOOL ReadFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED] CloseHandle = _stdcall_libraries['kernel32'].CloseHandle CloseHandle.restype = BOOL CloseHandle.argtypes = [HANDLE] ClearCommBreak = _stdcall_libraries['kernel32'].ClearCommBreak ClearCommBreak.restype = BOOL ClearCommBreak.argtypes = [HANDLE] LPCOMSTAT = POINTER(_COMSTAT) ClearCommError = _stdcall_libraries['kernel32'].ClearCommError ClearCommError.restype = BOOL ClearCommError.argtypes = [HANDLE, LPDWORD, LPCOMSTAT] SetupComm = _stdcall_libraries['kernel32'].SetupComm SetupComm.restype = BOOL SetupComm.argtypes = [HANDLE, DWORD, DWORD] EscapeCommFunction = _stdcall_libraries['kernel32'].EscapeCommFunction EscapeCommFunction.restype = BOOL EscapeCommFunction.argtypes = [HANDLE, DWORD] GetCommModemStatus = _stdcall_libraries['kernel32'].GetCommModemStatus GetCommModemStatus.restype = BOOL GetCommModemStatus.argtypes = [HANDLE, LPDWORD] LPDCB = POINTER(_DCB) GetCommState = _stdcall_libraries['kernel32'].GetCommState GetCommState.restype = BOOL GetCommState.argtypes = [HANDLE, LPDCB] LPCOMMTIMEOUTS = POINTER(_COMMTIMEOUTS) GetCommTimeouts = _stdcall_libraries['kernel32'].GetCommTimeouts GetCommTimeouts.restype = BOOL GetCommTimeouts.argtypes = [HANDLE, LPCOMMTIMEOUTS] PurgeComm = _stdcall_libraries['kernel32'].PurgeComm PurgeComm.restype = BOOL PurgeComm.argtypes = [HANDLE, DWORD] SetCommBreak = _stdcall_libraries['kernel32'].SetCommBreak SetCommBreak.restype = BOOL SetCommBreak.argtypes = [HANDLE] SetCommMask = _stdcall_libraries['kernel32'].SetCommMask SetCommMask.restype = BOOL SetCommMask.argtypes = [HANDLE, DWORD] SetCommState = _stdcall_libraries['kernel32'].SetCommState SetCommState.restype = BOOL SetCommState.argtypes = [HANDLE, LPDCB] SetCommTimeouts = _stdcall_libraries['kernel32'].SetCommTimeouts SetCommTimeouts.restype = BOOL SetCommTimeouts.argtypes = [HANDLE, LPCOMMTIMEOUTS] WaitForSingleObject = _stdcall_libraries['kernel32'].WaitForSingleObject WaitForSingleObject.restype = DWORD WaitForSingleObject.argtypes = [HANDLE, DWORD] ONESTOPBIT = 0 # Variable c_int TWOSTOPBITS = 2 # Variable c_int ONE5STOPBITS = 1 NOPARITY = 0 # Variable c_int ODDPARITY = 1 # Variable c_int EVENPARITY = 2 # Variable c_int MARKPARITY = 3 SPACEPARITY = 4 RTS_CONTROL_HANDSHAKE = 2 # Variable c_int RTS_CONTROL_DISABLE = 0 # Variable c_int RTS_CONTROL_ENABLE = 1 # Variable c_int RTS_CONTROL_TOGGLE = 3 # Variable c_int SETRTS = 3 CLRRTS = 4 DTR_CONTROL_HANDSHAKE = 2 # Variable c_int DTR_CONTROL_DISABLE = 0 # Variable c_int DTR_CONTROL_ENABLE = 1 # Variable c_int SETDTR = 5 CLRDTR = 6 MS_DSR_ON = 32 # Variable c_ulong EV_RING = 256 # Variable c_int EV_PERR = 512 # Variable c_int EV_ERR = 128 # Variable c_int SETXOFF = 1 # Variable c_int EV_RXCHAR = 1 # Variable c_int GENERIC_WRITE = 1073741824 # Variable c_long PURGE_TXCLEAR = 4 # Variable c_int FILE_FLAG_OVERLAPPED = 1073741824 # Variable c_int EV_DSR = 16 # Variable c_int MAXDWORD = 4294967295 # Variable c_uint EV_RLSD = 32 # Variable c_int ERROR_SUCCESS = 0 ERROR_IO_PENDING = 997 # Variable c_long MS_CTS_ON = 16 # Variable c_ulong EV_EVENT1 = 2048 # Variable c_int EV_RX80FULL = 1024 # Variable c_int PURGE_RXABORT = 2 # Variable c_int FILE_ATTRIBUTE_NORMAL = 128 # Variable c_int PURGE_TXABORT = 1 # Variable c_int SETXON = 2 # Variable c_int OPEN_EXISTING = 3 # Variable c_int MS_RING_ON = 64 # Variable c_ulong EV_TXEMPTY = 4 # Variable c_int EV_RXFLAG = 2 # Variable c_int MS_RLSD_ON = 128 # Variable c_ulong GENERIC_READ = 2147483648 # Variable c_ulong EV_EVENT2 = 4096 # Variable c_int EV_CTS = 8 # Variable c_int EV_BREAK = 64 # Variable c_int PURGE_RXCLEAR = 8 # Variable c_int INFINITE = 0xFFFFFFFF class N11_OVERLAPPED4DOLLAR_48E(Union): pass class N11_OVERLAPPED4DOLLAR_484DOLLAR_49E(Structure): pass N11_OVERLAPPED4DOLLAR_484DOLLAR_49E._fields_ = [ ('Offset', DWORD), ('OffsetHigh', DWORD), ] PVOID = c_void_p N11_OVERLAPPED4DOLLAR_48E._anonymous_ = ['_0'] N11_OVERLAPPED4DOLLAR_48E._fields_ = [ ('_0', N11_OVERLAPPED4DOLLAR_484DOLLAR_49E), ('Pointer', PVOID), ] _OVERLAPPED._anonymous_ = ['_0'] _OVERLAPPED._fields_ = [ ('Internal', ULONG_PTR), ('InternalHigh', ULONG_PTR), ('_0', N11_OVERLAPPED4DOLLAR_48E), ('hEvent', HANDLE), ] _SECURITY_ATTRIBUTES._fields_ = [ ('nLength', DWORD), ('lpSecurityDescriptor', LPVOID), ('bInheritHandle', BOOL), ] _COMSTAT._fields_ = [ ('fCtsHold', DWORD, 1), ('fDsrHold', DWORD, 1), ('fRlsdHold', DWORD, 1), ('fXoffHold', DWORD, 1), ('fXoffSent', DWORD, 1), ('fEof', DWORD, 1), ('fTxim', DWORD, 1), ('fReserved', DWORD, 25), ('cbInQue', DWORD), ('cbOutQue', DWORD), ] _DCB._fields_ = [ ('DCBlength', DWORD), ('BaudRate', DWORD), ('fBinary', DWORD, 1), ('fParity', DWORD, 1), ('fOutxCtsFlow', DWORD, 1), ('fOutxDsrFlow', DWORD, 1), ('fDtrControl', DWORD, 2), ('fDsrSensitivity', DWORD, 1), ('fTXContinueOnXoff', DWORD, 1), ('fOutX', DWORD, 1), ('fInX', DWORD, 1), ('fErrorChar', DWORD, 1), ('fNull', DWORD, 1), ('fRtsControl', DWORD, 2), ('fAbortOnError', DWORD, 1), ('fDummy2', DWORD, 17), ('wReserved', WORD), ('XonLim', WORD), ('XoffLim', WORD), ('ByteSize', BYTE), ('Parity', BYTE), ('StopBits', BYTE), ('XonChar', c_char), ('XoffChar', c_char), ('ErrorChar', c_char), ('EofChar', c_char), ('EvtChar', c_char), ('wReserved1', WORD), ] _COMMTIMEOUTS._fields_ = [ ('ReadIntervalTimeout', DWORD), ('ReadTotalTimeoutMultiplier', DWORD), ('ReadTotalTimeoutConstant', DWORD), ('WriteTotalTimeoutMultiplier', DWORD), ('WriteTotalTimeoutConstant', DWORD), ] __all__ = ['GetLastError', 'MS_CTS_ON', 'FILE_ATTRIBUTE_NORMAL', 'DTR_CONTROL_ENABLE', '_COMSTAT', 'MS_RLSD_ON', 'GetOverlappedResult', 'SETXON', 'PURGE_TXABORT', 'PurgeComm', 'N11_OVERLAPPED4DOLLAR_48E', 'EV_RING', 'ONESTOPBIT', 'SETXOFF', 'PURGE_RXABORT', 'GetCommState', 'RTS_CONTROL_ENABLE', '_DCB', 'CreateEvent', '_COMMTIMEOUTS', '_SECURITY_ATTRIBUTES', 'EV_DSR', 'EV_PERR', 'EV_RXFLAG', 'OPEN_EXISTING', 'DCB', 'FILE_FLAG_OVERLAPPED', 'EV_CTS', 'SetupComm', 'LPOVERLAPPED', 'EV_TXEMPTY', 'ClearCommBreak', 'LPSECURITY_ATTRIBUTES', 'SetCommBreak', 'SetCommTimeouts', 'COMMTIMEOUTS', 'ODDPARITY', 'EV_RLSD', 'GetCommModemStatus', 'EV_EVENT2', 'PURGE_TXCLEAR', 'EV_BREAK', 'EVENPARITY', 'LPCVOID', 'COMSTAT', 'ReadFile', 'PVOID', '_OVERLAPPED', 'WriteFile', 'GetCommTimeouts', 'ResetEvent', 'EV_RXCHAR', 'LPCOMSTAT', 'ClearCommError', 'ERROR_IO_PENDING', 'EscapeCommFunction', 'GENERIC_READ', 'RTS_CONTROL_HANDSHAKE', 'OVERLAPPED', 'DTR_CONTROL_HANDSHAKE', 'PURGE_RXCLEAR', 'GENERIC_WRITE', 'LPDCB', 'CreateEventW', 'SetCommMask', 'EV_EVENT1', 'SetCommState', 'LPVOID', 'CreateFileW', 'LPDWORD', 'EV_RX80FULL', 'TWOSTOPBITS', 'LPCOMMTIMEOUTS', 'MAXDWORD', 'MS_DSR_ON', 'MS_RING_ON', 'N11_OVERLAPPED4DOLLAR_484DOLLAR_49E', 'EV_ERR', 'ULONG_PTR', 'CreateFile', 'NOPARITY', 'CloseHandle']
z-fork/scrapy
refs/heads/master
scrapy/cmdline.py
84
from __future__ import print_function import sys import optparse import cProfile import inspect import pkg_resources import scrapy from scrapy.crawler import CrawlerProcess from scrapy.xlib import lsprofcalltree from scrapy.commands import ScrapyCommand from scrapy.exceptions import UsageError from scrapy.utils.misc import walk_modules from scrapy.utils.project import inside_project, get_project_settings from scrapy.settings.deprecated import check_deprecated_settings def _iter_command_classes(module_name): # TODO: add `name` attribute to commands and and merge this function with # scrapy.utils.spider.iter_spider_classes for module in walk_modules(module_name): for obj in vars(module).values(): if inspect.isclass(obj) and \ issubclass(obj, ScrapyCommand) and \ obj.__module__ == module.__name__: yield obj def _get_commands_from_module(module, inproject): d = {} for cmd in _iter_command_classes(module): if inproject or not cmd.requires_project: cmdname = cmd.__module__.split('.')[-1] d[cmdname] = cmd() return d def _get_commands_from_entry_points(inproject, group='scrapy.commands'): cmds = {} for entry_point in pkg_resources.iter_entry_points(group): obj = entry_point.load() if inspect.isclass(obj): cmds[entry_point.name] = obj() else: raise Exception("Invalid entry point %s" % entry_point.name) return cmds def _get_commands_dict(settings, inproject): cmds = _get_commands_from_module('scrapy.commands', inproject) cmds.update(_get_commands_from_entry_points(inproject)) cmds_module = settings['COMMANDS_MODULE'] if cmds_module: cmds.update(_get_commands_from_module(cmds_module, inproject)) return cmds def _pop_command_name(argv): i = 0 for arg in argv[1:]: if not arg.startswith('-'): del argv[i] return arg i += 1 def _print_header(settings, inproject): if inproject: print("Scrapy %s - project: %s\n" % (scrapy.__version__, \ settings['BOT_NAME'])) else: print("Scrapy %s - no active project\n" % scrapy.__version__) def _print_commands(settings, inproject): _print_header(settings, inproject) print("Usage:") print(" scrapy <command> [options] [args]\n") print("Available commands:") cmds = _get_commands_dict(settings, inproject) for cmdname, cmdclass in sorted(cmds.items()): print(" %-13s %s" % (cmdname, cmdclass.short_desc())) if not inproject: print() print(" [ more ] More commands available when run from project directory") print() print('Use "scrapy <command> -h" to see more info about a command') def _print_unknown_command(settings, cmdname, inproject): _print_header(settings, inproject) print("Unknown command: %s\n" % cmdname) print('Use "scrapy" to see available commands') def _run_print_help(parser, func, *a, **kw): try: func(*a, **kw) except UsageError as e: if str(e): parser.error(str(e)) if e.print_help: parser.print_help() sys.exit(2) def execute(argv=None, settings=None): if argv is None: argv = sys.argv # --- backwards compatibility for scrapy.conf.settings singleton --- if settings is None and 'scrapy.conf' in sys.modules: from scrapy import conf if hasattr(conf, 'settings'): settings = conf.settings # ------------------------------------------------------------------ if settings is None: settings = get_project_settings() check_deprecated_settings(settings) # --- backwards compatibility for scrapy.conf.settings singleton --- import warnings from scrapy.exceptions import ScrapyDeprecationWarning with warnings.catch_warnings(): warnings.simplefilter("ignore", ScrapyDeprecationWarning) from scrapy import conf conf.settings = settings # ------------------------------------------------------------------ inproject = inside_project() cmds = _get_commands_dict(settings, inproject) cmdname = _pop_command_name(argv) parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), \ conflict_handler='resolve') if not cmdname: _print_commands(settings, inproject) sys.exit(0) elif cmdname not in cmds: _print_unknown_command(settings, cmdname, inproject) sys.exit(2) cmd = cmds[cmdname] parser.usage = "scrapy %s %s" % (cmdname, cmd.syntax()) parser.description = cmd.long_desc() settings.setdict(cmd.default_settings, priority='command') cmd.settings = settings cmd.add_options(parser) opts, args = parser.parse_args(args=argv[1:]) _run_print_help(parser, cmd.process_options, args, opts) cmd.crawler_process = CrawlerProcess(settings) _run_print_help(parser, _run_command, cmd, args, opts) sys.exit(cmd.exitcode) def _run_command(cmd, args, opts): if opts.profile or opts.lsprof: _run_command_profiled(cmd, args, opts) else: cmd.run(args, opts) def _run_command_profiled(cmd, args, opts): if opts.profile: sys.stderr.write("scrapy: writing cProfile stats to %r\n" % opts.profile) if opts.lsprof: sys.stderr.write("scrapy: writing lsprof stats to %r\n" % opts.lsprof) loc = locals() p = cProfile.Profile() p.runctx('cmd.run(args, opts)', globals(), loc) if opts.profile: p.dump_stats(opts.profile) k = lsprofcalltree.KCacheGrind(p) if opts.lsprof: with open(opts.lsprof, 'w') as f: k.output(f) if __name__ == '__main__': execute()
super7ramp/vertaal
refs/heads/master
common/view/decorators.py
2
from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from django.conf import settings from common.view.renders.json import render_to_json #from common.view.renders.xml import render_to_xml class render: '''Register response engines based on HTTP_ACCEPT parameters: template: template for html rendering format: supported formats ('json','xml') @render('index.html') def my_view(request) @render('index.html', ('json','xml')) def my_view(request) html format is supported by default if a template is defined. @render('json') def my_view(request) in above case, json is the default format. @render('json', 'xml') def my_view(request) ''' class render_decorator: def __init__(self, parent, view_func): self.parent = parent self.view_func = view_func def __call__(self, *args, **kwargs): request = args[0] context = self.view_func(*args, **kwargs) if isinstance(context, HttpResponse): return context engine = None if request.META.has_key('HTTP_ACCEPT'): accept = request.META['HTTP_ACCEPT'] for content in self.parent.engines.iterkeys(): if accept.find(content)<>-1: engine, template = self.parent.engines.get(content) break if engine is None: engine, template = self.parent.engines.get(self.parent.default) cook = context.pop('cookjar',None) if 'html'==engine: response = self.html_render(request, context, template) elif 'json'==engine: response = self.json_render(request, context) elif 'xml'==engine: response = self.xml_render(request, context) else: response = context if isinstance(response, HttpResponse): if cook: for k,v in cook.iteritems(): if v is None: response.delete_cookie(str(k)) else: response.set_cookie(str(k), str(v), getattr(settings, 'COMMON_COOKIE_AGE', None)) return response def xml_render(self,request, context): #return render_to_xml(context) pass def json_render(self,request, context): return render_to_json(context) def html_render(self,request, context, template): return render_to_response( template, context, context_instance=RequestContext(request), ) def __register_engine(self, engine, template, default = False): if engine == 'json': content_type = 'application/json' elif engine == 'html': content_type = 'text/html' elif engine == 'xml': content_type = 'text/xml' else: raise ValueError("Unsuported format %s" % engine) if default: self.default = content_type self.engines[content_type] = engine, template def __init__(self, template=None, format=None): self.engines = {} if format is None: format = () elif not isinstance(format, tuple): format = (format,) if template == 'json': self.__register_engine('json', None, True) elif template: self.__register_engine('html', template, True) for f in format: self.__register_engine(f, None) def __call__(self, view_func): return render.render_decorator(self, view_func) # #def render(template=None, format='html'): # # if format=="html" and template is None: # raise ValueError("Template required for html render") # # def render_decorator(view_func): # def engine(*args, **kwargs): # request = args[0] # # render_engine = None # # if request.META.has_key('HTTP_ACCEPT'): # accept = request.META['HTTP_ACCEPT'] # print accept # if 'html'==format: # if 'text/html' in accept: # render_engine = format # elif 'json'==format: # if ('application/json' in accept) or ('json' in accept): # render_engine = format # elif 'xml'==format: # if 'text/xml' in accept: # render_engine = format # # # we are interest to know if there are more renders # # if not, just render the given format # if render_engine is None: # if not view_func.func_code == engine.func_code: # render_engine = format # else: # return view_func(*args, **kwargs) # # context = view_func(*args, **kwargs) # # if isinstance(context, HttpResponse): # return context # # if 'html'==render_engine: # return html_render(request, context) # elif 'json'==render_engine: # return json_render(request, context) # else: # return xml_render(request, context) # # def xlm_render(request, context): # pass # # def json_render(request, context): # return render_to_json(context) # # def html_render(request, context): # return render_to_response( # template, # context, # context_instance=RequestContext(request), # ) # # return engine # # def render_html_decorator(view_func): # def wrapper(*args, **kwargs): # request = args[0] # print request.META['HTTP_ACCEPT'] # context = view_func(*args, **kwargs) # return render_to_response( # template, # context, # context_instance=RequestContext(request), # ) # return wrapper # return render_decorator
pamfilos/data.cern.ch
refs/heads/update-docs
cap/alembic/3d92229a38c5_update_schemas_table.py
4
# # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Update schemas table.""" import sqlalchemy as sa from alembic import op from cap.types import json_type # revision identifiers, used by Alembic. revision = '3d92229a38c5' down_revision = 'f93f479d43f1' branch_labels = () depends_on = None def upgrade(): """Upgrade database.""" op.add_column( 'schema', sa.Column('created', sa.DateTime(), nullable=False, server_default=sa.func.current_timestamp())) op.add_column('schema', sa.Column('deposit_mapping', json_type, nullable=True)) op.add_column('schema', sa.Column('deposit_options', json_type, nullable=True)) op.add_column('schema', sa.Column('deposit_schema', json_type, nullable=True)) op.add_column( 'schema', sa.Column('is_indexed', sa.Boolean(create_constraint=False), nullable=True)) op.add_column('schema', sa.Column('record_mapping', json_type, nullable=True)) op.add_column('schema', sa.Column('record_options', json_type, nullable=True)) op.add_column('schema', sa.Column('record_schema', json_type, nullable=True)) op.add_column( 'schema', sa.Column('updated', sa.DateTime(), nullable=False, server_default=sa.func.current_timestamp())) op.add_column( 'schema', sa.Column('use_deposit_as_record', sa.Boolean(create_constraint=False), nullable=True)) op.drop_column('schema', 'json') op.drop_column('schema', 'is_deposit') def downgrade(): """Downgrade database.""" op.add_column( 'schema', sa.Column('is_deposit', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.add_column( 'schema', sa.Column('json', json_type, autoincrement=False, nullable=True)) op.drop_column('schema', 'use_deposit_as_record') op.drop_column('schema', 'updated') op.drop_column('schema', 'record_schema') op.drop_column('schema', 'record_options') op.drop_column('schema', 'record_mapping') op.drop_column('schema', 'is_indexed') op.drop_column('schema', 'deposit_schema') op.drop_column('schema', 'deposit_options') op.drop_column('schema', 'deposit_mapping') op.drop_column('schema', 'created')
rghe/ansible
refs/heads/devel
lib/ansible/modules/network/ios/ios_logging.py
48
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = """ --- module: ios_logging version_added: "2.4" author: "Trishna Guha (@trishnaguha)" short_description: Manage logging on network devices description: - This module provides declarative management of logging on Cisco Ios devices. notes: - Tested against IOS 15.6 options: dest: description: - Destination of the logs. choices: ['on', 'host', 'console', 'monitor', 'buffered'] name: description: - If value of C(dest) is I(file) it indicates file-name, for I(user) it indicates username and for I(host) indicates the host name to be notified. size: description: - Size of buffer. The acceptable value is in range from 4096 to 4294967295 bytes. default: 4096 facility: description: - Set logging facility. level: description: - Set logging severity levels. aggregate: description: List of logging definitions. state: description: - State of the logging configuration. default: present choices: ['present', 'absent'] extends_documentation_fragment: ios """ EXAMPLES = """ - name: configure host logging ios_logging: dest: host name: 172.16.0.1 state: present - name: remove host logging configuration ios_logging: dest: host name: 172.16.0.1 state: absent - name: configure console logging level and facility ios_logging: dest: console facility: local7 level: debugging state: present - name: enable logging to all ios_logging: dest : on - name: configure buffer size ios_logging: dest: buffered size: 5000 - name: Configure logging using aggregate ios_logging: aggregate: - { dest: console, level: notifications } - { dest: buffered, size: 9000 } - name: remove logging using aggregate ios_logging: aggregate: - { dest: console, level: notifications } - { dest: buffered, size: 9000 } state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always type: list sample: - logging facility local7 - logging host 172.16.0.1 """ import re from copy import deepcopy from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.common.utils import remove_default_spec, validate_ip_address from ansible.module_utils.network.ios.ios import get_config, load_config from ansible.module_utils.network.ios.ios import get_capabilities from ansible.module_utils.network.ios.ios import ios_argument_spec, check_args def validate_size(value, module): if value: if not int(4096) <= int(value) <= int(4294967295): module.fail_json(msg='size must be between 4096 and 4294967295') else: return value def map_obj_to_commands(updates, module, os_version): dest_group = ('console', 'monitor', 'buffered', 'on') commands = list() want, have = updates for w in want: dest = w['dest'] name = w['name'] size = w['size'] facility = w['facility'] level = w['level'] state = w['state'] del w['state'] if facility: w['dest'] = 'facility' if state == 'absent' and w in have: if dest: if dest == 'host': if '12.' in os_version: commands.append('no logging {0}'.format(name)) else: commands.append('no logging host {0}'.format(name)) elif dest in dest_group: commands.append('no logging {0}'.format(dest)) else: module.fail_json(msg='dest must be among console, monitor, buffered, host, on') if facility: commands.append('no logging facility {0}'.format(facility)) if state == 'present' and w not in have: if facility: present = False for entry in have: if entry['dest'] == 'facility' and entry['facility'] == facility: present = True if not present: commands.append('logging facility {0}'.format(facility)) if dest == 'host': if '12.' in os_version: commands.append('logging {0}'.format(name)) else: commands.append('logging host {0}'.format(name)) elif dest == 'on': commands.append('logging on') elif dest == 'buffered' and size: present = False for entry in have: if entry['dest'] == 'buffered' and entry['size'] == size and entry['level'] == level: present = True if not present: if level and level != 'debugging': commands.append('logging buffered {0} {1}'.format(size, level)) else: commands.append('logging buffered {0}'.format(size)) else: if dest: dest_cmd = 'logging {0}'.format(dest) if level: dest_cmd += ' {0}'.format(level) commands.append(dest_cmd) return commands def parse_facility(line, dest): facility = None if dest == 'facility': match = re.search(r'logging facility (\S+)', line, re.M) if match: facility = match.group(1) return facility def parse_size(line, dest): size = None if dest == 'buffered': match = re.search(r'logging buffered(?: (\d+))?(?: [a-z]+)?', line, re.M) if match: if match.group(1) is not None: size = match.group(1) else: size = "4096" return size def parse_name(line, dest): if dest == 'host': match = re.search(r'logging host (\S+)', line, re.M) if match: name = match.group(1) else: name = None return name def parse_level(line, dest): level_group = ('emergencies', 'alerts', 'critical', 'errors', 'warnings', 'notifications', 'informational', 'debugging') if dest == 'host': level = 'debugging' else: if dest == 'buffered': match = re.search(r'logging buffered(?: \d+)?(?: ([a-z]+))?', line, re.M) else: match = re.search(r'logging {0} (\S+)'.format(dest), line, re.M) if match and match.group(1) in level_group: level = match.group(1) else: level = 'debugging' return level def map_config_to_obj(module): obj = [] dest_group = ('console', 'host', 'monitor', 'buffered', 'on', 'facility') data = get_config(module, flags=['| include logging']) for line in data.split('\n'): match = re.search(r'logging (\S+)', line, re.M) if match: if match.group(1) in dest_group: dest = match.group(1) obj.append({ 'dest': dest, 'name': parse_name(line, dest), 'size': parse_size(line, dest), 'facility': parse_facility(line, dest), 'level': parse_level(line, dest) }) elif validate_ip_address(match.group(1)): dest = 'host' obj.append({ 'dest': dest, 'name': match.group(1), 'facility': parse_facility(line, dest), 'level': parse_level(line, dest) }) else: ip_match = re.search(r'\d+\.\d+\.\d+\.\d+', match.group(1), re.M) if ip_match: dest = 'host' obj.append({ 'dest': dest, 'name': match.group(1), 'facility': parse_facility(line, dest), 'level': parse_level(line, dest) }) return obj def map_params_to_obj(module, required_if=None): obj = [] aggregate = module.params.get('aggregate') if aggregate: for item in aggregate: for key in item: if item.get(key) is None: item[key] = module.params[key] module._check_required_if(required_if, item) d = item.copy() if d['dest'] != 'host': d['name'] = None if d['dest'] == 'buffered': if 'size' in d: d['size'] = str(validate_size(d['size'], module)) elif 'size' not in d: d['size'] = str(4096) else: pass if d['dest'] != 'buffered': d['size'] = None obj.append(d) else: if module.params['dest'] != 'host': module.params['name'] = None if module.params['dest'] == 'buffered': if not module.params['size']: module.params['size'] = str(4096) else: module.params['size'] = None if module.params['size'] is None: obj.append({ 'dest': module.params['dest'], 'name': module.params['name'], 'size': module.params['size'], 'facility': module.params['facility'], 'level': module.params['level'], 'state': module.params['state'] }) else: obj.append({ 'dest': module.params['dest'], 'name': module.params['name'], 'size': str(validate_size(module.params['size'], module)), 'facility': module.params['facility'], 'level': module.params['level'], 'state': module.params['state'] }) return obj def main(): """ main entry point for module execution """ element_spec = dict( dest=dict(type='str', choices=['on', 'host', 'console', 'monitor', 'buffered']), name=dict(type='str'), size=dict(type='int'), facility=dict(type='str'), level=dict(type='str', default='debugging'), state=dict(default='present', choices=['present', 'absent']), ) aggregate_spec = deepcopy(element_spec) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(ios_argument_spec) required_if = [('dest', 'host', ['name'])] module = AnsibleModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True) device_info = get_capabilities(module) os_version = device_info['device_info']['network_os_version'] warnings = list() check_args(module, warnings) result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module, required_if=required_if) have = map_config_to_obj(module) commands = map_obj_to_commands((want, have), module, os_version) result['commands'] = commands if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result) if __name__ == '__main__': main()
MaxGuevara/quark-txmsg
refs/heads/master
contrib/pyminer/pyminer.py
385
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import sys from multiprocessing import Process ERR_SLEEP = 15 MAX_NONCE = 1000000L settings = {} pp = pprint.PrettyPrinter(indent=4) class BitcoinRPC: OBJID = 1 def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) self.authhdr = "Basic %s" % (base64.b64encode(authpair)) self.conn = httplib.HTTPConnection(host, port, False, 30) def rpc(self, method, params=None): self.OBJID += 1 obj = { 'version' : '1.1', 'method' : method, 'id' : self.OBJID } if params is None: obj['params'] = [] else: obj['params'] = params self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self.authhdr, 'Content-type' : 'application/json' }) resp = self.conn.getresponse() if resp is None: print "JSON-RPC: no response" return None body = resp.read() resp_obj = json.loads(body) if resp_obj is None: print "JSON-RPC: cannot JSON-decode body" return None if 'error' in resp_obj and resp_obj['error'] != None: return resp_obj['error'] if 'result' not in resp_obj: print "JSON-RPC: no result in object" return None return resp_obj['result'] def getblockcount(self): return self.rpc('getblockcount') def getwork(self, data=None): return self.rpc('getwork', data) def uint32(x): return x & 0xffffffffL def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) def bufreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): word = struct.unpack('@I', in_buf[i:i+4])[0] out_words.append(struct.pack('@I', bytereverse(word))) return ''.join(out_words) def wordreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): out_words.append(in_buf[i:i+4]) out_words.reverse() return ''.join(out_words) class Miner: def __init__(self, id): self.id = id self.max_nonce = MAX_NONCE def work(self, datastr, targetstr): # decode work data hex string to binary static_data = datastr.decode('hex') static_data = bufreverse(static_data) # the first 76b of 80b do not change blk_hdr = static_data[:76] # decode 256-bit target value targetbin = targetstr.decode('hex') targetbin = targetbin[::-1] # byte-swap and dword-swap targetbin_str = targetbin.encode('hex') target = long(targetbin_str, 16) # pre-hash first 76b of block header static_hash = hashlib.sha256() static_hash.update(blk_hdr) for nonce in xrange(self.max_nonce): # encode 32-bit nonce value nonce_bin = struct.pack("<I", nonce) # hash final 4b, the nonce value hash1_o = static_hash.copy() hash1_o.update(nonce_bin) hash1 = hash1_o.digest() # sha256 hash of sha256 hash hash_o = hashlib.sha256() hash_o.update(hash1) hash = hash_o.digest() # quick test for winning solution: high 32 bits zero? if hash[-4:] != '\0\0\0\0': continue # convert binary hash to 256-bit Python long hash = bufreverse(hash) hash = wordreverse(hash) hash_str = hash.encode('hex') l = long(hash_str, 16) # proof-of-work test: hash < target if l < target: print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,) return (nonce + 1, nonce_bin) else: print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,) # return (nonce + 1, nonce_bin) return (nonce + 1, None) def submit_work(self, rpc, original_data, nonce_bin): nonce_bin = bufreverse(nonce_bin) nonce = nonce_bin.encode('hex') solution = original_data[:152] + nonce + original_data[160:256] param_arr = [ solution ] result = rpc.getwork(param_arr) print time.asctime(), "--> Upstream RPC result:", result def iterate(self, rpc): work = rpc.getwork() if work is None: time.sleep(ERR_SLEEP) return if 'data' not in work or 'target' not in work: time.sleep(ERR_SLEEP) return time_start = time.time() (hashes_done, nonce_bin) = self.work(work['data'], work['target']) time_end = time.time() time_diff = time_end - time_start self.max_nonce = long( (hashes_done * settings['scantime']) / time_diff) if self.max_nonce > 0xfffffffaL: self.max_nonce = 0xfffffffaL if settings['hashmeter']: print "HashMeter(%d): %d hashes, %.2f Khash/sec" % ( self.id, hashes_done, (hashes_done / 1000.0) / time_diff) if nonce_bin is not None: self.submit_work(rpc, work['data'], nonce_bin) def loop(self): rpc = BitcoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpass']) if rpc is None: return while True: self.iterate(rpc) def miner_thread(id): miner = Miner(id) miner.loop() if __name__ == '__main__': if len(sys.argv) != 2: print "Usage: pyminer.py CONFIG-FILE" sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() if 'host' not in settings: settings['host'] = '127.0.0.1' if 'port' not in settings: settings['port'] = 8332 if 'threads' not in settings: settings['threads'] = 1 if 'hashmeter' not in settings: settings['hashmeter'] = 0 if 'scantime' not in settings: settings['scantime'] = 30L if 'rpcuser' not in settings or 'rpcpass' not in settings: print "Missing username and/or password in cfg file" sys.exit(1) settings['port'] = int(settings['port']) settings['threads'] = int(settings['threads']) settings['hashmeter'] = int(settings['hashmeter']) settings['scantime'] = long(settings['scantime']) thr_list = [] for thr_id in range(settings['threads']): p = Process(target=miner_thread, args=(thr_id,)) p.start() thr_list.append(p) time.sleep(1) # stagger threads print settings['threads'], "mining threads started" print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port']) try: for thr_proc in thr_list: thr_proc.join() except KeyboardInterrupt: pass print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port'])
CamelBackNotation/CarnotKE
refs/heads/master
jyhton/lib-python/2.7/tabnanny.py
394
#! /usr/bin/env python """The Tab Nanny despises ambiguous indentation. She knows no mercy. tabnanny -- Detection of ambiguous indentation For the time being this module is intended to be called as a script. However it is possible to import it into an IDE and use the function check() described below. Warning: The API provided by this module is likely to change in future releases; such changes may not be backward compatible. """ # Released to the public domain, by Tim Peters, 15 April 1998. # XXX Note: this is now a standard library module. # XXX The API needs to undergo changes however; the current code is too # XXX script-like. This will be addressed later. __version__ = "6" import os import sys import getopt import tokenize if not hasattr(tokenize, 'NL'): raise ValueError("tokenize.NL doesn't exist -- tokenize module too old") __all__ = ["check", "NannyNag", "process_tokens"] verbose = 0 filename_only = 0 def errprint(*args): sep = "" for arg in args: sys.stderr.write(sep + str(arg)) sep = " " sys.stderr.write("\n") def main(): global verbose, filename_only try: opts, args = getopt.getopt(sys.argv[1:], "qv") except getopt.error, msg: errprint(msg) return for o, a in opts: if o == '-q': filename_only = filename_only + 1 if o == '-v': verbose = verbose + 1 if not args: errprint("Usage:", sys.argv[0], "[-v] file_or_directory ...") return for arg in args: check(arg) class NannyNag(Exception): """ Raised by tokeneater() if detecting an ambiguous indent. Captured and handled in check(). """ def __init__(self, lineno, msg, line): self.lineno, self.msg, self.line = lineno, msg, line def get_lineno(self): return self.lineno def get_msg(self): return self.msg def get_line(self): return self.line def check(file): """check(file_or_dir) If file_or_dir is a directory and not a symbolic link, then recursively descend the directory tree named by file_or_dir, checking all .py files along the way. If file_or_dir is an ordinary Python source file, it is checked for whitespace related problems. The diagnostic messages are written to standard output using the print statement. """ if os.path.isdir(file) and not os.path.islink(file): if verbose: print "%r: listing directory" % (file,) names = os.listdir(file) for name in names: fullname = os.path.join(file, name) if (os.path.isdir(fullname) and not os.path.islink(fullname) or os.path.normcase(name[-3:]) == ".py"): check(fullname) return try: f = open(file) except IOError, msg: errprint("%r: I/O Error: %s" % (file, msg)) return if verbose > 1: print "checking %r ..." % file try: process_tokens(tokenize.generate_tokens(f.readline)) except tokenize.TokenError, msg: errprint("%r: Token Error: %s" % (file, msg)) return except IndentationError, msg: errprint("%r: Indentation Error: %s" % (file, msg)) return except NannyNag, nag: badline = nag.get_lineno() line = nag.get_line() if verbose: print "%r: *** Line %d: trouble in tab city! ***" % (file, badline) print "offending line: %r" % (line,) print nag.get_msg() else: if ' ' in file: file = '"' + file + '"' if filename_only: print file else: print file, badline, repr(line) return if verbose: print "%r: Clean bill of health." % (file,) class Whitespace: # the characters used for space and tab S, T = ' \t' # members: # raw # the original string # n # the number of leading whitespace characters in raw # nt # the number of tabs in raw[:n] # norm # the normal form as a pair (count, trailing), where: # count # a tuple such that raw[:n] contains count[i] # instances of S * i + T # trailing # the number of trailing spaces in raw[:n] # It's A Theorem that m.indent_level(t) == # n.indent_level(t) for all t >= 1 iff m.norm == n.norm. # is_simple # true iff raw[:n] is of the form (T*)(S*) def __init__(self, ws): self.raw = ws S, T = Whitespace.S, Whitespace.T count = [] b = n = nt = 0 for ch in self.raw: if ch == S: n = n + 1 b = b + 1 elif ch == T: n = n + 1 nt = nt + 1 if b >= len(count): count = count + [0] * (b - len(count) + 1) count[b] = count[b] + 1 b = 0 else: break self.n = n self.nt = nt self.norm = tuple(count), b self.is_simple = len(count) <= 1 # return length of longest contiguous run of spaces (whether or not # preceding a tab) def longest_run_of_spaces(self): count, trailing = self.norm return max(len(count)-1, trailing) def indent_level(self, tabsize): # count, il = self.norm # for i in range(len(count)): # if count[i]: # il = il + (i/tabsize + 1)*tabsize * count[i] # return il # quicker: # il = trailing + sum (i/ts + 1)*ts*count[i] = # trailing + ts * sum (i/ts + 1)*count[i] = # trailing + ts * sum i/ts*count[i] + count[i] = # trailing + ts * [(sum i/ts*count[i]) + (sum count[i])] = # trailing + ts * [(sum i/ts*count[i]) + num_tabs] # and note that i/ts*count[i] is 0 when i < ts count, trailing = self.norm il = 0 for i in range(tabsize, len(count)): il = il + i/tabsize * count[i] return trailing + tabsize * (il + self.nt) # return true iff self.indent_level(t) == other.indent_level(t) # for all t >= 1 def equal(self, other): return self.norm == other.norm # return a list of tuples (ts, i1, i2) such that # i1 == self.indent_level(ts) != other.indent_level(ts) == i2. # Intended to be used after not self.equal(other) is known, in which # case it will return at least one witnessing tab size. def not_equal_witness(self, other): n = max(self.longest_run_of_spaces(), other.longest_run_of_spaces()) + 1 a = [] for ts in range(1, n+1): if self.indent_level(ts) != other.indent_level(ts): a.append( (ts, self.indent_level(ts), other.indent_level(ts)) ) return a # Return True iff self.indent_level(t) < other.indent_level(t) # for all t >= 1. # The algorithm is due to Vincent Broman. # Easy to prove it's correct. # XXXpost that. # Trivial to prove n is sharp (consider T vs ST). # Unknown whether there's a faster general way. I suspected so at # first, but no longer. # For the special (but common!) case where M and N are both of the # form (T*)(S*), M.less(N) iff M.len() < N.len() and # M.num_tabs() <= N.num_tabs(). Proof is easy but kinda long-winded. # XXXwrite that up. # Note that M is of the form (T*)(S*) iff len(M.norm[0]) <= 1. def less(self, other): if self.n >= other.n: return False if self.is_simple and other.is_simple: return self.nt <= other.nt n = max(self.longest_run_of_spaces(), other.longest_run_of_spaces()) + 1 # the self.n >= other.n test already did it for ts=1 for ts in range(2, n+1): if self.indent_level(ts) >= other.indent_level(ts): return False return True # return a list of tuples (ts, i1, i2) such that # i1 == self.indent_level(ts) >= other.indent_level(ts) == i2. # Intended to be used after not self.less(other) is known, in which # case it will return at least one witnessing tab size. def not_less_witness(self, other): n = max(self.longest_run_of_spaces(), other.longest_run_of_spaces()) + 1 a = [] for ts in range(1, n+1): if self.indent_level(ts) >= other.indent_level(ts): a.append( (ts, self.indent_level(ts), other.indent_level(ts)) ) return a def format_witnesses(w): firsts = map(lambda tup: str(tup[0]), w) prefix = "at tab size" if len(w) > 1: prefix = prefix + "s" return prefix + " " + ', '.join(firsts) def process_tokens(tokens): INDENT = tokenize.INDENT DEDENT = tokenize.DEDENT NEWLINE = tokenize.NEWLINE JUNK = tokenize.COMMENT, tokenize.NL indents = [Whitespace("")] check_equal = 0 for (type, token, start, end, line) in tokens: if type == NEWLINE: # a program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? # If an INDENT appears, setting check_equal is wrong, and will # be undone when we see the INDENT. check_equal = 1 elif type == INDENT: check_equal = 0 thisguy = Whitespace(token) if not indents[-1].less(thisguy): witness = indents[-1].not_less_witness(thisguy) msg = "indent not greater e.g. " + format_witnesses(witness) raise NannyNag(start[0], msg, line) indents.append(thisguy) elif type == DEDENT: # there's nothing we need to check here! what's important is # that when the run of DEDENTs ends, the indentation of the # program statement (or ENDMARKER) that triggered the run is # equal to what's left at the top of the indents stack # Ouch! This assert triggers if the last line of the source # is indented *and* lacks a newline -- then DEDENTs pop out # of thin air. # assert check_equal # else no earlier NEWLINE, or an earlier INDENT check_equal = 1 del indents[-1] elif check_equal and type not in JUNK: # this is the first "real token" following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER; the "line" argument exposes the leading whitespace # for this statement; in the case of ENDMARKER, line is an empty # string, so will properly match the empty string with which the # "indents" stack was seeded check_equal = 0 thisguy = Whitespace(line) if not indents[-1].equal(thisguy): witness = indents[-1].not_equal_witness(thisguy) msg = "indent not equal e.g. " + format_witnesses(witness) raise NannyNag(start[0], msg, line) if __name__ == '__main__': main()
liuzheng712/Misago
refs/heads/master
misago/core/testproject/views.py
8
from django.contrib.auth import get_user_model from django.core.exceptions import PermissionDenied from django.http import Http404, HttpResponse from misago.core import errorpages, mail from misago.core.decorators import require_POST from misago.core.shortcuts import paginate, validate_slug from misago.core.testproject.models import Model from misago.core.views import noscript def test_mail_user(request): User = get_user_model() test_user = User.objects.all().first() mail.mail_user(request, test_user, "Misago Test Mail", "misago/emails/base") return HttpResponse("Mailed user!") def test_mail_users(request): User = get_user_model() mail.mail_users(request, User.objects.iterator(), "Misago Test Spam", "misago/emails/base") return HttpResponse("Mailed users!") def test_pagination(request, page=None): items = range(15) page = paginate(items, page, 5) return HttpResponse(",".join([str(x) for x in page.object_list])) def validate_slug_view(request, model_id, model_slug): model = Model(int(model_id), 'eric-the-fish') validate_slug(model, model_slug) return HttpResponse("Allright!") def raise_misago_403(request): raise PermissionDenied('Misago 403') def raise_misago_404(request): raise Http404('Misago 404') def raise_misago_405(request): return errorpages.not_allowed(request) def raise_403(request): raise PermissionDenied() def raise_404(request): raise Http404() def test_noscript(request): return noscript(request, **request.POST) @require_POST def test_require_post(request): return HttpResponse("Request method: %s" % request.method) @errorpages.shared_403_exception_handler def mock_custom_403_error_page(request): return HttpResponse("Custom 403", status=403) @errorpages.shared_404_exception_handler def mock_custom_404_error_page(request): return HttpResponse("Custom 404", status=404)
collinprice/titanium_mobile
refs/heads/master
support/common/markdown/extensions/wikilinks.py
123
#!/usr/bin/env python ''' WikiLinks Extension for Python-Markdown ====================================== Converts [[WikiLinks]] to relative links. Requires Python-Markdown 2.0+ Basic usage: >>> import markdown >>> text = "Some text with a [[WikiLink]]." >>> html = markdown.markdown(text, ['wikilinks']) >>> html u'<p>Some text with a <a class="wikilink" href="/WikiLink/">WikiLink</a>.</p>' Whitespace behavior: >>> markdown.markdown('[[ foo bar_baz ]]', ['wikilinks']) u'<p><a class="wikilink" href="/foo_bar_baz/">foo bar_baz</a></p>' >>> markdown.markdown('foo [[ ]] bar', ['wikilinks']) u'<p>foo bar</p>' To define custom settings the simple way: >>> markdown.markdown(text, ... ['wikilinks(base_url=/wiki/,end_url=.html,html_class=foo)'] ... ) u'<p>Some text with a <a class="foo" href="/wiki/WikiLink.html">WikiLink</a>.</p>' Custom settings the complex way: >>> md = markdown.Markdown( ... extensions = ['wikilinks'], ... extension_configs = {'wikilinks': [ ... ('base_url', 'http://example.com/'), ... ('end_url', '.html'), ... ('html_class', '') ]}, ... safe_mode = True) >>> md.convert(text) u'<p>Some text with a <a href="http://example.com/WikiLink.html">WikiLink</a>.</p>' Use MetaData with mdx_meta.py (Note the blank html_class in MetaData): >>> text = """wiki_base_url: http://example.com/ ... wiki_end_url: .html ... wiki_html_class: ... ... Some text with a [[WikiLink]].""" >>> md = markdown.Markdown(extensions=['meta', 'wikilinks']) >>> md.convert(text) u'<p>Some text with a <a href="http://example.com/WikiLink.html">WikiLink</a>.</p>' MetaData should not carry over to next document: >>> md.convert("No [[MetaData]] here.") u'<p>No <a class="wikilink" href="/MetaData/">MetaData</a> here.</p>' Define a custom URL builder: >>> def my_url_builder(label, base, end): ... return '/bar/' >>> md = markdown.Markdown(extensions=['wikilinks'], ... extension_configs={'wikilinks' : [('build_url', my_url_builder)]}) >>> md.convert('[[foo]]') u'<p><a class="wikilink" href="/bar/">foo</a></p>' From the command line: python markdown.py -x wikilinks(base_url=http://example.com/,end_url=.html,html_class=foo) src.txt By [Waylan Limberg](http://achinghead.com/). License: [BSD](http://www.opensource.org/licenses/bsd-license.php) Dependencies: * [Python 2.3+](http://python.org) * [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/) ''' import markdown import re def build_url(label, base, end): """ Build a url from the label, a base, and an end. """ clean_label = re.sub(r'([ ]+_)|(_[ ]+)|([ ]+)', '_', label) return '%s%s%s'% (base, clean_label, end) class WikiLinkExtension(markdown.Extension): def __init__(self, configs): # set extension defaults self.config = { 'base_url' : ['/', 'String to append to beginning or URL.'], 'end_url' : ['/', 'String to append to end of URL.'], 'html_class' : ['wikilink', 'CSS hook. Leave blank for none.'], 'build_url' : [build_url, 'Callable formats URL from label.'], } # Override defaults with user settings for key, value in configs : self.setConfig(key, value) def extendMarkdown(self, md, md_globals): self.md = md # append to end of inline patterns WIKILINK_RE = r'\[\[([A-Za-z0-9_ -]+)\]\]' wikilinkPattern = WikiLinks(WIKILINK_RE, self.config) wikilinkPattern.md = md md.inlinePatterns.add('wikilink', wikilinkPattern, "<not_strong") class WikiLinks(markdown.inlinepatterns.Pattern): def __init__(self, pattern, config): markdown.inlinepatterns.Pattern.__init__(self, pattern) self.config = config def handleMatch(self, m): if m.group(2).strip(): base_url, end_url, html_class = self._getMeta() label = m.group(2).strip() url = self.config['build_url'][0](label, base_url, end_url) a = markdown.etree.Element('a') a.text = label a.set('href', url) if html_class: a.set('class', html_class) else: a = '' return a def _getMeta(self): """ Return meta data or config data. """ base_url = self.config['base_url'][0] end_url = self.config['end_url'][0] html_class = self.config['html_class'][0] if hasattr(self.md, 'Meta'): if self.md.Meta.has_key('wiki_base_url'): base_url = self.md.Meta['wiki_base_url'][0] if self.md.Meta.has_key('wiki_end_url'): end_url = self.md.Meta['wiki_end_url'][0] if self.md.Meta.has_key('wiki_html_class'): html_class = self.md.Meta['wiki_html_class'][0] return base_url, end_url, html_class def makeExtension(configs=None) : return WikiLinkExtension(configs=configs) if __name__ == "__main__": import doctest doctest.testmod()
LukeC92/iris
refs/heads/latest
lib/iris/tests/unit/util/test_new_axis.py
5
# (C) British Crown Copyright 2013 - 2017, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Iris is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see <http://www.gnu.org/licenses/>. """Test function :func:`iris.util.new_axis`.""" from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests import iris.tests.stock as stock import copy from iris._lazy_data import as_lazy_data import numpy as np import unittest import iris from iris.util import new_axis class Test(tests.IrisTest): def setUp(self): self.data = np.array([[1, 2], [1, 2]]) self.cube = iris.cube.Cube(self.data) lat = iris.coords.DimCoord([1, 2], standard_name='latitude') lon = iris.coords.DimCoord([1, 2], standard_name='longitude') time = iris.coords.DimCoord([1], standard_name='time') wibble = iris.coords.AuxCoord([1], long_name='wibble') self.cube.add_dim_coord(lat, 0) self.cube.add_dim_coord(lon, 1) self.cube.add_aux_coord(time, None) self.cube.add_aux_coord(wibble, None) self.coords = {'lat': lat, 'lon': lon, 'time': time, 'wibble': wibble} def _assert_cube_notis(self, cube_a, cube_b): for coord_a, coord_b in zip(cube_a.coords(), cube_b.coords()): self.assertIsNot(coord_a, coord_b) self.assertIsNot(cube_a.metadata, cube_b.metadata) for factory_a, factory_b in zip( cube_a.aux_factories, cube_b.aux_factories): self.assertIsNot(factory_a, factory_b) def test_no_coord(self): # Providing no coordinate to promote. res = new_axis(self.cube) com = iris.cube.Cube(self.data[None]) com.add_dim_coord(self.coords['lat'].copy(), 1) com.add_dim_coord(self.coords['lon'].copy(), 2) com.add_aux_coord(self.coords['time'].copy(), None) com.add_aux_coord(self.coords['wibble'].copy(), None) self.assertEqual(res, com) self._assert_cube_notis(res, self.cube) def test_scalar_dimcoord(self): # Providing a scalar coordinate to promote. res = new_axis(self.cube, 'time') com = iris.cube.Cube(self.data[None]) com.add_dim_coord(self.coords['lat'].copy(), 1) com.add_dim_coord(self.coords['lon'].copy(), 2) com.add_aux_coord(self.coords['time'].copy(), 0) com.add_aux_coord(self.coords['wibble'].copy(), None) self.assertEqual(res, com) self._assert_cube_notis(res, self.cube) def test_scalar_auxcoord(self): # Providing a scalar coordinate to promote. res = new_axis(self.cube, 'wibble') com = iris.cube.Cube(self.data[None]) com.add_dim_coord(self.coords['lat'].copy(), 1) com.add_dim_coord(self.coords['lon'].copy(), 2) com.add_aux_coord(self.coords['time'].copy(), None) com.add_aux_coord(self.coords['wibble'].copy(), 0) self.assertEqual(res, com) self._assert_cube_notis(res, self.cube) def test_maint_factory(self): # Ensure that aux factory persists. data = np.arange(12, dtype='i8').reshape((3, 4)) orography = iris.coords.AuxCoord( [10, 25, 50, 5], standard_name='surface_altitude', units='m') model_level = iris.coords.AuxCoord( [2, 1, 0], standard_name='model_level_number') level_height = iris.coords.DimCoord( [100, 50, 10], long_name='level_height', units='m', attributes={'positive': 'up'}, bounds=[[150, 75], [75, 20], [20, 0]]) sigma = iris.coords.AuxCoord( [0.8, 0.9, 0.95], long_name='sigma', bounds=[[0.7, 0.85], [0.85, 0.97], [0.97, 1.0]]) hybrid_height = iris.aux_factory.HybridHeightFactory( level_height, sigma, orography) cube = iris.cube.Cube( data, standard_name='air_temperature', units='K', dim_coords_and_dims=[(level_height, 0)], aux_coords_and_dims=[(orography, 1), (model_level, 0), (sigma, 0)], aux_factories=[hybrid_height]) com = iris.cube.Cube( data[None], standard_name='air_temperature', units='K', dim_coords_and_dims=[(copy.copy(level_height), 1)], aux_coords_and_dims=[(copy.copy(orography), 2), (copy.copy(model_level), 1), (copy.copy(sigma), 1)], aux_factories=[copy.copy(hybrid_height)]) res = new_axis(cube) self.assertEqual(res, com) self._assert_cube_notis(res, cube) def test_lazy_data(self): cube = iris.cube.Cube(as_lazy_data(self.data)) cube.add_aux_coord(iris.coords.DimCoord([1], standard_name='time')) res = new_axis(cube, 'time') self.assertTrue(cube.has_lazy_data()) self.assertTrue(res.has_lazy_data()) self.assertEqual(res.shape, (1,) + cube.shape) def test_masked_unit_array(self): cube = stock.simple_3d_mask() test_cube = cube[0, 0, 0] test_cube = new_axis(test_cube, 'longitude') test_cube = new_axis(test_cube, 'latitude') data_shape = test_cube.data.shape mask_shape = test_cube.data.mask.shape self.assertEqual(data_shape, mask_shape) if __name__ == '__main__': unittest.main()
varunarya10/heat
refs/heads/master
heat/tests/test_engine_api_utils.py
5
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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 heat.engine.api as api from heat.engine import parser from heat.engine import resource from heat.openstack.common import uuidutils from heat.rpc import api as rpc_api from heat.tests.common import HeatTestCase from heat.tests import generic_resource as generic_rsrc from heat.tests import utils class EngineApiTest(HeatTestCase): def test_timeout_extract(self): p = {'timeout_mins': '5'} args = api.extract_args(p) self.assertEqual(args['timeout_mins'], 5) def test_timeout_extract_zero(self): p = {'timeout_mins': '0'} args = api.extract_args(p) self.assertTrue('timeout_mins' not in args) def test_timeout_extract_garbage(self): p = {'timeout_mins': 'wibble'} args = api.extract_args(p) self.assertTrue('timeout_mins' not in args) def test_timeout_extract_none(self): p = {'timeout_mins': None} args = api.extract_args(p) self.assertTrue('timeout_mins' not in args) def test_timeout_extract_not_present(self): args = api.extract_args({}) self.assertTrue('timeout_mins' not in args) def test_disable_rollback_extract_true(self): args = api.extract_args({'disable_rollback': True}) self.assertTrue('disable_rollback' in args) self.assertTrue(args.get('disable_rollback')) args = api.extract_args({'disable_rollback': 'True'}) self.assertTrue('disable_rollback' in args) self.assertTrue(args.get('disable_rollback')) args = api.extract_args({'disable_rollback': 'true'}) self.assertTrue('disable_rollback' in args) self.assertTrue(args.get('disable_rollback')) def test_disable_rollback_extract_false(self): args = api.extract_args({'disable_rollback': False}) self.assertTrue('disable_rollback' in args) self.assertFalse(args.get('disable_rollback')) args = api.extract_args({'disable_rollback': 'False'}) self.assertTrue('disable_rollback' in args) self.assertFalse(args.get('disable_rollback')) args = api.extract_args({'disable_rollback': 'false'}) self.assertTrue('disable_rollback' in args) self.assertFalse(args.get('disable_rollback')) def test_disable_rollback_extract_bad(self): self.assertRaises(ValueError, api.extract_args, {'disable_rollback': 'bad'}) class FormatTest(HeatTestCase): def setUp(self): super(FormatTest, self).setUp() utils.setup_dummy_db() template = parser.Template({ 'Resources': { 'generic1': {'Type': 'GenericResourceType'}, 'generic2': { 'Type': 'GenericResourceType', 'DependsOn': 'generic1'} } }) resource._register_class('GenericResourceType', generic_rsrc.GenericResource) self.stack = parser.Stack(utils.dummy_context(), 'test_stack', template, stack_id=uuidutils.generate_uuid()) def test_format_stack_resource(self): res = self.stack['generic1'] resource_keys = set(( rpc_api.RES_UPDATED_TIME, rpc_api.RES_NAME, rpc_api.RES_PHYSICAL_ID, rpc_api.RES_METADATA, rpc_api.RES_ACTION, rpc_api.RES_STATUS, rpc_api.RES_STATUS_DATA, rpc_api.RES_TYPE, rpc_api.RES_ID, rpc_api.RES_STACK_ID, rpc_api.RES_STACK_NAME, rpc_api.RES_REQUIRED_BY)) resource_details_keys = resource_keys.union(set( (rpc_api.RES_DESCRIPTION, rpc_api.RES_METADATA))) formatted = api.format_stack_resource(res, True) self.assertEqual(resource_details_keys, set(formatted.keys())) formatted = api.format_stack_resource(res, False) self.assertEqual(resource_keys, set(formatted.keys())) def test_format_stack_resource_required_by(self): res1 = api.format_stack_resource(self.stack['generic1']) res2 = api.format_stack_resource(self.stack['generic2']) self.assertEqual(res1['required_by'], ['generic2']) self.assertEqual(res2['required_by'], [])
cleverhans-lab/cleverhans
refs/heads/master
cleverhans_v3.1.0/examples/multigpu_advtrain/utils_svhn.py
1
""" Reading the SVHN dataset. It is derived from CIFAR10 scripts in RevNets code. https://github.com/renmengye/revnet-public/blob/master/resnet/data/cifar_input.py MIT License Copyright (c) 2017 Mengye Ren Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # pylint: disable=missing-docstring from __future__ import absolute_import, division, print_function, unicode_literals import os import numpy as np from six.moves import range import tensorflow as tf import scipy.io as sio # Global constants describing the SVHN data set. IMAGE_HEIGHT = 32 IMAGE_WIDTH = 32 NUM_CLASSES = 10 NUM_CHANNEL = 3 NUM_TRAIN_IMG = 73257 + 531131 NUM_TEST_IMG = 26032 def read_SVHN(data_folder): """ Reads and parses examples from SVHN data files """ train_img = [] train_label = [] test_img = [] test_label = [] train_file_list = ["train_32x32.mat", "extra_32x32.mat"] test_file_list = ["test_32x32.mat"] for i in range(len(train_file_list)): tmp_dict = sio.loadmat(os.path.join(data_folder, train_file_list[i])) train_img.append(tmp_dict["X"]) train_label.append(tmp_dict["y"]) tmp_dict = sio.loadmat(os.path.join(data_folder, test_file_list[0])) test_img.append(tmp_dict["X"]) test_label.append(tmp_dict["y"]) train_img = np.concatenate(train_img, axis=-1) train_label = np.concatenate(train_label).flatten() test_img = np.concatenate(test_img, axis=-1) test_label = np.concatenate(test_label).flatten() # change format from [H, W, C, B] to [B, H, W, C] for feeding to Tensorflow train_img = np.transpose(train_img, [3, 0, 1, 2]) test_img = np.transpose(test_img, [3, 0, 1, 2]) mean_img = np.mean(np.concatenate([train_img, test_img]), axis=0) train_img = train_img - mean_img test_img = test_img - mean_img train_y = train_label - 1 # 0-based label test_y = test_label - 1 # 0-based label train_label = np.eye(10)[train_y] test_label = np.eye(10)[test_y] return train_img, train_label, test_img, test_label def svhn_tf_preprocess(inp, random_crop=True): image_size = 32 image = inp if random_crop: print("Apply random cropping") image = tf.image.resize_image_with_crop_or_pad( inp, image_size + 4, image_size + 4 ) image = tf.random_crop(image, [image_size, image_size, 3]) return inp, image
amorilia/blender_nif_plugin
refs/heads/develop
io_scene_nif/armaturesys/__init__.py
12133432
2013Commons/HUE-SHARK
refs/heads/master
build/env/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/conf/locale/es/__init__.py
12133432
jamielennox/keystone
refs/heads/master
keystone/endpoint_policy/backends/__init__.py
12133432
msporny/node-gyp
refs/heads/master
gyp/pylib/gyp/common.py
497
# 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. from __future__ import with_statement import errno import filecmp import os.path import re import tempfile import sys # A minimal memoizing decorator. It'll blow up if the args aren't immutable, # among other "problems". class memoize(object): def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: result = self.func(*args) self.cache[args] = result return result class GypError(Exception): """Error class representing an error, which is to be presented to the user. The main entry point will catch and display this. """ pass def ExceptionAppend(e, msg): """Append a message to the given exception's message.""" if not e.args: e.args = (msg,) elif len(e.args) == 1: e.args = (str(e.args[0]) + ' ' + msg,) else: e.args = (str(e.args[0]) + ' ' + msg,) + e.args[1:] def FindQualifiedTargets(target, qualified_list): """ Given a list of qualified targets, return the qualified targets for the specified |target|. """ return [t for t in qualified_list if ParseQualifiedTarget(t)[1] == target] def ParseQualifiedTarget(target): # Splits a qualified target into a build file, target name and toolset. # NOTE: rsplit is used to disambiguate the Windows drive letter separator. target_split = target.rsplit(':', 1) if len(target_split) == 2: [build_file, target] = target_split else: build_file = None target_split = target.rsplit('#', 1) if len(target_split) == 2: [target, toolset] = target_split else: toolset = None return [build_file, target, toolset] def ResolveTarget(build_file, target, toolset): # This function resolves a target into a canonical form: # - a fully defined build file, either absolute or relative to the current # directory # - a target name # - a toolset # # build_file is the file relative to which 'target' is defined. # target is the qualified target. # toolset is the default toolset for that target. [parsed_build_file, target, parsed_toolset] = ParseQualifiedTarget(target) if parsed_build_file: if build_file: # If a relative path, parsed_build_file is relative to the directory # containing build_file. If build_file is not in the current directory, # parsed_build_file is not a usable path as-is. Resolve it by # interpreting it as relative to build_file. If parsed_build_file is # absolute, it is usable as a path regardless of the current directory, # and os.path.join will return it as-is. build_file = os.path.normpath(os.path.join(os.path.dirname(build_file), parsed_build_file)) # Further (to handle cases like ../cwd), make it relative to cwd) if not os.path.isabs(build_file): build_file = RelativePath(build_file, '.') else: build_file = parsed_build_file if parsed_toolset: toolset = parsed_toolset return [build_file, target, toolset] def BuildFile(fully_qualified_target): # Extracts the build file from the fully qualified target. return ParseQualifiedTarget(fully_qualified_target)[0] def GetEnvironFallback(var_list, default): """Look up a key in the environment, with fallback to secondary keys and finally falling back to a default value.""" for var in var_list: if var in os.environ: return os.environ[var] return default def QualifiedTarget(build_file, target, toolset): # "Qualified" means the file that a target was defined in and the target # name, separated by a colon, suffixed by a # and the toolset name: # /path/to/file.gyp:target_name#toolset fully_qualified = build_file + ':' + target if toolset: fully_qualified = fully_qualified + '#' + toolset return fully_qualified @memoize def RelativePath(path, relative_to): # Assuming both |path| and |relative_to| are relative to the current # directory, returns a relative path that identifies path relative to # relative_to. # Convert to normalized (and therefore absolute paths). path = os.path.realpath(path) relative_to = os.path.realpath(relative_to) # On Windows, we can't create a relative path to a different drive, so just # use the absolute path. if sys.platform == 'win32': if (os.path.splitdrive(path)[0].lower() != os.path.splitdrive(relative_to)[0].lower()): return path # Split the paths into components. path_split = path.split(os.path.sep) relative_to_split = relative_to.split(os.path.sep) # Determine how much of the prefix the two paths share. prefix_len = len(os.path.commonprefix([path_split, relative_to_split])) # Put enough ".." components to back up out of relative_to to the common # prefix, and then append the part of path_split after the common prefix. relative_split = [os.path.pardir] * (len(relative_to_split) - prefix_len) + \ path_split[prefix_len:] if len(relative_split) == 0: # The paths were the same. return '' # Turn it back into a string and we're done. return os.path.join(*relative_split) @memoize def InvertRelativePath(path, toplevel_dir=None): """Given a path like foo/bar that is relative to toplevel_dir, return the inverse relative path back to the toplevel_dir. E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path))) should always produce the empty string, unless the path contains symlinks. """ if not path: return path toplevel_dir = '.' if toplevel_dir is None else toplevel_dir return RelativePath(toplevel_dir, os.path.join(toplevel_dir, path)) def FixIfRelativePath(path, relative_to): # Like RelativePath but returns |path| unchanged if it is absolute. if os.path.isabs(path): return path return RelativePath(path, relative_to) def UnrelativePath(path, relative_to): # Assuming that |relative_to| is relative to the current directory, and |path| # is a path relative to the dirname of |relative_to|, returns a path that # identifies |path| relative to the current directory. rel_dir = os.path.dirname(relative_to) return os.path.normpath(os.path.join(rel_dir, path)) # re objects used by EncodePOSIXShellArgument. See IEEE 1003.1 XCU.2.2 at # http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_02 # and the documentation for various shells. # _quote is a pattern that should match any argument that needs to be quoted # with double-quotes by EncodePOSIXShellArgument. It matches the following # characters appearing anywhere in an argument: # \t, \n, space parameter separators # # comments # $ expansions (quoted to always expand within one argument) # % called out by IEEE 1003.1 XCU.2.2 # & job control # ' quoting # (, ) subshell execution # *, ?, [ pathname expansion # ; command delimiter # <, >, | redirection # = assignment # {, } brace expansion (bash) # ~ tilde expansion # It also matches the empty string, because "" (or '') is the only way to # represent an empty string literal argument to a POSIX shell. # # This does not match the characters in _escape, because those need to be # backslash-escaped regardless of whether they appear in a double-quoted # string. _quote = re.compile('[\t\n #$%&\'()*;<=>?[{|}~]|^$') # _escape is a pattern that should match any character that needs to be # escaped with a backslash, whether or not the argument matched the _quote # pattern. _escape is used with re.sub to backslash anything in _escape's # first match group, hence the (parentheses) in the regular expression. # # _escape matches the following characters appearing anywhere in an argument: # " to prevent POSIX shells from interpreting this character for quoting # \ to prevent POSIX shells from interpreting this character for escaping # ` to prevent POSIX shells from interpreting this character for command # substitution # Missing from this list is $, because the desired behavior of # EncodePOSIXShellArgument is to permit parameter (variable) expansion. # # Also missing from this list is !, which bash will interpret as the history # expansion character when history is enabled. bash does not enable history # by default in non-interactive shells, so this is not thought to be a problem. # ! was omitted from this list because bash interprets "\!" as a literal string # including the backslash character (avoiding history expansion but retaining # the backslash), which would not be correct for argument encoding. Handling # this case properly would also be problematic because bash allows the history # character to be changed with the histchars shell variable. Fortunately, # as history is not enabled in non-interactive shells and # EncodePOSIXShellArgument is only expected to encode for non-interactive # shells, there is no room for error here by ignoring !. _escape = re.compile(r'(["\\`])') def EncodePOSIXShellArgument(argument): """Encodes |argument| suitably for consumption by POSIX shells. argument may be quoted and escaped as necessary to ensure that POSIX shells treat the returned value as a literal representing the argument passed to this function. Parameter (variable) expansions beginning with $ are allowed to remain intact without escaping the $, to allow the argument to contain references to variables to be expanded by the shell. """ if not isinstance(argument, str): argument = str(argument) if _quote.search(argument): quote = '"' else: quote = '' encoded = quote + re.sub(_escape, r'\\\1', argument) + quote return encoded def EncodePOSIXShellList(list): """Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator. """ encoded_arguments = [] for argument in list: encoded_arguments.append(EncodePOSIXShellArgument(argument)) return ' '.join(encoded_arguments) def DeepDependencyTargets(target_dicts, roots): """Returns the recursive list of target dependencies.""" dependencies = set() pending = set(roots) while pending: # Pluck out one. r = pending.pop() # Skip if visited already. if r in dependencies: continue # Add it. dependencies.add(r) # Add its children. spec = target_dicts[r] pending.update(set(spec.get('dependencies', []))) pending.update(set(spec.get('dependencies_original', []))) return list(dependencies - set(roots)) def BuildFileTargets(target_list, build_file): """From a target_list, returns the subset from the specified build_file. """ return [p for p in target_list if BuildFile(p) == build_file] def AllTargets(target_list, target_dicts, build_file): """Returns all targets (direct and dependencies) for the specified build_file. """ bftargets = BuildFileTargets(target_list, build_file) deptargets = DeepDependencyTargets(target_dicts, bftargets) return bftargets + deptargets def WriteOnDiff(filename): """Write to a file only if the new contents differ. Arguments: filename: name of the file to potentially write to. Returns: A file like object which will write to temporary file and only overwrite the target if it differs (on close). """ class Writer: """Wrapper around file which only covers the target if it differs.""" def __init__(self): # Pick temporary file. tmp_fd, self.tmp_path = tempfile.mkstemp( suffix='.tmp', prefix=os.path.split(filename)[1] + '.gyp.', dir=os.path.split(filename)[0]) try: self.tmp_file = os.fdopen(tmp_fd, 'wb') except Exception: # Don't leave turds behind. os.unlink(self.tmp_path) raise def __getattr__(self, attrname): # Delegate everything else to self.tmp_file return getattr(self.tmp_file, attrname) def close(self): try: # Close tmp file. self.tmp_file.close() # Determine if different. same = False try: same = filecmp.cmp(self.tmp_path, filename, False) except OSError, e: if e.errno != errno.ENOENT: raise if same: # The new file is identical to the old one, just get rid of the new # one. os.unlink(self.tmp_path) else: # The new file is different from the old one, or there is no old one. # Rename the new file to the permanent name. # # tempfile.mkstemp uses an overly restrictive mode, resulting in a # file that can only be read by the owner, regardless of the umask. # There's no reason to not respect the umask here, which means that # an extra hoop is required to fetch it and reset the new file's mode. # # No way to get the umask without setting a new one? Set a safe one # and then set it back to the old value. umask = os.umask(077) os.umask(umask) os.chmod(self.tmp_path, 0666 & ~umask) if sys.platform == 'win32' and os.path.exists(filename): # NOTE: on windows (but not cygwin) rename will not replace an # existing file, so it must be preceded with a remove. Sadly there # is no way to make the switch atomic. os.remove(filename) os.rename(self.tmp_path, filename) except Exception: # Don't leave turds behind. os.unlink(self.tmp_path) raise return Writer() def EnsureDirExists(path): """Make sure the directory for |path| exists.""" try: os.makedirs(os.path.dirname(path)) except OSError: pass def GetFlavor(params): """Returns |params.flavor| if it's set, the system's default flavor else.""" flavors = { 'cygwin': 'win', 'win32': 'win', 'darwin': 'mac', } if 'flavor' in params: return params['flavor'] if sys.platform in flavors: return flavors[sys.platform] if sys.platform.startswith('sunos'): return 'solaris' if sys.platform.startswith('freebsd'): return 'freebsd' if sys.platform.startswith('openbsd'): return 'openbsd' if sys.platform.startswith('aix'): return 'aix' return 'linux' def CopyTool(flavor, out_path): """Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it to |out_path|.""" # aix and solaris just need flock emulation. mac and win use more complicated # support scripts. prefix = { 'aix': 'flock', 'solaris': 'flock', 'mac': 'mac', 'win': 'win' }.get(flavor, None) if not prefix: return # Slurp input file. source_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), '%s_tool.py' % prefix) with open(source_path) as source_file: source = source_file.readlines() # Add header and write it out. tool_path = os.path.join(out_path, 'gyp-%s-tool' % prefix) with open(tool_path, 'w') as tool_file: tool_file.write( ''.join([source[0], '# Generated by gyp. Do not edit.\n'] + source[1:])) # Make file executable. os.chmod(tool_path, 0755) # From Alex Martelli, # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 # ASPN: Python Cookbook: Remove duplicates from a sequence # First comment, dated 2001/10/13. # (Also in the printed Python Cookbook.) def uniquer(seq, idfun=None): if idfun is None: idfun = lambda x: x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result class CycleError(Exception): """An exception raised when an unexpected cycle is detected.""" def __init__(self, nodes): self.nodes = nodes def __str__(self): return 'CycleError: cycle involving: ' + str(self.nodes) def TopologicallySorted(graph, get_edges): """Topologically sort based on a user provided edge definition. Args: graph: A list of node names. get_edges: A function mapping from node name to a hashable collection of node names which this node has outgoing edges to. Returns: A list containing all of the node in graph in topological order. It is assumed that calling get_edges once for each node and caching is cheaper than repeatedly calling get_edges. Raises: CycleError in the event of a cycle. Example: graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'} def GetEdges(node): return re.findall(r'\$\(([^))]\)', graph[node]) print TopologicallySorted(graph.keys(), GetEdges) ==> ['a', 'c', b'] """ get_edges = memoize(get_edges) visited = set() visiting = set() ordered_nodes = [] def Visit(node): if node in visiting: raise CycleError(visiting) if node in visited: return visited.add(node) visiting.add(node) for neighbor in get_edges(node): Visit(neighbor) visiting.remove(node) ordered_nodes.insert(0, node) for node in sorted(graph): Visit(node) return ordered_nodes
gregdek/ansible
refs/heads/devel
lib/ansible/module_utils/facts/network/darwin.py
128
# This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.facts.network.base import NetworkCollector from ansible.module_utils.facts.network.generic_bsd import GenericBsdIfconfigNetwork class DarwinNetwork(GenericBsdIfconfigNetwork): """ This is the Mac macOS Darwin Network Class. It uses the GenericBsdIfconfigNetwork unchanged """ platform = 'Darwin' # media line is different to the default FreeBSD one def parse_media_line(self, words, current_if, ips): # not sure if this is useful - we also drop information current_if['media'] = 'Unknown' # Mac does not give us this current_if['media_select'] = words[1] if len(words) > 2: # MacOSX sets the media to '<unknown type>' for bridge interface # and parsing splits this into two words; this if/else helps if words[1] == '<unknown' and words[2] == 'type>': current_if['media_select'] = 'Unknown' current_if['media_type'] = 'unknown type' else: current_if['media_type'] = words[2][1:-1] if len(words) > 3: current_if['media_options'] = self.get_options(words[3]) class DarwinNetworkCollector(NetworkCollector): _fact_class = DarwinNetwork _platform = 'Darwin'
marcoitur/Freecad_test
refs/heads/master
src/Mod/Arch/ArchBuilding.py
18
#*************************************************************************** #* * #* Copyright (c) 2011 * #* Yorik van Havre <yorik@uncreated.net> * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* * #* 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 Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library 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 * #* * #*************************************************************************** import FreeCAD,Draft,ArchCommands,ArchFloor if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui from DraftTools import translate else: def translate(ctxt,txt): return txt __title__="FreeCAD Building" __author__ = "Yorik van Havre" __url__ = "http://www.freecadweb.org" BuildingTypes = ['Undefined', 'Agricultural - Barn', 'Agricultural - Chicken coop or chickenhouse', 'Agricultural - Cow-shed', 'Agricultural - Farmhouse', 'Agricultural - Granary', 'Agricultural - Greenhouse', 'Agricultural - Hayloft', 'Agricultural - Pigpen or sty', 'Agricultural - Root cellar', 'Agricultural - Shed', 'Agricultural - Silo', 'Agricultural - Stable', 'Agricultural - Storm cellar', 'Agricultural - Well house', 'Agricultural - Underground pit', 'Commercial - Automobile repair shop', 'Commercial - Bank', 'Commercial - Car wash', 'Commercial - Convention center', 'Commercial - Forum', 'Commercial - Gas station', 'Commercial - Hotel', 'Commercial - Market', 'Commercial - Market house', 'Commercial - Skyscraper', 'Commercial - Shop', 'Commercial - Shopping mall', 'Commercial - Supermarket', 'Commercial - Warehouse', 'Commercial - Restaurant', 'Residential - Apartment block', 'Residential - Asylum', 'Residential - Condominium', 'Residential - Dormitory', 'Residential - Duplex', 'Residential - House', 'Residential - Nursing home', 'Residential - Townhouse', 'Residential - Villa', 'Residential - Bungalow', 'Educational - Archive', 'Educational - College classroom building', 'Educational - College gymnasium', 'Educational - College students union', 'Educational - School', 'Educational - Library', 'Educational - Museum', 'Educational - Art gallery', 'Educational - Theater', 'Educational - Amphitheater', 'Educational - Concert hall', 'Educational - Cinema', 'Educational - Opera house', 'Educational - Boarding school', 'Government - Capitol', 'Government - City hall', 'Government - Consulate', 'Government - Courthouse', 'Government - Embassy', 'Government - Fire station', 'Government - Meeting house', 'Government - Moot hall', 'Government - Palace', 'Government - Parliament', 'Government - Police station', 'Government - Post office', 'Government - Prison', 'Industrial - Brewery', 'Industrial - Factory', 'Industrial - Foundry', 'Industrial - Power plant', 'Industrial - Mill', 'Military - Arsenal', 'Military -Barracks', 'Parking - Boathouse', 'Parking - Garage', 'Parking - Hangar', 'Storage - Silo', 'Storage - Hangar', 'Religious - Church', 'Religious - Basilica', 'Religious - Cathedral', 'Religious - Chapel', 'Religious - Oratory', 'Religious - Martyrium', 'Religious - Mosque', 'Religious - Mihrab', 'Religious - Surau', 'Religious - Imambargah', 'Religious - Monastery', 'Religious - Mithraeum', 'Religious - Fire temple', 'Religious - Shrine', 'Religious - Synagogue', 'Religious - Temple', 'Religious - Pagoda', 'Religious - Gurdwara', 'Religious - Hindu temple', 'Transport - Airport terminal', 'Transport - Bus station', 'Transport - Metro station', 'Transport - Taxi station', 'Transport - Railway station', 'Transport - Signal box', 'Transport - Lighthouse', 'Infrastructure - Data centre', 'Power station - Fossil-fuel power station', 'Power station - Nuclear power plant', 'Power station - Geothermal power', 'Power station - Biomass-fuelled power plant', 'Power station - Waste heat power plant', 'Power station - Renewable energy power station', 'Power station - Atomic energy plant', 'Other - Apartment', 'Other - Clinic', 'Other - Community hall', 'Other - Eatery', 'Other - Folly', 'Other - Food court', 'Other - Hospice', 'Other - Hospital', 'Other - Hut', 'Other - Bathhouse', 'Other - Workshop', 'Other - World trade centre' ] def makeBuilding(objectslist=None,baseobj=None,name="Building"): '''makeBuilding(objectslist): creates a building including the objects from the given list.''' obj = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroupPython",name) _Building(obj) if FreeCAD.GuiUp: _ViewProviderBuilding(obj.ViewObject) if objectslist: obj.Group = objectslist obj.Label = translate("Arch",name) return obj class _CommandBuilding: "the Arch Building command definition" def GetResources(self): return {'Pixmap' : 'Arch_Building', 'MenuText': QtCore.QT_TRANSLATE_NOOP("Arch_Building","Building"), 'Accel': "B, U", 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Arch_Building","Creates a building object including selected objects.")} def IsActive(self): return not FreeCAD.ActiveDocument is None def Activated(self): sel = FreeCADGui.Selection.getSelection() ok = False if (len(sel) == 1): if Draft.getType(sel[0]) in ["Cell","Site","Floor"]: FreeCAD.ActiveDocument.openTransaction(translate("Arch","Type conversion")) FreeCADGui.addModule("Arch") FreeCADGui.doCommand("obj = Arch.makeBuilding()") FreeCADGui.doCommand("Arch.copyProperties(FreeCAD.ActiveDocument."+sel[0].Name+",obj)") FreeCADGui.doCommand('FreeCAD.ActiveDocument.removeObject("'+sel[0].Name+'")') FreeCAD.ActiveDocument.commitTransaction() ok = True if not ok: FreeCAD.ActiveDocument.openTransaction(translate("Arch"," Create Building")) ss = "[" for o in sel: if len(ss) > 1: ss += "," ss += "FreeCAD.ActiveDocument."+o.Name ss += "]" FreeCAD.ActiveDocument.openTransaction(translate("Arch","Floor")) FreeCADGui.addModule("Arch") FreeCADGui.doCommand("Arch.makeBuilding("+ss+")") FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() class _Building(ArchFloor._Floor): "The Building object" def __init__(self,obj): ArchFloor._Floor.__init__(self,obj) obj.addProperty("App::PropertyEnumeration","BuildingType","Arch",translate("Arch","The type of this building")) self.Type = "Building" obj.setEditorMode('Height',2) obj.BuildingType = BuildingTypes class _ViewProviderBuilding(ArchFloor._ViewProviderFloor): "A View Provider for the Building object" def __init__(self,vobj): ArchFloor._ViewProviderFloor.__init__(self,vobj) def getIcon(self): import Arch_rc return ":/icons/Arch_Building_Tree.svg" if FreeCAD.GuiUp: FreeCADGui.addCommand('Arch_Building',_CommandBuilding())
kriberg/stationspinner
refs/heads/master
stationspinner/corporation/migrations/0024_auto_20151230_1951.py
1
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('corporation', '0023_auto_20151230_1948'), ] operations = [ migrations.AlterField( model_name='industryjob', name='stationID', field=models.BigIntegerField(null=True), ), migrations.AlterField( model_name='industryjobhistory', name='stationID', field=models.BigIntegerField(null=True), ), ]
artursmet/django-payments
refs/heads/master
payments/dotpay/test_dotpay.py
1
from __future__ import unicode_literals import hashlib from unittest import TestCase from django.http import HttpResponse, HttpResponseForbidden from mock import MagicMock, Mock from .forms import ACCEPTED, REJECTED from . import DotpayProvider VARIANT = 'dotpay' PIN = '123' PROCESS_POST = { 'status': 'OK', 'id': '111', 'control': '1', 't_id': 't111', 'amount': '100.0', 'email': 'chf@o2.pl', 't_status': str(ACCEPTED), 'description': 'description', 'md5': '?'} def get_post_with_md5(post): post = post.copy() key_vars = ( PIN, post['id'], post['control'], post['t_id'], post['amount'], post.get('email', ''), '', # service '', # code '', # username '', # password post['t_status']) key = ':'.join(key_vars) md5 = hashlib.md5() md5.update(key.encode('utf-8')) key_hash = md5.hexdigest() post['md5'] = key_hash return post class Payment(Mock): id = 1 variant = VARIANT currency = 'USD' total = 100 status = 'waiting' def get_process_url(self): return 'http://example.com' def get_failure_url(self): return 'http://cancel.com' def get_success_url(self): return 'http://success.com' def change_status(self, status): self.status = status class TestDotpayProvider(TestCase): def setUp(self): self.payment = Payment() def test_get_hidden_fields(self): """DotpayProvider.get_hidden_fields() returns a dictionary""" provider = DotpayProvider(seller_id='123', pin=PIN) self.assertEqual(type(provider.get_hidden_fields(self.payment)), dict) def test_process_data_payment_accepted(self): """DotpayProvider.process_data() returns a correct HTTP response""" request = MagicMock() request.POST = get_post_with_md5(PROCESS_POST) params = { 'seller_id': 123, 'pin': PIN, 'endpoint': 'test.endpoint.com', 'channel': 1, 'lang': 'en', 'lock': True} provider = DotpayProvider(**params) response = provider.process_data(self.payment, request) self.assertEqual(type(response), HttpResponse) self.assertEqual(self.payment.status, 'confirmed') def test_process_data_payment_rejected(self): """DotpayProvider.process_data() returns a correct HTTP response""" data = dict(PROCESS_POST) data.update({'t_status': str(REJECTED)}) request = MagicMock() request.POST = get_post_with_md5(data) params = { 'seller_id': 123, 'pin': PIN, 'endpoint': 'test.endpoint.com', 'channel': 1, 'lang': 'en', 'lock': True} provider = DotpayProvider(**params) response = provider.process_data(self.payment, request) self.assertEqual(type(response), HttpResponse) self.assertEqual(self.payment.status, 'rejected') def test_incorrect_process_data(self): """DotpayProvider.process_data() checks POST signature""" request = MagicMock() request.POST = PROCESS_POST provider = DotpayProvider(seller_id='123', pin=PIN) response = provider.process_data(self.payment, request) self.assertEqual(type(response), HttpResponseForbidden)
titasakgm/brc-stock
refs/heads/master
openerp/addons/hr_timesheet_invoice/report/__init__.py
433
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import account_analytic_profit import report_analytic import hr_timesheet_invoice_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
hellotomfan/v8-coroutine
refs/heads/master
deps/v8/tools/testrunner/local/testsuite.py
3
# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import imp import os from . import commands from . import statusfile from . import utils from ..objects import testcase # Use this to run several variants of the tests. VARIANT_FLAGS = { "default": [], "stress": ["--stress-opt", "--always-opt"], "turbofan": ["--turbo-asm", "--turbo-filter=*", "--always-opt"], "nocrankshaft": ["--nocrankshaft"]} FAST_VARIANT_FLAGS = [ f for v, f in VARIANT_FLAGS.iteritems() if v in ["default", "turbofan"] ] class TestSuite(object): @staticmethod def LoadTestSuite(root): name = root.split(os.path.sep)[-1] f = None try: (f, pathname, description) = imp.find_module("testcfg", [root]) module = imp.load_module("testcfg", f, pathname, description) return module.GetSuite(name, root) except: # Use default if no testcfg is present. return GoogleTestSuite(name, root) finally: if f: f.close() def __init__(self, name, root): self.name = name # string self.root = root # string containing path self.tests = None # list of TestCase objects self.rules = None # dictionary mapping test path to list of outcomes self.wildcards = None # dictionary mapping test paths to list of outcomes self.total_duration = None # float, assigned on demand def shell(self): return "d8" def suffix(self): return ".js" def status_file(self): return "%s/%s.status" % (self.root, self.name) # Used in the status file and for stdout printing. def CommonTestName(self, testcase): if utils.IsWindows(): return testcase.path.replace("\\", "/") else: return testcase.path def ListTests(self, context): raise NotImplementedError def VariantFlags(self, testcase, default_flags): if testcase.outcomes and statusfile.OnlyStandardVariant(testcase.outcomes): return [[]] if testcase.outcomes and statusfile.OnlyFastVariants(testcase.outcomes): return filter(lambda flags: flags in FAST_VARIANT_FLAGS, default_flags) return default_flags def DownloadData(self): pass def ReadStatusFile(self, variables): (self.rules, self.wildcards) = \ statusfile.ReadStatusFile(self.status_file(), variables) def ReadTestCases(self, context): self.tests = self.ListTests(context) @staticmethod def _FilterFlaky(flaky, mode): return (mode == "run" and not flaky) or (mode == "skip" and flaky) @staticmethod def _FilterSlow(slow, mode): return (mode == "run" and not slow) or (mode == "skip" and slow) @staticmethod def _FilterPassFail(pass_fail, mode): return (mode == "run" and not pass_fail) or (mode == "skip" and pass_fail) def FilterTestCasesByStatus(self, warn_unused_rules, flaky_tests="dontcare", slow_tests="dontcare", pass_fail_tests="dontcare"): filtered = [] used_rules = set() for t in self.tests: flaky = False slow = False pass_fail = False testname = self.CommonTestName(t) if testname in self.rules: used_rules.add(testname) # Even for skipped tests, as the TestCase object stays around and # PrintReport() uses it. t.outcomes = self.rules[testname] if statusfile.DoSkip(t.outcomes): continue # Don't add skipped tests to |filtered|. flaky = statusfile.IsFlaky(t.outcomes) slow = statusfile.IsSlow(t.outcomes) pass_fail = statusfile.IsPassOrFail(t.outcomes) skip = False for rule in self.wildcards: assert rule[-1] == '*' if testname.startswith(rule[:-1]): used_rules.add(rule) t.outcomes = self.wildcards[rule] if statusfile.DoSkip(t.outcomes): skip = True break # "for rule in self.wildcards" flaky = flaky or statusfile.IsFlaky(t.outcomes) slow = slow or statusfile.IsSlow(t.outcomes) pass_fail = pass_fail or statusfile.IsPassOrFail(t.outcomes) if (skip or self._FilterFlaky(flaky, flaky_tests) or self._FilterSlow(slow, slow_tests) or self._FilterPassFail(pass_fail, pass_fail_tests)): continue # "for t in self.tests" filtered.append(t) self.tests = filtered if not warn_unused_rules: return for rule in self.rules: if rule not in used_rules: print("Unused rule: %s -> %s" % (rule, self.rules[rule])) for rule in self.wildcards: if rule not in used_rules: print("Unused rule: %s -> %s" % (rule, self.wildcards[rule])) def FilterTestCasesByArgs(self, args): filtered = [] filtered_args = [] for a in args: argpath = a.split(os.path.sep) if argpath[0] != self.name: continue if len(argpath) == 1 or (len(argpath) == 2 and argpath[1] == '*'): return # Don't filter, run all tests in this suite. path = os.path.sep.join(argpath[1:]) if path[-1] == '*': path = path[:-1] filtered_args.append(path) for t in self.tests: for a in filtered_args: if t.path.startswith(a): filtered.append(t) break self.tests = filtered def GetFlagsForTestCase(self, testcase, context): raise NotImplementedError def GetSourceForTest(self, testcase): return "(no source available)" def IsFailureOutput(self, output, testpath): return output.exit_code != 0 def IsNegativeTest(self, testcase): return False def HasFailed(self, testcase): execution_failed = self.IsFailureOutput(testcase.output, testcase.path) if self.IsNegativeTest(testcase): return not execution_failed else: return execution_failed def GetOutcome(self, testcase): if testcase.output.HasCrashed(): return statusfile.CRASH elif testcase.output.HasTimedOut(): return statusfile.TIMEOUT elif self.HasFailed(testcase): return statusfile.FAIL else: return statusfile.PASS def HasUnexpectedOutput(self, testcase): outcome = self.GetOutcome(testcase) return not outcome in (testcase.outcomes or [statusfile.PASS]) def StripOutputForTransmit(self, testcase): if not self.HasUnexpectedOutput(testcase): testcase.output.stdout = "" testcase.output.stderr = "" def CalculateTotalDuration(self): self.total_duration = 0.0 for t in self.tests: self.total_duration += t.duration return self.total_duration class GoogleTestSuite(TestSuite): def __init__(self, name, root): super(GoogleTestSuite, self).__init__(name, root) def ListTests(self, context): shell = os.path.abspath(os.path.join(context.shell_dir, self.shell())) if utils.IsWindows(): shell += ".exe" output = commands.Execute(context.command_prefix + [shell, "--gtest_list_tests"] + context.extra_flags) if output.exit_code != 0: print output.stdout print output.stderr raise Exception("Test executable failed to list the tests.") tests = [] test_case = '' for line in output.stdout.splitlines(): test_desc = line.strip().split()[0] if test_desc.endswith('.'): test_case = test_desc elif test_case and test_desc: test = testcase.TestCase(self, test_case + test_desc, dependency=None) tests.append(test) tests.sort() return tests def GetFlagsForTestCase(self, testcase, context): return (testcase.flags + ["--gtest_filter=" + testcase.path] + ["--gtest_random_seed=%s" % context.random_seed] + ["--gtest_print_time=0"] + context.mode_flags) def shell(self): return self.name
coffenbacher/askbot-devel
refs/heads/master
askbot/deployment/package_utils.py
21
"""utilities that determine versions of packages that are part of askbot versions of all packages are normalized to three-tuples of integers (missing zeroes added) """ import coffin import django def get_coffin_version(): """Returns version of Coffin package as a three integer value tuple """ version = coffin.__version__ if len(version) == 2: micro_version = 0 elif len(version) == 3: micro_version = version[2] else: raise ValueError('unsupported version of coffin %s' % '.'.join(version)) major_version = version[0] minor_version = version[1] return (major_version, minor_version, micro_version) def get_django_version(): """returns three-tuple for the version of django""" return django.VERSION[:3]
davgibbs/django
refs/heads/master
tests/migrations/test_migrations_squashed_complex_multi_apps/__init__.py
12133432
winndows/cinder
refs/heads/master
cinder/db/sqlalchemy/migrate_repo/versions/030_placeholder.py
171
# 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. # Do not use this number for new Kilo work. New Kilo work starts after # all the placeholders. # http://lists.openstack.org/pipermail/openstack-dev/2013-March/006827.html def upgrade(migrate_engine): pass def downgrade(migration_engine): pass
korealerts1/sentry
refs/heads/master
src/sentry/migrations/0172_auto__del_field_team_owner.py
34
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Team.owner' db.delete_column(u'sentry_team', 'owner_id') def backwards(self, orm): # Adding field 'Team.owner' db.add_column(u'sentry_team', 'owner', self.gf('sentry.db.models.fields.foreignkey.FlexibleForeignKey')(to=orm['sentry.User'], null=True), keep_default=False) models = { 'sentry.accessgroup': { 'Meta': {'unique_together': "(('team', 'name'),)", 'object_name': 'AccessGroup'}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'managed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.User']", 'symmetrical': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'projects': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Project']", 'symmetrical': 'False'}), 'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}), 'type': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '50'}) }, 'sentry.activity': { 'Meta': {'object_name': 'Activity'}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Event']", 'null': 'True'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'}) }, 'sentry.alert': { 'Meta': {'object_name': 'Alert'}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'related_groups': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_alerts'", 'symmetrical': 'False', 'through': "orm['sentry.AlertRelatedGroup']", 'to': "orm['sentry.Group']"}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}) }, 'sentry.alertrelatedgroup': { 'Meta': {'unique_together': "(('group', 'alert'),)", 'object_name': 'AlertRelatedGroup'}, 'alert': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Alert']"}), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}) }, 'sentry.apikey': { 'Meta': {'object_name': 'ApiKey'}, 'allowed_origins': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}), 'label': ('django.db.models.fields.CharField', [], {'default': "'Default'", 'max_length': '64', 'blank': 'True'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Organization']"}), 'scopes': ('django.db.models.fields.BigIntegerField', [], {'default': 'None'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}) }, 'sentry.auditlogentry': { 'Meta': {'object_name': 'AuditLogEntry'}, 'actor': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'audit_actors'", 'to': "orm['sentry.User']"}), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39', 'null': 'True'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'target_object': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}), 'target_user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'audit_targets'", 'null': 'True', 'to': "orm['sentry.User']"}) }, 'sentry.authidentity': { 'Meta': {'unique_together': "(('auth_provider', 'ident'), ('auth_provider', 'user'))", 'object_name': 'AuthIdentity'}, 'auth_provider': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.AuthProvider']"}), 'data': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'last_synced': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_verified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}) }, 'sentry.authprovider': { 'Meta': {'object_name': 'AuthProvider'}, 'config': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'default_global_access': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'default_role': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '50'}), 'default_teams': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Team']", 'symmetrical': 'False', 'blank': 'True'}), 'flags': ('django.db.models.fields.BigIntegerField', [], {'default': '0'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'last_sync': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']", 'unique': 'True'}), 'provider': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'sync_time': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}) }, 'sentry.broadcast': { 'Meta': {'object_name': 'Broadcast'}, 'badge': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'message': ('django.db.models.fields.CharField', [], {'max_length': '256'}) }, 'sentry.event': { 'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'Event', 'db_table': "'sentry_message'", 'index_together': "(('group', 'datetime'),)"}, 'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'data': ('sentry.db.models.fields.node.NodeField', [], {'null': 'True', 'blank': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'db_column': "'message_id'"}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'event_set'", 'null': 'True', 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'null': 'True'}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'time_spent': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'null': 'True'}) }, 'sentry.eventmapping': { 'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'EventMapping'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}) }, 'sentry.file': { 'Meta': {'object_name': 'File'}, 'checksum': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True'}), 'headers': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'path': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'size': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}), 'storage': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}), 'storage_options': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, 'sentry.group': { 'Meta': {'unique_together': "(('project', 'checksum'),)", 'object_name': 'Group', 'db_table': "'sentry_groupedmessage'"}, 'active_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'culprit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True', 'blank': 'True'}), 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'level': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}), 'logger': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'null': 'True'}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'resolved_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'score': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '0'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}), 'time_spent_count': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '0'}), 'time_spent_total': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '0'}), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '1', 'db_index': 'True'}) }, 'sentry.groupassignee': { 'Meta': {'object_name': 'GroupAssignee', 'db_table': "'sentry_groupasignee'"}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'unique': 'True', 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'sentry_assignee_set'", 'to': "orm['sentry.User']"}) }, 'sentry.groupbookmark': { 'Meta': {'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'sentry_bookmark_set'", 'to': "orm['sentry.User']"}) }, 'sentry.grouphash': { 'Meta': {'unique_together': "(('project', 'hash'),)", 'object_name': 'GroupHash'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}) }, 'sentry.groupmeta': { 'Meta': {'unique_together': "(('group', 'key'),)", 'object_name': 'GroupMeta'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'value': ('django.db.models.fields.TextField', [], {}) }, 'sentry.grouprulestatus': { 'Meta': {'unique_together': "(('rule', 'group'),)", 'object_name': 'GroupRuleStatus'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'last_active': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'rule': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Rule']"}), 'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}) }, 'sentry.groupseen': { 'Meta': {'unique_together': "(('user', 'group'),)", 'object_name': 'GroupSeen'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'db_index': 'False'}) }, 'sentry.grouptagkey': { 'Meta': {'unique_together': "(('project', 'group', 'key'),)", 'object_name': 'GroupTagKey'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}) }, 'sentry.grouptagvalue': { 'Meta': {'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'GroupTagValue', 'db_table': "'sentry_messagefiltervalue'"}, 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'null': 'True', 'to': "orm['sentry.Project']"}), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'sentry.helppage': { 'Meta': {'object_name': 'HelpPage'}, 'content': ('django.db.models.fields.TextField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_visible': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64', 'unique': 'True', 'null': 'True'}), 'priority': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '50'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, 'sentry.lostpasswordhash': { 'Meta': {'object_name': 'LostPasswordHash'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'unique': 'True'}) }, 'sentry.option': { 'Meta': {'object_name': 'Option'}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.organization': { 'Meta': {'object_name': 'Organization'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'flags': ('django.db.models.fields.BigIntegerField', [], {'default': '0'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'org_memberships'", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMember']", 'to': "orm['sentry.User']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'owner': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}) }, 'sentry.organizationaccessrequest': { 'Meta': {'unique_together': "(('team', 'member'),)", 'object_name': 'OrganizationAccessRequest'}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'member': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.OrganizationMember']"}), 'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}) }, 'sentry.organizationmember': { 'Meta': {'unique_together': "(('organization', 'user'), ('organization', 'email'))", 'object_name': 'OrganizationMember'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'flags': ('django.db.models.fields.BigIntegerField', [], {'default': '0'}), 'has_global_access': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'member_set'", 'to': "orm['sentry.Organization']"}), 'teams': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Team']", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMemberTeam']", 'blank': 'True'}), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '50'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'sentry_orgmember_set'", 'null': 'True', 'to': "orm['sentry.User']"}) }, 'sentry.organizationmemberteam': { 'Meta': {'unique_together': "(('team', 'organizationmember'),)", 'object_name': 'OrganizationMemberTeam', 'db_table': "'sentry_organizationmember_teams'"}, 'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'organizationmember': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.OrganizationMember']"}), 'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}) }, 'sentry.pendingteammember': { 'Meta': {'unique_together': "(('team', 'email'),)", 'object_name': 'PendingTeamMember'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'pending_member_set'", 'to': "orm['sentry.Team']"}), 'type': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '50'}) }, 'sentry.project': { 'Meta': {'unique_together': "(('team', 'slug'), ('organization', 'slug'))", 'object_name': 'Project'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}), 'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}) }, 'sentry.projectkey': { 'Meta': {'object_name': 'ProjectKey'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Project']"}), 'public_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}), 'roles': ('django.db.models.fields.BigIntegerField', [], {'default': '1'}), 'secret_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}), 'user_added': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'keys_added_set'", 'null': 'True', 'to': "orm['sentry.User']"}) }, 'sentry.projectoption': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'"}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.release': { 'Meta': {'unique_together': "(('project', 'version'),)", 'object_name': 'Release'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, 'sentry.releasefile': { 'Meta': {'unique_together': "(('release', 'ident'),)", 'object_name': 'ReleaseFile'}, 'file': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.File']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'name': ('django.db.models.fields.TextField', [], {}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'release': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Release']"}) }, 'sentry.rule': { 'Meta': {'object_name': 'Rule'}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}) }, 'sentry.tagkey': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'TagKey', 'db_table': "'sentry_filterkey'"}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}) }, 'sentry.tagvalue': { 'Meta': {'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'TagValue', 'db_table': "'sentry_filtervalue'"}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True', 'blank': 'True'}), 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'sentry.team': { 'Meta': {'unique_together': "(('organization', 'slug'),)", 'object_name': 'Team'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}) }, 'sentry.teammember': { 'Meta': {'unique_together': "(('team', 'user'),)", 'object_name': 'TeamMember'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}), 'type': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '50'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}) }, 'sentry.user': { 'Meta': {'object_name': 'User', 'db_table': "'auth_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'}), 'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_managed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), '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'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}) }, 'sentry.useroption': { 'Meta': {'unique_together': "(('user', 'project', 'key'),)", 'object_name': 'UserOption'}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) } } complete_apps = ['sentry']
ChaosData/iRcbRg
refs/heads/master
args.py
1
''' nick irc(s)://hostname1:port channel1 irc(s)://hostname2:port2 channel2 ''' import argparse def parseArgs(argv): parser = argparse.ArgumentParser(description='Brigde two IRC channels.') parser.add_argument('-n', '--nick', metavar='nickname', default='iRcbRg', type=str, nargs='?', help='Nickname to appear in both channels. Defaults to "iRcbRg"') parser.add_argument('-u', '--user', metavar='username', default='iRcbRg', type=str, nargs='?', help='IRC user name. Defaults to "iRcbRg"') parser.add_argument('-r', '--real', metavar='real name', default='iRcbRg Smith', type=str, nargs='?', help='IRC real name. Defaults to "iRcbRg Smith"') parser.add_argument('uri1', metavar='URI_1', type=str, help='URI of first IRC server. ex: irc(s)://irc.example.com:1234') parser.add_argument('chan1', metavar='channel_1', type=str, help='Channel on the first IRC server. ex: (#)python') parser.add_argument('uri2', metavar='URI_2', type=str, help='URI of second IRC server. ex: irc(s)://irc.example.info:1234') parser.add_argument('chan2', metavar='channel_2', type=str, help='Channel on the second IRC server. ex: (#)twisted') args = parser.parse_args(argv) return args if __name__=='__main__': import sys print parseArgs(sys.argv)
Samuel789/MediPi
refs/heads/master
MedManagementWeb/env/lib/python3.5/site-packages/setuptools/command/upload_docs.py
173
# -*- coding: utf-8 -*- """upload_docs Implements a Distutils 'upload_docs' subcommand (upload documentation to PyPI's pythonhosted.org). """ from base64 import standard_b64encode from distutils import log from distutils.errors import DistutilsOptionError import os import socket import zipfile import tempfile import shutil import itertools import functools from setuptools.extern import six from setuptools.extern.six.moves import http_client, urllib from pkg_resources import iter_entry_points from .upload import upload def _encode(s): errors = 'surrogateescape' if six.PY3 else 'strict' return s.encode('utf-8', errors) class upload_docs(upload): # override the default repository as upload_docs isn't # supported by Warehouse (and won't be). DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi/' description = 'Upload documentation to PyPI' user_options = [ ('repository=', 'r', "url of repository [default: %s]" % upload.DEFAULT_REPOSITORY), ('show-response', None, 'display full response text from server'), ('upload-dir=', None, 'directory to upload'), ] boolean_options = upload.boolean_options def has_sphinx(self): if self.upload_dir is None: for ep in iter_entry_points('distutils.commands', 'build_sphinx'): return True sub_commands = [('build_sphinx', has_sphinx)] def initialize_options(self): upload.initialize_options(self) self.upload_dir = None self.target_dir = None def finalize_options(self): upload.finalize_options(self) if self.upload_dir is None: if self.has_sphinx(): build_sphinx = self.get_finalized_command('build_sphinx') self.target_dir = build_sphinx.builder_target_dir else: build = self.get_finalized_command('build') self.target_dir = os.path.join(build.build_base, 'docs') else: self.ensure_dirname('upload_dir') self.target_dir = self.upload_dir if 'pypi.python.org' in self.repository: log.warn("Upload_docs command is deprecated. Use RTD instead.") self.announce('Using upload directory %s' % self.target_dir) def create_zipfile(self, filename): zip_file = zipfile.ZipFile(filename, "w") try: self.mkpath(self.target_dir) # just in case for root, dirs, files in os.walk(self.target_dir): if root == self.target_dir and not files: tmpl = "no files found in upload directory '%s'" raise DistutilsOptionError(tmpl % self.target_dir) for name in files: full = os.path.join(root, name) relative = root[len(self.target_dir):].lstrip(os.path.sep) dest = os.path.join(relative, name) zip_file.write(full, dest) finally: zip_file.close() def run(self): # Run sub commands for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) tmp_dir = tempfile.mkdtemp() name = self.distribution.metadata.get_name() zip_file = os.path.join(tmp_dir, "%s.zip" % name) try: self.create_zipfile(zip_file) self.upload_file(zip_file) finally: shutil.rmtree(tmp_dir) @staticmethod def _build_part(item, sep_boundary): key, values = item title = '\nContent-Disposition: form-data; name="%s"' % key # handle multiple entries for the same name if not isinstance(values, list): values = [values] for value in values: if isinstance(value, tuple): title += '; filename="%s"' % value[0] value = value[1] else: value = _encode(value) yield sep_boundary yield _encode(title) yield b"\n\n" yield value if value and value[-1:] == b'\r': yield b'\n' # write an extra newline (lurve Macs) @classmethod def _build_multipart(cls, data): """ Build up the MIME payload for the POST data """ boundary = b'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' sep_boundary = b'\n--' + boundary end_boundary = sep_boundary + b'--' end_items = end_boundary, b"\n", builder = functools.partial( cls._build_part, sep_boundary=sep_boundary, ) part_groups = map(builder, data.items()) parts = itertools.chain.from_iterable(part_groups) body_items = itertools.chain(parts, end_items) content_type = 'multipart/form-data; boundary=%s' % boundary.decode('ascii') return b''.join(body_items), content_type def upload_file(self, filename): with open(filename, 'rb') as f: content = f.read() meta = self.distribution.metadata data = { ':action': 'doc_upload', 'name': meta.get_name(), 'content': (os.path.basename(filename), content), } # set up the authentication credentials = _encode(self.username + ':' + self.password) credentials = standard_b64encode(credentials) if six.PY3: credentials = credentials.decode('ascii') auth = "Basic " + credentials body, ct = self._build_multipart(data) msg = "Submitting documentation to %s" % (self.repository) self.announce(msg, log.INFO) # build the Request # We can't use urllib2 since we need to send the Basic # auth right with the first request schema, netloc, url, params, query, fragments = \ urllib.parse.urlparse(self.repository) assert not params and not query and not fragments if schema == 'http': conn = http_client.HTTPConnection(netloc) elif schema == 'https': conn = http_client.HTTPSConnection(netloc) else: raise AssertionError("unsupported schema " + schema) data = '' try: conn.connect() conn.putrequest("POST", url) content_type = ct conn.putheader('Content-type', content_type) conn.putheader('Content-length', str(len(body))) conn.putheader('Authorization', auth) conn.endheaders() conn.send(body) except socket.error as e: self.announce(str(e), log.ERROR) return r = conn.getresponse() if r.status == 200: msg = 'Server response (%s): %s' % (r.status, r.reason) self.announce(msg, log.INFO) elif r.status == 301: location = r.getheader('Location') if location is None: location = 'https://pythonhosted.org/%s/' % meta.get_name() msg = 'Upload successful. Visit %s' % location self.announce(msg, log.INFO) else: msg = 'Upload failed (%s): %s' % (r.status, r.reason) self.announce(msg, log.ERROR) if self.show_response: print('-' * 75, r.read(), '-' * 75)
ywcui1990/nupic
refs/heads/master
external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_tkagg.py
69
# Todd Miller jmiller@stsci.edu from __future__ import division import os, sys, math import Tkinter as Tk, FileDialog import tkagg # Paint image to Tk photo blitter extension from backend_agg import FigureCanvasAgg import os.path import matplotlib from matplotlib.cbook import is_string_like from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \ FigureManagerBase, FigureCanvasBase, NavigationToolbar2, cursors from matplotlib.figure import Figure from matplotlib._pylab_helpers import Gcf import matplotlib.windowing as windowing from matplotlib.widgets import SubplotTool import matplotlib.cbook as cbook rcParams = matplotlib.rcParams verbose = matplotlib.verbose backend_version = Tk.TkVersion # the true dots per inch on the screen; should be display dependent # see http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5 for some info about screen dpi PIXELS_PER_INCH = 75 cursord = { cursors.MOVE: "fleur", cursors.HAND: "hand2", cursors.POINTER: "arrow", cursors.SELECT_REGION: "tcross", } def round(x): return int(math.floor(x+0.5)) def raise_msg_to_str(msg): """msg is a return arg from a raise. Join with new lines""" if not is_string_like(msg): msg = '\n'.join(map(str, msg)) return msg def error_msg_tkpaint(msg, parent=None): import tkMessageBox tkMessageBox.showerror("matplotlib", msg) def draw_if_interactive(): if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.show() def show(): """ Show all the figures and enter the gtk mainloop This should be the last line of your script. This function sets interactive mode to True, as detailed on http://matplotlib.sf.net/interactive.html """ for manager in Gcf.get_all_fig_managers(): manager.show() import matplotlib matplotlib.interactive(True) if rcParams['tk.pythoninspect']: os.environ['PYTHONINSPECT'] = '1' if show._needmain: Tk.mainloop() show._needmain = False show._needmain = True def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ _focus = windowing.FocusManager() FigureClass = kwargs.pop('FigureClass', Figure) figure = FigureClass(*args, **kwargs) window = Tk.Tk() canvas = FigureCanvasTkAgg(figure, master=window) figManager = FigureManagerTkAgg(canvas, num, window) if matplotlib.is_interactive(): figManager.show() return figManager class FigureCanvasTkAgg(FigureCanvasAgg): keyvald = {65507 : 'control', 65505 : 'shift', 65513 : 'alt', 65508 : 'control', 65506 : 'shift', 65514 : 'alt', 65361 : 'left', 65362 : 'up', 65363 : 'right', 65364 : 'down', 65307 : 'escape', 65470 : 'f1', 65471 : 'f2', 65472 : 'f3', 65473 : 'f4', 65474 : 'f5', 65475 : 'f6', 65476 : 'f7', 65477 : 'f8', 65478 : 'f9', 65479 : 'f10', 65480 : 'f11', 65481 : 'f12', 65300 : 'scroll_lock', 65299 : 'break', 65288 : 'backspace', 65293 : 'enter', 65379 : 'insert', 65535 : 'delete', 65360 : 'home', 65367 : 'end', 65365 : 'pageup', 65366 : 'pagedown', 65438 : '0', 65436 : '1', 65433 : '2', 65435 : '3', 65430 : '4', 65437 : '5', 65432 : '6', 65429 : '7', 65431 : '8', 65434 : '9', 65451 : '+', 65453 : '-', 65450 : '*', 65455 : '/', 65439 : 'dec', 65421 : 'enter', } def __init__(self, figure, master=None, resize_callback=None): FigureCanvasAgg.__init__(self, figure) self._idle = True t1,t2,w,h = self.figure.bbox.bounds w, h = int(w), int(h) self._tkcanvas = Tk.Canvas( master=master, width=w, height=h, borderwidth=4) self._tkphoto = Tk.PhotoImage( master=self._tkcanvas, width=w, height=h) self._tkcanvas.create_image(w/2, h/2, image=self._tkphoto) self._resize_callback = resize_callback self._tkcanvas.bind("<Configure>", self.resize) self._tkcanvas.bind("<Key>", self.key_press) self._tkcanvas.bind("<Motion>", self.motion_notify_event) self._tkcanvas.bind("<KeyRelease>", self.key_release) for name in "<Button-1>", "<Button-2>", "<Button-3>": self._tkcanvas.bind(name, self.button_press_event) for name in "<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>": self._tkcanvas.bind(name, self.button_release_event) # Mouse wheel on Linux generates button 4/5 events for name in "<Button-4>", "<Button-5>": self._tkcanvas.bind(name, self.scroll_event) # Mouse wheel for windows goes to the window with the focus. # Since the canvas won't usually have the focus, bind the # event to the window containing the canvas instead. # See http://wiki.tcl.tk/3893 (mousewheel) for details root = self._tkcanvas.winfo_toplevel() root.bind("<MouseWheel>", self.scroll_event_windows) self._master = master self._tkcanvas.focus_set() # a dict from func-> cbook.Scheduler threads self.sourced = dict() # call the idle handler def on_idle(*ignore): self.idle_event() return True # disable until you figure out how to handle threads and interrupts #t = cbook.Idle(on_idle) #self._tkcanvas.after_idle(lambda *ignore: t.start()) def resize(self, event): width, height = event.width, event.height if self._resize_callback is not None: self._resize_callback(event) # compute desired figure size in inches dpival = self.figure.dpi winch = width/dpival hinch = height/dpival self.figure.set_size_inches(winch, hinch) self._tkcanvas.delete(self._tkphoto) self._tkphoto = Tk.PhotoImage( master=self._tkcanvas, width=width, height=height) self._tkcanvas.create_image(width/2,height/2,image=self._tkphoto) self.resize_event() self.show() def draw(self): FigureCanvasAgg.draw(self) tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2) self._master.update_idletasks() def blit(self, bbox=None): tkagg.blit(self._tkphoto, self.renderer._renderer, bbox=bbox, colormode=2) self._master.update_idletasks() show = draw def draw_idle(self): 'update drawing area only if idle' d = self._idle self._idle = False def idle_draw(*args): self.draw() self._idle = True if d: self._tkcanvas.after_idle(idle_draw) def get_tk_widget(self): """returns the Tk widget used to implement FigureCanvasTkAgg. Although the initial implementation uses a Tk canvas, this routine is intended to hide that fact. """ return self._tkcanvas def motion_notify_event(self, event): x = event.x # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) def button_press_event(self, event): x = event.x # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y num = getattr(event, 'num', None) if sys.platform=='darwin': # 2 and 3 were reversed on the OSX platform I # tested under tkagg if num==2: num=3 elif num==3: num=2 FigureCanvasBase.button_press_event(self, x, y, num, guiEvent=event) def button_release_event(self, event): x = event.x # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y num = getattr(event, 'num', None) if sys.platform=='darwin': # 2 and 3 were reversed on the OSX platform I # tested under tkagg if num==2: num=3 elif num==3: num=2 FigureCanvasBase.button_release_event(self, x, y, num, guiEvent=event) def scroll_event(self, event): x = event.x y = self.figure.bbox.height - event.y num = getattr(event, 'num', None) if num==4: step = -1 elif num==5: step = +1 else: step = 0 FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) def scroll_event_windows(self, event): """MouseWheel event processor""" # need to find the window that contains the mouse w = event.widget.winfo_containing(event.x_root, event.y_root) if w == self._tkcanvas: x = event.x_root - w.winfo_rootx() y = event.y_root - w.winfo_rooty() y = self.figure.bbox.height - y step = event.delta/120. FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) def _get_key(self, event): val = event.keysym_num if val in self.keyvald: key = self.keyvald[val] elif val<256: key = chr(val) else: key = None return key def key_press(self, event): key = self._get_key(event) FigureCanvasBase.key_press_event(self, key, guiEvent=event) def key_release(self, event): key = self._get_key(event) FigureCanvasBase.key_release_event(self, key, guiEvent=event) def flush_events(self): self._master.update() def start_event_loop(self,timeout): FigureCanvasBase.start_event_loop_default(self,timeout) start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__ class FigureManagerTkAgg(FigureManagerBase): """ Public attributes canvas : The FigureCanvas instance num : The Figure number toolbar : The tk.Toolbar window : The tk.Window """ def __init__(self, canvas, num, window): FigureManagerBase.__init__(self, canvas, num) self.window = window self.window.withdraw() self.window.wm_title("Figure %d" % num) self.canvas = canvas self._num = num t1,t2,w,h = canvas.figure.bbox.bounds w, h = int(w), int(h) self.window.minsize(int(w*3/4),int(h*3/4)) if matplotlib.rcParams['toolbar']=='classic': self.toolbar = NavigationToolbar( canvas, self.window ) elif matplotlib.rcParams['toolbar']=='toolbar2': self.toolbar = NavigationToolbar2TkAgg( canvas, self.window ) else: self.toolbar = None if self.toolbar is not None: self.toolbar.update() self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self._shown = False def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar != None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) # attach a show method to the figure for pylab ease of use self.canvas.figure.show = lambda *args: self.show() def resize(self, event): width, height = event.width, event.height self.toolbar.configure(width=width) # , height=height) def show(self): """ this function doesn't segfault but causes the PyEval_RestoreThread: NULL state bug on win32 """ def destroy(*args): self.window = None Gcf.destroy(self._num) if not self._shown: self.canvas._tkcanvas.bind("<Destroy>", destroy) _focus = windowing.FocusManager() if not self._shown: self.window.deiconify() # anim.py requires this if sys.platform=='win32' : self.window.update() else: self.canvas.draw() self._shown = True def destroy(self, *args): if Gcf.get_num_fig_managers()==0 and not matplotlib.is_interactive(): if self.window is not None: self.window.quit() if self.window is not None: #self.toolbar.destroy() self.window.destroy() pass self.window = None def set_window_title(self, title): self.window.wm_title(title) class AxisMenu: def __init__(self, master, naxes): self._master = master self._naxes = naxes self._mbar = Tk.Frame(master=master, relief=Tk.RAISED, borderwidth=2) self._mbar.pack(side=Tk.LEFT) self._mbutton = Tk.Menubutton( master=self._mbar, text="Axes", underline=0) self._mbutton.pack(side=Tk.LEFT, padx="2m") self._mbutton.menu = Tk.Menu(self._mbutton) self._mbutton.menu.add_command( label="Select All", command=self.select_all) self._mbutton.menu.add_command( label="Invert All", command=self.invert_all) self._axis_var = [] self._checkbutton = [] for i in range(naxes): self._axis_var.append(Tk.IntVar()) self._axis_var[i].set(1) self._checkbutton.append(self._mbutton.menu.add_checkbutton( label = "Axis %d" % (i+1), variable=self._axis_var[i], command=self.set_active)) self._mbutton.menu.invoke(self._mbutton.menu.index("Select All")) self._mbutton['menu'] = self._mbutton.menu self._mbar.tk_menuBar(self._mbutton) self.set_active() def adjust(self, naxes): if self._naxes < naxes: for i in range(self._naxes, naxes): self._axis_var.append(Tk.IntVar()) self._axis_var[i].set(1) self._checkbutton.append( self._mbutton.menu.add_checkbutton( label = "Axis %d" % (i+1), variable=self._axis_var[i], command=self.set_active)) elif self._naxes > naxes: for i in range(self._naxes-1, naxes-1, -1): del self._axis_var[i] self._mbutton.menu.forget(self._checkbutton[i]) del self._checkbutton[i] self._naxes = naxes self.set_active() def get_indices(self): a = [i for i in range(len(self._axis_var)) if self._axis_var[i].get()] return a def set_active(self): self._master.set_active(self.get_indices()) def invert_all(self): for a in self._axis_var: a.set(not a.get()) self.set_active() def select_all(self): for a in self._axis_var: a.set(1) self.set_active() class NavigationToolbar(Tk.Frame): """ Public attriubutes canvas - the FigureCanvas (gtk.DrawingArea) win - the gtk.Window """ def _Button(self, text, file, command): file = os.path.join(rcParams['datapath'], 'images', file) im = Tk.PhotoImage(master=self, file=file) b = Tk.Button( master=self, text=text, padx=2, pady=2, image=im, command=command) b._ntimage = im b.pack(side=Tk.LEFT) return b def __init__(self, canvas, window): self.canvas = canvas self.window = window xmin, xmax = canvas.figure.bbox.intervalx height, width = 50, xmax-xmin Tk.Frame.__init__(self, master=self.window, width=width, height=height, borderwidth=2) self.update() # Make axes menu self.bLeft = self._Button( text="Left", file="stock_left.ppm", command=lambda x=-1: self.panx(x)) self.bRight = self._Button( text="Right", file="stock_right.ppm", command=lambda x=1: self.panx(x)) self.bZoomInX = self._Button( text="ZoomInX",file="stock_zoom-in.ppm", command=lambda x=1: self.zoomx(x)) self.bZoomOutX = self._Button( text="ZoomOutX", file="stock_zoom-out.ppm", command=lambda x=-1: self.zoomx(x)) self.bUp = self._Button( text="Up", file="stock_up.ppm", command=lambda y=1: self.pany(y)) self.bDown = self._Button( text="Down", file="stock_down.ppm", command=lambda y=-1: self.pany(y)) self.bZoomInY = self._Button( text="ZoomInY", file="stock_zoom-in.ppm", command=lambda y=1: self.zoomy(y)) self.bZoomOutY = self._Button( text="ZoomOutY",file="stock_zoom-out.ppm", command=lambda y=-1: self.zoomy(y)) self.bSave = self._Button( text="Save", file="stock_save_as.ppm", command=self.save_figure) self.pack(side=Tk.BOTTOM, fill=Tk.X) def set_active(self, ind): self._ind = ind self._active = [ self._axes[i] for i in self._ind ] def panx(self, direction): for a in self._active: a.xaxis.pan(direction) self.canvas.draw() def pany(self, direction): for a in self._active: a.yaxis.pan(direction) self.canvas.draw() def zoomx(self, direction): for a in self._active: a.xaxis.zoom(direction) self.canvas.draw() def zoomy(self, direction): for a in self._active: a.yaxis.zoom(direction) self.canvas.draw() def save_figure(self): fs = FileDialog.SaveFileDialog(master=self.window, title='Save the figure') try: self.lastDir except AttributeError: self.lastDir = os.curdir fname = fs.go(dir_or_file=self.lastDir) # , pattern="*.png") if fname is None: # Cancel return self.lastDir = os.path.dirname(fname) try: self.canvas.print_figure(fname) except IOError, msg: err = '\n'.join(map(str, msg)) msg = 'Failed to save %s: Error msg was\n\n%s' % ( fname, err) error_msg_tkpaint(msg) def update(self): _focus = windowing.FocusManager() self._axes = self.canvas.figure.axes naxes = len(self._axes) if not hasattr(self, "omenu"): self.set_active(range(naxes)) self.omenu = AxisMenu(master=self, naxes=naxes) else: self.omenu.adjust(naxes) class NavigationToolbar2TkAgg(NavigationToolbar2, Tk.Frame): """ Public attriubutes canvas - the FigureCanvas (gtk.DrawingArea) win - the gtk.Window """ def __init__(self, canvas, window): self.canvas = canvas self.window = window self._idle = True #Tk.Frame.__init__(self, master=self.canvas._tkcanvas) NavigationToolbar2.__init__(self, canvas) def destroy(self, *args): del self.message Tk.Frame.destroy(self, *args) def set_message(self, s): self.message.set(s) def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y0 = height-y0 y1 = height-y1 try: self.lastrect except AttributeError: pass else: self.canvas._tkcanvas.delete(self.lastrect) self.lastrect = self.canvas._tkcanvas.create_rectangle(x0, y0, x1, y1) #self.canvas.draw() def release(self, event): try: self.lastrect except AttributeError: pass else: self.canvas._tkcanvas.delete(self.lastrect) del self.lastrect def set_cursor(self, cursor): self.window.configure(cursor=cursord[cursor]) def _Button(self, text, file, command): file = os.path.join(rcParams['datapath'], 'images', file) im = Tk.PhotoImage(master=self, file=file) b = Tk.Button( master=self, text=text, padx=2, pady=2, image=im, command=command) b._ntimage = im b.pack(side=Tk.LEFT) return b def _init_toolbar(self): xmin, xmax = self.canvas.figure.bbox.intervalx height, width = 50, xmax-xmin Tk.Frame.__init__(self, master=self.window, width=width, height=height, borderwidth=2) self.update() # Make axes menu self.bHome = self._Button( text="Home", file="home.ppm", command=self.home) self.bBack = self._Button( text="Back", file="back.ppm", command = self.back) self.bForward = self._Button(text="Forward", file="forward.ppm", command = self.forward) self.bPan = self._Button( text="Pan", file="move.ppm", command = self.pan) self.bZoom = self._Button( text="Zoom", file="zoom_to_rect.ppm", command = self.zoom) self.bsubplot = self._Button( text="Configure Subplots", file="subplots.ppm", command = self.configure_subplots) self.bsave = self._Button( text="Save", file="filesave.ppm", command = self.save_figure) self.message = Tk.StringVar(master=self) self._message_label = Tk.Label(master=self, textvariable=self.message) self._message_label.pack(side=Tk.RIGHT) self.pack(side=Tk.BOTTOM, fill=Tk.X) def configure_subplots(self): toolfig = Figure(figsize=(6,3)) window = Tk.Tk() canvas = FigureCanvasTkAgg(toolfig, master=window) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) def save_figure(self): from tkFileDialog import asksaveasfilename from tkMessageBox import showerror filetypes = self.canvas.get_supported_filetypes().copy() default_filetype = self.canvas.get_default_filetype() # Tk doesn't provide a way to choose a default filetype, # so we just have to put it first default_filetype_name = filetypes[default_filetype] del filetypes[default_filetype] sorted_filetypes = filetypes.items() sorted_filetypes.sort() sorted_filetypes.insert(0, (default_filetype, default_filetype_name)) tk_filetypes = [ (name, '*.%s' % ext) for (ext, name) in sorted_filetypes] fname = asksaveasfilename( master=self.window, title='Save the figure', filetypes = tk_filetypes, defaultextension = self.canvas.get_default_filetype() ) if fname == "" or fname == (): return else: try: # This method will handle the delegation to the correct type self.canvas.print_figure(fname) except Exception, e: showerror("Error saving file", str(e)) def set_active(self, ind): self._ind = ind self._active = [ self._axes[i] for i in self._ind ] def update(self): _focus = windowing.FocusManager() self._axes = self.canvas.figure.axes naxes = len(self._axes) #if not hasattr(self, "omenu"): # self.set_active(range(naxes)) # self.omenu = AxisMenu(master=self, naxes=naxes) #else: # self.omenu.adjust(naxes) NavigationToolbar2.update(self) def dynamic_update(self): 'update drawing area only if idle' # legacy method; new method is canvas.draw_idle self.canvas.draw_idle() FigureManager = FigureManagerTkAgg
kinow-io/kinow-python-sdk
refs/heads/master
test/test_languages.py
1
# coding: utf-8 """ Server API Reference for Server API (REST/Json) OpenAPI spec version: 1.4.41 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kinow_client from kinow_client.rest import ApiException from kinow_client.models.languages import Languages class TestLanguages(unittest.TestCase): """ Languages unit test stubs """ def setUp(self): pass def tearDown(self): pass def testLanguages(self): """ Test Languages """ model = kinow_client.models.languages.Languages() if __name__ == '__main__': unittest.main()
RCOSDP/waterbutler
refs/heads/nii-mergework-201901
waterbutler/providers/figshare/settings.py
4
from waterbutler import settings config = settings.child('FIGSHARE_PROVIDER_CONFIG') BASE_URL = config.get('BASE_URL', 'https://api.figshare.com/v2') VIEW_URL = config.get('VIEW_URL', 'https://figshare.com/') DOWNLOAD_URL = config.get('VIEW_URL', 'https://ndownloader.figshare.com/') VALID_CONTAINER_TYPES = ['project', 'collection', 'article', 'fileset'] FOLDER_TYPES = [4] # Figshare ID for filesets PRIVATE_IDENTIFIER = 'https://api.figshare.com/v2/account/' ARTICLE_TYPE_IDENTIFIER = 'https://api.figshare.com/v2/account/articles/' # During initial testing this was set to 2 because file was not instantly ready after receiving HTTP 201 FILE_CREATE_WAIT = 0.1 # seconds passed to time.sleep # project/collection article listings are paginated. Specify max number of results returned per page. MAX_PAGE_SIZE = int(config.get('MAX_PAGE_SIZE', 100))
Gravecorp/Gap
refs/heads/master
Gap/Lib/fileinput.py
224
"""Helper class to quickly write a loop over all standard input files. Typical use is: import fileinput for line in fileinput.input(): process(line) This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-' it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the argument to input(). A single file name is also allowed. Functions filename(), lineno() return the filename and cumulative line number of the line that has just been read; filelineno() returns its line number in the current file; isfirstline() returns true iff the line just read is the first line of its file; isstdin() returns true iff the line was read from sys.stdin. Function nextfile() closes the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count; the filename is not changed until after the first line of the next file has been read. Function close() closes the sequence. Before any lines have been read, filename() returns None and both line numbers are zero; nextfile() has no effect. After all lines have been read, filename() and the line number functions return the values pertaining to the last line read; nextfile() has no effect. All files are opened in text mode by default, you can override this by setting the mode parameter to input() or FileInput.__init__(). If an I/O error occurs during opening or reading a file, the IOError exception is raised. If sys.stdin is used more than once, the second and further use will return no lines, except perhaps for interactive use, or if it has been explicitly reset (e.g. using sys.stdin.seek(0)). Empty files are opened and immediately closed; the only time their presence in the list of filenames is noticeable at all is when the last file opened is empty. It is possible that the last line of a file doesn't end in a newline character; otherwise lines are returned including the trailing newline. Class FileInput is the implementation; its methods filename(), lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close() correspond to the functions in the module. In addition it has a readline() method which returns the next input line, and a __getitem__() method which implements the sequence behavior. The sequence must be accessed in strictly sequential order; sequence access and readline() cannot be mixed. Optional in-place filtering: if the keyword argument inplace=1 is passed to input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file. This makes it possible to write a filter that rewrites its input file in place. If the keyword argument backup=".<some extension>" is also given, it specifies the extension for the backup file, and the backup file remains around; by default, the extension is ".bak" and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read. XXX The current implementation does not work for MS-DOS 8+3 filesystems. Performance: this module is unfortunately one of the slower ways of processing large numbers of input lines. Nevertheless, a significant speed-up has been obtained by using readlines(bufsize) instead of readline(). A new keyword argument, bufsize=N, is present on the input() function and the FileInput() class to override the default buffer size. XXX Possible additions: - optional getopt argument processing - isatty() - read(), read(size), even readlines() """ import sys, os __all__ = ["input","close","nextfile","filename","lineno","filelineno", "isfirstline","isstdin","FileInput"] _state = None DEFAULT_BUFSIZE = 8*1024 def input(files=None, inplace=0, backup="", bufsize=0, mode="r", openhook=None): """input([files[, inplace[, backup[, mode[, openhook]]]]]) Create an instance of the FileInput class. The instance will be used as global state for the functions of this module, and is also returned to use during iteration. The parameters to this function will be passed along to the constructor of the FileInput class. """ global _state if _state and _state._file: raise RuntimeError, "input() already active" _state = FileInput(files, inplace, backup, bufsize, mode, openhook) return _state def close(): """Close the sequence.""" global _state state = _state _state = None if state: state.close() def nextfile(): """ Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not changed until after the first line of the next file has been read. Before the first line has been read, this function has no effect; it cannot be used to skip the first file. After the last line of the last file has been read, this function has no effect. """ if not _state: raise RuntimeError, "no active input()" return _state.nextfile() def filename(): """ Return the name of the file currently being read. Before the first line has been read, returns None. """ if not _state: raise RuntimeError, "no active input()" return _state.filename() def lineno(): """ Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line. """ if not _state: raise RuntimeError, "no active input()" return _state.lineno() def filelineno(): """ Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file. """ if not _state: raise RuntimeError, "no active input()" return _state.filelineno() def fileno(): """ Return the file number of the current file. When no file is currently opened, returns -1. """ if not _state: raise RuntimeError, "no active input()" return _state.fileno() def isfirstline(): """ Returns true the line just read is the first line of its file, otherwise returns false. """ if not _state: raise RuntimeError, "no active input()" return _state.isfirstline() def isstdin(): """ Returns true if the last line was read from sys.stdin, otherwise returns false. """ if not _state: raise RuntimeError, "no active input()" return _state.isstdin() class FileInput: """class FileInput([files[, inplace[, backup[, mode[, openhook]]]]]) Class FileInput is the implementation of the module; its methods filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(), nextfile() and close() correspond to the functions of the same name in the module. In addition it has a readline() method which returns the next input line, and a __getitem__() method which implements the sequence behavior. The sequence must be accessed in strictly sequential order; random access and readline() cannot be mixed. """ def __init__(self, files=None, inplace=0, backup="", bufsize=0, mode="r", openhook=None): if isinstance(files, basestring): files = (files,) else: if files is None: files = sys.argv[1:] if not files: files = ('-',) else: files = tuple(files) self._files = files self._inplace = inplace self._backup = backup self._bufsize = bufsize or DEFAULT_BUFSIZE self._savestdout = None self._output = None self._filename = None self._lineno = 0 self._filelineno = 0 self._file = None self._isstdin = False self._backupfilename = None self._buffer = [] self._bufindex = 0 # restrict mode argument to reading modes if mode not in ('r', 'rU', 'U', 'rb'): raise ValueError("FileInput opening mode must be one of " "'r', 'rU', 'U' and 'rb'") self._mode = mode if inplace and openhook: raise ValueError("FileInput cannot use an opening hook in inplace mode") elif openhook and not hasattr(openhook, '__call__'): raise ValueError("FileInput openhook must be callable") self._openhook = openhook def __del__(self): self.close() def close(self): self.nextfile() self._files = () def __iter__(self): return self def next(self): try: line = self._buffer[self._bufindex] except IndexError: pass else: self._bufindex += 1 self._lineno += 1 self._filelineno += 1 return line line = self.readline() if not line: raise StopIteration return line def __getitem__(self, i): if i != self._lineno: raise RuntimeError, "accessing lines out of order" try: return self.next() except StopIteration: raise IndexError, "end of input reached" def nextfile(self): savestdout = self._savestdout self._savestdout = 0 if savestdout: sys.stdout = savestdout output = self._output self._output = 0 if output: output.close() file = self._file self._file = 0 if file and not self._isstdin: file.close() backupfilename = self._backupfilename self._backupfilename = 0 if backupfilename and not self._backup: try: os.unlink(backupfilename) except OSError: pass self._isstdin = False self._buffer = [] self._bufindex = 0 def readline(self): try: line = self._buffer[self._bufindex] except IndexError: pass else: self._bufindex += 1 self._lineno += 1 self._filelineno += 1 return line if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = False self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = True else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or os.extsep+"bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next few lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, self._mode) try: perm = os.fstat(self._file.fileno()).st_mode except OSError: self._output = open(self._filename, "w") else: fd = os.open(self._filename, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, perm) self._output = os.fdopen(fd, "w") try: if hasattr(os, 'chmod'): os.chmod(self._filename, perm) except OSError: pass self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError if self._openhook: self._file = self._openhook(self._filename, self._mode) else: self._file = open(self._filename, self._mode) self._buffer = self._file.readlines(self._bufsize) self._bufindex = 0 if not self._buffer: self.nextfile() # Recursive call return self.readline() def filename(self): return self._filename def lineno(self): return self._lineno def filelineno(self): return self._filelineno def fileno(self): if self._file: try: return self._file.fileno() except ValueError: return -1 else: return -1 def isfirstline(self): return self._filelineno == 1 def isstdin(self): return self._isstdin def hook_compressed(filename, mode): ext = os.path.splitext(filename)[1] if ext == '.gz': import gzip return gzip.open(filename, mode) elif ext == '.bz2': import bz2 return bz2.BZ2File(filename, mode) else: return open(filename, mode) def hook_encoded(encoding): import codecs def openhook(filename, mode): return codecs.open(filename, mode, encoding) return openhook def _test(): import getopt inplace = 0 backup = 0 opts, args = getopt.getopt(sys.argv[1:], "ib:") for o, a in opts: if o == '-i': inplace = 1 if o == '-b': backup = a for line in input(args, inplace=inplace, backup=backup): if line[-1:] == '\n': line = line[:-1] if line[-1:] == '\r': line = line[:-1] print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(), isfirstline() and "*" or "", line) print "%d: %s[%d]" % (lineno(), filename(), filelineno()) if __name__ == '__main__': _test()
viewdy/phantomjs2
refs/heads/master
src/qt/qtwebkit/Tools/Scripts/webkitpy/common/checkout/__init__.py
135
# Required for Python to search this directory for module files from .checkout import Checkout
xorstream/unicorn
refs/heads/master
tests/regress/wrong_rip_arm.py
10
#!/usr/bin/python from unicorn import * from unicorn.x86_const import * from unicorn.arm_const import * import regress # adds r1, #0x48 # ldrsb r7, [r7, r7] # ldrsh r7, [r2, r1] # ldr r0, [pc, #0x168] # cmp r7, #0xbf # str r7, [r5, #0x20] # ldr r1, [r5, #0x64] # strb r7, [r5, #0xc] # ldr r0, [pc, #0x1a0] binary1 = b'\x48\x31\xff\x57\x57\x5e\x5a\x48\xbf\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xef\x08\x57\x54\x5f\x6a\x3b\x58\x0f\x05' # binary1 = b'\x48\x31\xff\x57' #adds r1, #0x48 #ldrsb r7, [r7, r7] class WrongRIPArm(regress.RegressTest): def runTest(self): mu = Uc(UC_ARCH_ARM, UC_MODE_THUMB) mu.mem_map(0, 2 * 1024 * 1024) # write machine code to be emulated to memory mu.mem_write(0, binary1) mu.reg_write(UC_ARM_REG_R13, 1 * 1024 * 1024) # emu for maximum 1 instruction. mu.emu_start(0, len(binary1), 0, 1) self.assertEqual(0x48, mu.reg_read(UC_ARM_REG_R1)) pos = mu.reg_read(UC_ARM_REG_R15) self.assertEqual(0x2, pos) if __name__ == '__main__': regress.main()
darkfeline/pymsmtpq
refs/heads/master
mir/msmtpq/__init__.py
2
# Copyright (C) 2016 Allen Li # # 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. __version__ = '1.0.1'
sqlalchemy/sqlalchemy
refs/heads/master
test/orm/test_pickled.py
3
import copy import sqlalchemy as sa from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import String from sqlalchemy import testing from sqlalchemy.orm import aliased from sqlalchemy.orm import attributes from sqlalchemy.orm import clear_mappers from sqlalchemy.orm import exc as orm_exc from sqlalchemy.orm import instrumentation from sqlalchemy.orm import lazyload from sqlalchemy.orm import mapper from sqlalchemy.orm import relationship from sqlalchemy.orm import state as sa_state from sqlalchemy.orm import subqueryload from sqlalchemy.orm import with_polymorphic from sqlalchemy.orm.collections import attribute_mapped_collection from sqlalchemy.orm.collections import column_mapped_collection from sqlalchemy.testing import assert_raises_message from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.testing.fixtures import fixture_session from sqlalchemy.testing.pickleable import Address from sqlalchemy.testing.pickleable import Child1 from sqlalchemy.testing.pickleable import Child2 from sqlalchemy.testing.pickleable import Dingaling from sqlalchemy.testing.pickleable import EmailUser from sqlalchemy.testing.pickleable import Order from sqlalchemy.testing.pickleable import Parent from sqlalchemy.testing.pickleable import Screen from sqlalchemy.testing.pickleable import User from sqlalchemy.testing.schema import Column from sqlalchemy.testing.schema import Table from sqlalchemy.testing.util import picklers from sqlalchemy.util import pickle from test.orm import _fixtures from .inheritance._poly_fixtures import _Polymorphic from .inheritance._poly_fixtures import Company from .inheritance._poly_fixtures import Engineer from .inheritance._poly_fixtures import Manager from .inheritance._poly_fixtures import Person class PickleTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(30), nullable=False), test_needs_acid=True, test_needs_fk=True, ) Table( "addresses", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("user_id", None, ForeignKey("users.id")), Column("email_address", String(50), nullable=False), test_needs_acid=True, test_needs_fk=True, ) Table( "orders", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("user_id", None, ForeignKey("users.id")), Column("address_id", None, ForeignKey("addresses.id")), Column("description", String(30)), Column("isopen", Integer), test_needs_acid=True, test_needs_fk=True, ) Table( "dingalings", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("address_id", None, ForeignKey("addresses.id")), Column("data", String(30)), test_needs_acid=True, test_needs_fk=True, ) def _option_test_fixture(self): users, addresses, dingalings = ( self.tables.users, self.tables.addresses, self.tables.dingalings, ) mapper( User, users, properties={"addresses": relationship(Address, backref="user")}, ) mapper( Address, addresses, properties={"dingaling": relationship(Dingaling)}, ) mapper(Dingaling, dingalings) sess = fixture_session() u1 = User(name="ed") u1.addresses.append(Address(email_address="ed@bar.com")) sess.add(u1) sess.flush() sess.expunge_all() return sess, User, Address, Dingaling def test_transient(self): users, addresses = (self.tables.users, self.tables.addresses) mapper( User, users, properties={"addresses": relationship(Address, backref="user")}, ) mapper(Address, addresses) sess = fixture_session() u1 = User(name="ed") u1.addresses.append(Address(email_address="ed@bar.com")) u2 = pickle.loads(pickle.dumps(u1)) sess.add(u2) sess.flush() sess.expunge_all() eq_(u1, sess.query(User).get(u2.id)) def test_no_mappers(self): users = self.tables.users mapper(User, users) u1 = User(name="ed") u1_pickled = pickle.dumps(u1, -1) clear_mappers() assert_raises_message( orm_exc.UnmappedInstanceError, "Cannot deserialize object of type " "<class 'sqlalchemy.testing.pickleable.User'> - no mapper()", pickle.loads, u1_pickled, ) def test_no_instrumentation(self): users = self.tables.users mapper(User, users) u1 = User(name="ed") u1_pickled = pickle.dumps(u1, -1) clear_mappers() mapper(User, users) u1 = pickle.loads(u1_pickled) # this fails unless the InstanceState # compiles the mapper eq_(str(u1), "User(name='ed')") def test_class_deferred_cols(self): addresses, users = (self.tables.addresses, self.tables.users) mapper( User, users, properties={ "name": sa.orm.deferred(users.c.name), "addresses": relationship(Address, backref="user"), }, ) mapper( Address, addresses, properties={ "email_address": sa.orm.deferred(addresses.c.email_address) }, ) with fixture_session(expire_on_commit=False) as sess: u1 = User(name="ed") u1.addresses.append(Address(email_address="ed@bar.com")) sess.add(u1) sess.commit() with fixture_session() as sess: u1 = sess.query(User).get(u1.id) assert "name" not in u1.__dict__ assert "addresses" not in u1.__dict__ u2 = pickle.loads(pickle.dumps(u1)) with fixture_session() as sess2: sess2.add(u2) eq_(u2.name, "ed") eq_( u2, User( name="ed", addresses=[Address(email_address="ed@bar.com")] ), ) u2 = pickle.loads(pickle.dumps(u1)) with fixture_session() as sess2: u2 = sess2.merge(u2, load=False) eq_(u2.name, "ed") eq_( u2, User( name="ed", addresses=[Address(email_address="ed@bar.com")] ), ) def test_instance_lazy_relation_loaders(self): users, addresses = (self.tables.users, self.tables.addresses) mapper( User, users, properties={"addresses": relationship(Address, lazy="noload")}, ) mapper(Address, addresses) sess = fixture_session() u1 = User(name="ed", addresses=[Address(email_address="ed@bar.com")]) sess.add(u1) sess.commit() sess.close() u1 = sess.query(User).options(lazyload(User.addresses)).first() u2 = pickle.loads(pickle.dumps(u1)) sess = fixture_session() sess.add(u2) assert u2.addresses def test_lazyload_extra_criteria_not_supported(self): users, addresses = (self.tables.users, self.tables.addresses) mapper( User, users, properties={"addresses": relationship(Address)}, ) mapper(Address, addresses) sess = fixture_session() u1 = User( name="ed", addresses=[ Address(email_address="ed@bar.com"), Address(email_address="ed@wood.com"), ], ) sess.add(u1) sess.commit() sess.close() u1 = ( sess.query(User) .options( lazyload( User.addresses.and_(Address.email_address == "ed@bar.com") ) ) .first() ) with testing.expect_warnings( r"Can't reliably serialize a lazyload\(\) option" ): u2 = pickle.loads(pickle.dumps(u1)) eq_(len(u1.addresses), 1) sess = fixture_session() sess.add(u2) eq_(len(u2.addresses), 2) def test_invalidated_flag_pickle(self): users, addresses = (self.tables.users, self.tables.addresses) mapper( User, users, properties={"addresses": relationship(Address, lazy="noload")}, ) mapper(Address, addresses) u1 = User() u1.addresses.append(Address()) u2 = pickle.loads(pickle.dumps(u1)) u2.addresses.append(Address()) eq_(len(u2.addresses), 2) def test_invalidated_flag_deepcopy(self): users, addresses = (self.tables.users, self.tables.addresses) mapper( User, users, properties={"addresses": relationship(Address, lazy="noload")}, ) mapper(Address, addresses) u1 = User() u1.addresses.append(Address()) u2 = copy.deepcopy(u1) u2.addresses.append(Address()) eq_(len(u2.addresses), 2) @testing.requires.non_broken_pickle def test_instance_deferred_cols(self): users, addresses = (self.tables.users, self.tables.addresses) mapper( User, users, properties={"addresses": relationship(Address, backref="user")}, ) mapper(Address, addresses) with fixture_session(expire_on_commit=False) as sess: u1 = User(name="ed") u1.addresses.append(Address(email_address="ed@bar.com")) sess.add(u1) sess.commit() with fixture_session(expire_on_commit=False) as sess: u1 = ( sess.query(User) .options( sa.orm.defer("name"), sa.orm.defer("addresses.email_address"), ) .get(u1.id) ) assert "name" not in u1.__dict__ assert "addresses" not in u1.__dict__ u2 = pickle.loads(pickle.dumps(u1)) with fixture_session() as sess2: sess2.add(u2) eq_(u2.name, "ed") assert "addresses" not in u2.__dict__ ad = u2.addresses[0] assert "email_address" not in ad.__dict__ eq_(ad.email_address, "ed@bar.com") eq_( u2, User( name="ed", addresses=[Address(email_address="ed@bar.com")] ), ) u2 = pickle.loads(pickle.dumps(u1)) with fixture_session() as sess2: u2 = sess2.merge(u2, load=False) eq_(u2.name, "ed") assert "addresses" not in u2.__dict__ ad = u2.addresses[0] # mapper options now transmit over merge(), # new as of 0.6, so email_address is deferred. assert "email_address" not in ad.__dict__ eq_(ad.email_address, "ed@bar.com") eq_( u2, User( name="ed", addresses=[Address(email_address="ed@bar.com")] ), ) def test_pickle_protocols(self): users, addresses = (self.tables.users, self.tables.addresses) mapper( User, users, properties={"addresses": relationship(Address, backref="user")}, ) mapper(Address, addresses) sess = fixture_session() u1 = User(name="ed") u1.addresses.append(Address(email_address="ed@bar.com")) sess.add(u1) sess.commit() u1 = sess.query(User).first() u1.addresses for loads, dumps in picklers(): u2 = loads(dumps(u1)) eq_(u1, u2) def test_09_pickle(self): users = self.tables.users mapper(User, users) sess = fixture_session() sess.add(User(id=1, name="ed")) sess.commit() sess.close() inst = User(id=1, name="ed") del inst._sa_instance_state state = sa_state.InstanceState.__new__(sa_state.InstanceState) state_09 = { "class_": User, "modified": False, "committed_state": {}, "instance": inst, "callables": {"name": state, "id": state}, "key": (User, (1,)), "expired": True, } manager = instrumentation._SerializeManager.__new__( instrumentation._SerializeManager ) manager.class_ = User state_09["manager"] = manager state.__setstate__(state_09) eq_(state.expired_attributes, {"name", "id"}) sess = fixture_session() sess.add(inst) eq_(inst.name, "ed") # test identity_token expansion eq_(sa.inspect(inst).key, (User, (1,), None)) def test_11_pickle(self): users = self.tables.users mapper(User, users) sess = fixture_session() u1 = User(id=1, name="ed") sess.add(u1) sess.commit() sess.close() manager = instrumentation._SerializeManager.__new__( instrumentation._SerializeManager ) manager.class_ = User state_11 = { "class_": User, "modified": False, "committed_state": {}, "instance": u1, "manager": manager, "key": (User, (1,)), "expired_attributes": set(), "expired": True, } state = sa_state.InstanceState.__new__(sa_state.InstanceState) state.__setstate__(state_11) eq_(state.identity_token, None) eq_(state.identity_key, (User, (1,), None)) def test_state_info_pickle(self): users = self.tables.users mapper(User, users) u1 = User(id=1, name="ed") sa.inspect(u1).info["some_key"] = "value" state_dict = sa.inspect(u1).__getstate__() state = sa_state.InstanceState.__new__(sa_state.InstanceState) state.__setstate__(state_dict) u2 = state.obj() eq_(sa.inspect(u2).info["some_key"], "value") @testing.requires.non_broken_pickle def test_unbound_options(self): sess, User, Address, Dingaling = self._option_test_fixture() for opt in [ sa.orm.joinedload(User.addresses), sa.orm.joinedload("addresses"), sa.orm.defer("name"), sa.orm.defer(User.name), sa.orm.joinedload("addresses").joinedload(Address.dingaling), ]: opt2 = pickle.loads(pickle.dumps(opt)) eq_(opt.path, opt2.path) u1 = sess.query(User).options(opt).first() pickle.loads(pickle.dumps(u1)) @testing.requires.non_broken_pickle def test_bound_options(self): sess, User, Address, Dingaling = self._option_test_fixture() for opt in [ sa.orm.Load(User).joinedload(User.addresses), sa.orm.Load(User).joinedload("addresses"), sa.orm.Load(User).defer("name"), sa.orm.Load(User).defer(User.name), sa.orm.Load(User) .joinedload("addresses") .joinedload(Address.dingaling), sa.orm.Load(User) .joinedload("addresses", innerjoin=True) .joinedload(Address.dingaling), ]: opt2 = pickle.loads(pickle.dumps(opt)) eq_(opt.path, opt2.path) eq_(opt.context.keys(), opt2.context.keys()) eq_(opt.local_opts, opt2.local_opts) u1 = sess.query(User).options(opt).first() pickle.loads(pickle.dumps(u1)) @testing.requires.non_broken_pickle def test_became_bound_options(self): sess, User, Address, Dingaling = self._option_test_fixture() for opt in [ sa.orm.joinedload(User.addresses), sa.orm.joinedload("addresses"), sa.orm.defer("name"), sa.orm.defer(User.name), sa.orm.joinedload("addresses").joinedload(Address.dingaling), ]: context = sess.query(User).options(opt)._compile_context() opt = [ v for v in context.attributes.values() if isinstance(v, sa.orm.Load) ][0] opt2 = pickle.loads(pickle.dumps(opt)) eq_(opt.path, opt2.path) eq_(opt.local_opts, opt2.local_opts) u1 = sess.query(User).options(opt).first() pickle.loads(pickle.dumps(u1)) def test_collection_setstate(self): """test a particular cycle that requires CollectionAdapter to not rely upon InstanceState to deserialize.""" m = MetaData() c1 = Table( "c1", m, Column("parent_id", String, ForeignKey("p.id"), primary_key=True), ) c2 = Table( "c2", m, Column("parent_id", String, ForeignKey("p.id"), primary_key=True), ) p = Table("p", m, Column("id", String, primary_key=True)) mapper( Parent, p, properties={ "children1": relationship(Child1), "children2": relationship(Child2), }, ) mapper(Child1, c1) mapper(Child2, c2) obj = Parent() screen1 = Screen(obj) screen1.errors = [obj.children1, obj.children2] screen2 = Screen(Child2(), screen1) pickle.loads(pickle.dumps(screen2)) def test_exceptions(self): class Foo(object): pass users = self.tables.users mapper(User, users) for sa_exc in ( orm_exc.UnmappedInstanceError(Foo()), orm_exc.UnmappedClassError(Foo), orm_exc.ObjectDeletedError(attributes.instance_state(User())), ): for loads, dumps in picklers(): repickled = loads(dumps(sa_exc)) eq_(repickled.args[0], sa_exc.args[0]) def test_attribute_mapped_collection(self): users, addresses = self.tables.users, self.tables.addresses mapper( User, users, properties={ "addresses": relationship( Address, collection_class=attribute_mapped_collection( "email_address" ), ) }, ) mapper(Address, addresses) u1 = User() u1.addresses = {"email1": Address(email_address="email1")} for loads, dumps in picklers(): repickled = loads(dumps(u1)) eq_(u1.addresses, repickled.addresses) eq_(repickled.addresses["email1"], Address(email_address="email1")) def test_column_mapped_collection(self): users, addresses = self.tables.users, self.tables.addresses mapper( User, users, properties={ "addresses": relationship( Address, collection_class=column_mapped_collection( addresses.c.email_address ), ) }, ) mapper(Address, addresses) u1 = User() u1.addresses = { "email1": Address(email_address="email1"), "email2": Address(email_address="email2"), } for loads, dumps in picklers(): repickled = loads(dumps(u1)) eq_(u1.addresses, repickled.addresses) eq_(repickled.addresses["email1"], Address(email_address="email1")) def test_composite_column_mapped_collection(self): users, addresses = self.tables.users, self.tables.addresses mapper( User, users, properties={ "addresses": relationship( Address, collection_class=column_mapped_collection( [addresses.c.id, addresses.c.email_address] ), ) }, ) mapper(Address, addresses) u1 = User() u1.addresses = { (1, "email1"): Address(id=1, email_address="email1"), (2, "email2"): Address(id=2, email_address="email2"), } for loads, dumps in picklers(): repickled = loads(dumps(u1)) eq_(u1.addresses, repickled.addresses) eq_( repickled.addresses[(1, "email1")], Address(id=1, email_address="email1"), ) class OptionsTest(_Polymorphic): @testing.requires.non_broken_pickle def test_options_of_type(self): with_poly = with_polymorphic(Person, [Engineer, Manager], flat=True) for opt, serialized in [ ( sa.orm.joinedload(Company.employees.of_type(Engineer)), [(Company, "employees", Engineer)], ), ( sa.orm.joinedload(Company.employees.of_type(with_poly)), [(Company, "employees", None)], ), ]: opt2 = pickle.loads(pickle.dumps(opt)) eq_(opt.__getstate__()["path"], serialized) eq_(opt2.__getstate__()["path"], serialized) def test_load(self): s = fixture_session() with_poly = with_polymorphic(Person, [Engineer, Manager], flat=True) emp = ( s.query(Company) .options(subqueryload(Company.employees.of_type(with_poly))) .first() ) pickle.loads(pickle.dumps(emp)) class PolymorphicDeferredTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(30)), Column("type", String(30)), ) Table( "email_users", metadata, Column("id", Integer, ForeignKey("users.id"), primary_key=True), Column("email_address", String(30)), ) def test_polymorphic_deferred(self): email_users, users = (self.tables.email_users, self.tables.users) mapper( User, users, polymorphic_identity="user", polymorphic_on=users.c.type, ) mapper( EmailUser, email_users, inherits=User, polymorphic_identity="emailuser", ) eu = EmailUser(name="user1", email_address="foo@bar.com") with fixture_session() as sess: sess.add(eu) sess.commit() with fixture_session() as sess: eu = sess.query(User).first() eu2 = pickle.loads(pickle.dumps(eu)) sess2 = fixture_session() sess2.add(eu2) assert "email_address" not in eu2.__dict__ eq_(eu2.email_address, "foo@bar.com") class TupleLabelTest(_fixtures.FixtureTest): @classmethod def setup_classes(cls): pass @classmethod def setup_mappers(cls): users, addresses, orders = ( cls.tables.users, cls.tables.addresses, cls.tables.orders, ) mapper( User, users, properties={ "addresses": relationship( Address, backref="user", order_by=addresses.c.id ), # o2m, m2o "orders": relationship( Order, backref="user", order_by=orders.c.id ), }, ) mapper(Address, addresses) mapper( Order, orders, properties={"address": relationship(Address)} ) # m2o def test_tuple_labeling(self): sess = fixture_session() # test pickle + all the protocols ! for pickled in False, -1, 0, 1, 2: for row in sess.query(User, Address).join(User.addresses).all(): if pickled is not False: row = pickle.loads(pickle.dumps(row, pickled)) eq_(list(row._fields), ["User", "Address"]) eq_(row.User, row[0]) eq_(row.Address, row[1]) for row in sess.query(User.name, User.id.label("foobar")): if pickled is not False: row = pickle.loads(pickle.dumps(row, pickled)) eq_(list(row._fields), ["name", "foobar"]) eq_(row.name, row[0]) eq_(row.foobar, row[1]) for row in sess.query(User).with_entities( User.name, User.id.label("foobar") ): if pickled is not False: row = pickle.loads(pickle.dumps(row, pickled)) eq_(list(row._fields), ["name", "foobar"]) eq_(row.name, row[0]) eq_(row.foobar, row[1]) oalias = aliased(Order) for row in ( sess.query(User, oalias) .join(User.orders.of_type(oalias)) .all() ): if pickled is not False: row = pickle.loads(pickle.dumps(row, pickled)) eq_(list(row._fields), ["User"]) eq_(row.User, row[0]) oalias = aliased(Order, name="orders") for row in ( sess.query(User, oalias).join(oalias, User.orders).all() ): if pickled is not False: row = pickle.loads(pickle.dumps(row, pickled)) eq_(list(row._fields), ["User", "orders"]) eq_(row.User, row[0]) eq_(row.orders, row[1]) for row in sess.query(User.name + "hoho", User.name): eq_(list(row._fields), ["name"]) eq_(row[0], row.name + "hoho") if pickled is not False: ret = sess.query(User, Address).join(User.addresses).all() pickle.loads(pickle.dumps(ret, pickled)) class CustomSetupTeardownTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(30), nullable=False), test_needs_acid=True, test_needs_fk=True, ) Table( "addresses", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("user_id", None, ForeignKey("users.id")), Column("email_address", String(50), nullable=False), test_needs_acid=True, test_needs_fk=True, ) def test_rebuild_state(self): """not much of a 'test', but illustrate how to remove instance-level state before pickling. """ users = self.tables.users mapper(User, users) u1 = User() attributes.manager_of_class(User).teardown_instance(u1) assert not u1.__dict__ u2 = pickle.loads(pickle.dumps(u1)) attributes.manager_of_class(User).setup_instance(u2) assert attributes.instance_state(u2)
fintech-circle/edx-platform
refs/heads/master
openedx/core/djangoapps/profile_images/views.py
6
""" This module implements the upload and remove endpoints of the profile image api. """ import datetime import itertools import logging from contextlib import closing from django.utils.timezone import utc from django.utils.translation import ugettext as _ from rest_framework import permissions, status from rest_framework.parsers import FormParser, MultiPartParser from rest_framework.response import Response from rest_framework.views import APIView from openedx.core.djangoapps.user_api.accounts.image_helpers import get_profile_image_names, set_has_profile_image from openedx.core.djangoapps.user_api.errors import UserNotFound from openedx.core.lib.api.authentication import ( OAuth2AuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser ) from openedx.core.lib.api.parsers import TypedFileUploadParser from openedx.core.lib.api.permissions import IsUserInUrl from openedx.core.lib.api.view_utils import DeveloperErrorViewMixin from .exceptions import ImageValidationError from .images import IMAGE_TYPES, create_profile_images, remove_profile_images, validate_uploaded_image log = logging.getLogger(__name__) LOG_MESSAGE_CREATE = 'Generated and uploaded images %(image_names)s for user %(user_id)s' LOG_MESSAGE_DELETE = 'Deleted images %(image_names)s for user %(user_id)s' def _make_upload_dt(): """ Generate a server-side timestamp for the upload. This is in a separate function so its behavior can be overridden in tests. """ return datetime.datetime.utcnow().replace(tzinfo=utc) class ProfileImageView(DeveloperErrorViewMixin, APIView): """ **Use Cases** Add or remove profile images associated with user accounts. The requesting user must be signed in. Users can only add profile images to their own account. Users with staff access can remove profile images for other user accounts. All other users can remove only their own profile images. **Example Requests** POST /api/user/v1/accounts/{username}/image DELETE /api/user/v1/accounts/{username}/image **Example POST Responses** When the requesting user attempts to upload an image for their own account, the request returns one of the following responses: * If the upload could not be performed, the request returns an HTTP 400 "Bad Request" response with information about why the request failed. * If the upload is successful, the request returns an HTTP 204 "No Content" response with no additional content. If the requesting user tries to upload an image for a different user, the request returns one of the following responses: * If no user matches the "username" parameter, the request returns an HTTP 404 "Not Found" response. * If the user whose profile image is being uploaded exists, but the requesting user does not have staff access, the request returns an HTTP 404 "Not Found" response. * If the specified user exists, and the requesting user has staff access, the request returns an HTTP 403 "Forbidden" response. **Example DELETE Responses** When the requesting user attempts to remove the profile image for their own account, the request returns one of the following responses: * If the image could not be removed, the request returns an HTTP 400 "Bad Request" response with information about why the request failed. * If the request successfully removes the image, the request returns an HTTP 204 "No Content" response with no additional content. When the requesting user tries to remove the profile image for a different user, the view will return one of the following responses: * If the requesting user has staff access, and the "username" parameter matches a user, the profile image for the specified user is deleted, and the request returns an HTTP 204 "No Content" response with no additional content. * If the requesting user has staff access, but no user is matched by the "username" parameter, the request returns an HTTP 404 "Not Found" response. * If the requesting user does not have staff access, the request returns an HTTP 404 "Not Found" response, regardless of whether the user exists or not. """ parser_classes = (MultiPartParser, FormParser, TypedFileUploadParser) authentication_classes = (OAuth2AuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser) permission_classes = (permissions.IsAuthenticated, IsUserInUrl) upload_media_types = set(itertools.chain(*(image_type.mimetypes for image_type in IMAGE_TYPES.values()))) def post(self, request, username): """ POST /api/user/v1/accounts/{username}/image """ # validate request: # verify that the user's # ensure any file was sent if 'file' not in request.FILES: return Response( { "developer_message": u"No file provided for profile image", "user_message": _(u"No file provided for profile image"), }, status=status.HTTP_400_BAD_REQUEST ) # process the upload. uploaded_file = request.FILES['file'] # no matter what happens, delete the temporary file when we're done with closing(uploaded_file): # image file validation. try: validate_uploaded_image(uploaded_file) except ImageValidationError as error: return Response( {"developer_message": error.message, "user_message": error.user_message}, status=status.HTTP_400_BAD_REQUEST, ) # generate profile pic and thumbnails and store them profile_image_names = get_profile_image_names(username) create_profile_images(uploaded_file, profile_image_names) # update the user account to reflect that a profile image is available. set_has_profile_image(username, True, _make_upload_dt()) log.info( LOG_MESSAGE_CREATE, {'image_names': profile_image_names.values(), 'user_id': request.user.id} ) # send client response. return Response(status=status.HTTP_204_NO_CONTENT) def delete(self, request, username): """ DELETE /api/user/v1/accounts/{username}/image """ try: # update the user account to reflect that the images were removed. set_has_profile_image(username, False) # remove physical files from storage. profile_image_names = get_profile_image_names(username) remove_profile_images(profile_image_names) log.info( LOG_MESSAGE_DELETE, {'image_names': profile_image_names.values(), 'user_id': request.user.id} ) except UserNotFound: return Response(status=status.HTTP_404_NOT_FOUND) # send client response. return Response(status=status.HTTP_204_NO_CONTENT) class ProfileImageUploadView(APIView): """ **DEPRECATION WARNING** /api/profile_images/v1/{username}/upload is deprecated. All requests should now be sent to /api/user/v1/accounts/{username}/image """ parser_classes = ProfileImageView.parser_classes authentication_classes = ProfileImageView.authentication_classes permission_classes = ProfileImageView.permission_classes def post(self, request, username): """ POST /api/profile_images/v1/{username}/upload """ return ProfileImageView().post(request, username) class ProfileImageRemoveView(APIView): """ **DEPRECATION WARNING** /api/profile_images/v1/{username}/remove is deprecated. This endpoint's POST is replaced by the DELETE method at /api/user/v1/accounts/{username}/image. """ authentication_classes = ProfileImageView.authentication_classes permission_classes = ProfileImageView.permission_classes def post(self, request, username): """ POST /api/profile_images/v1/{username}/remove """ return ProfileImageView().delete(request, username)
MilesDuronCIMAT/book_exercises
refs/heads/master
chapter_11/lists/urls.py
2
"""superlists URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from lists import views urlpatterns = [ #url(r'^admin/', admin.site.urls), url(r'^(\d+)/$', views.view_list, name='view_list'), url(r'^new$', views.new_list, name='new_list'), ]
antotodd/lab5
refs/heads/master
main/lib/flask_wtf/recaptcha/__init__.py
30
from . import fields from . import validators from . import widgets __all__ = fields.__all__ + validators.__all__ + widgets.__all__
woshilapin/cjdns
refs/heads/master
node_build/dependencies/libuv/build/gyp/test/ios/gyptest-extension.py
74
#!/usr/bin/env python # Copyright (c) 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that ios app extensions are built correctly. """ import TestGyp import TestMac import sys if sys.platform == 'darwin' and TestMac.Xcode.Version()>="0600": test = TestGyp.TestGyp(formats=['ninja', 'xcode']) test.run_gyp('extension.gyp', chdir='extension') test.build('extension.gyp', 'ExtensionContainer', chdir='extension') # Test that the extension is .appex test.built_file_must_exist( 'ExtensionContainer.app/PlugIns/ActionExtension.appex', chdir='extension') test.pass_test()
mozilla/bugbro
refs/heads/base
apps/examples/models.py
12133432
alxgu/ansible
refs/heads/devel
test/units/utils/test_unsafe_proxy.py
40
# -*- coding: utf-8 -*- # (c) 2018 Matt Martz <matt@sivel.net> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible.module_utils.six import PY3 from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeText, UnsafeProxy, wrap_var def test_UnsafeProxy(): assert isinstance(UnsafeProxy({}), dict) assert not isinstance(UnsafeProxy({}), AnsibleUnsafe) assert isinstance(UnsafeProxy('foo'), AnsibleUnsafeText) def test_wrap_var_string(): assert isinstance(wrap_var('foo'), AnsibleUnsafeText) assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText) if PY3: assert isinstance(wrap_var(b'foo'), type(b'')) assert not isinstance(wrap_var(b'foo'), AnsibleUnsafe) else: assert isinstance(wrap_var(b'foo'), AnsibleUnsafeText) def test_wrap_var_dict(): assert isinstance(wrap_var(dict(foo='bar')), dict) assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe) assert isinstance(wrap_var(dict(foo='bar'))['foo'], AnsibleUnsafeText) def test_wrap_var_dict_None(): assert wrap_var(dict(foo=None))['foo'] is None assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe) def test_wrap_var_list(): assert isinstance(wrap_var(['foo']), list) assert not isinstance(wrap_var(['foo']), AnsibleUnsafe) assert isinstance(wrap_var(['foo'])[0], AnsibleUnsafeText) def test_wrap_var_list_None(): assert wrap_var([None])[0] is None assert not isinstance(wrap_var([None])[0], AnsibleUnsafe) def test_wrap_var_set(): assert isinstance(wrap_var(set(['foo'])), set) assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe) for item in wrap_var(set(['foo'])): assert isinstance(item, AnsibleUnsafeText) def test_wrap_var_set_None(): for item in wrap_var(set([None])): assert item is None assert not isinstance(item, AnsibleUnsafe) def test_wrap_var_tuple(): assert isinstance(wrap_var(('foo',)), tuple) assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe) assert isinstance(wrap_var(('foo',))[0], type('')) assert not isinstance(wrap_var(('foo',))[0], AnsibleUnsafe) def test_wrap_var_None(): assert wrap_var(None) is None assert not isinstance(wrap_var(None), AnsibleUnsafe) def test_wrap_var_unsafe(): assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText) def test_AnsibleUnsafeText(): assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
Mattie432/deluge-rbb
refs/heads/master
browsebutton/gtkui.py
1
# # gtkui.py # # Copyright (C) 2014 dredkin <dmitry.redkin@gmail.com> # Basic plugin template created by: # Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com> # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2009 Damien Churchill <damoxc@gmail.com> # # Deluge is free software. # # You may 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. # # deluge 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 deluge. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the OpenSSL # library. # You must obey the GNU General Public License in all respects for all of # the code used other than OpenSSL. If you modify file(s) with this # exception, you may extend this exception to your version of the file(s), # but you are not obligated to do so. If you do not wish to do so, delete # this exception statement from your version. If you delete this exception # statement from all source files in the program, then also delete it here. # import gtk from deluge.log import LOG as log from deluge.ui.client import client from deluge.plugins.pluginbase import GtkPluginBase import deluge.component as component import deluge.common importError = None try: import pkg_resources import common except: importError = "Install package setuptools to run this plugin!" def findwidget(container, name): if hasattr(container, 'get_children'): ch = container.get_children() for widget in ch: if widget.get_name() == name: return widget ret = findwidget(widget, name) if ret is not None: return ret return None def showMessage(parent, message): if parent is None: parent = component.get("MainWindow").window md = gtk.MessageDialog(parent, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, 'Error starting plugin: '+ message) md.format_secondary_text('Remote browse button plugin'); md.run() md.destroy() def caseInsensitive(key): return key.lower() class BrowseDialog: def __init__(self, path, recent, parent, RootDirectory, RootDirectoryDisableTraverse): self.selectedfolder = path self.builder = gtk.Builder() self.builder.add_from_file(common.get_resource('folder_browse_dialog.glade')) self.dialog = self.builder.get_object("browse_folders_dialog") self.dialog.set_transient_for(parent) self.recentliststore = gtk.ListStore(str) self.label = self.builder.get_object("selected_folder") self.label.set_model(self.recentliststore) cell = gtk.CellRendererText() self.label.pack_start(cell, True) self.label.add_attribute(cell, "text", 0) self.handler_id = self.label.connect("changed", self.recent_chosed) self.liststore = gtk.ListStore(gtk.gdk.Pixbuf, str) self.iconview = self.builder.get_object("iconview1") self.iconview.set_model(self.liststore) self.iconview.set_pixbuf_column(0) self.iconview.set_text_column(1) self.iconview.set_item_width(300) self.iconview.connect("item-activated", self.subfolder_activated) self.refillList("") self.recent = recent self.RootDirectory = RootDirectory self.RootDirectoryDisableTraverse = RootDirectoryDisableTraverse def refillList(self, subfolder): client.browsebutton.get_folder_list(self.selectedfolder, subfolder).addCallback(self.get_folder_list_callback) def get_folder_list_callback(self, results): if results[3]: showMessage(None, results[3]) return if self.RootDirectoryDisableTraverse: if self.RootDirectory and not results[0].startswith(self.RootDirectory): log.debug("Browse Folder: disable=" + str(self.RootDirectoryDisableTraverse) + " matched start with rootDir '" + results[0] + "'") return self.liststore.clear() self.selectedfolder = results[0] log.debug("RBB:callback selectedfolder="+self.selectedfolder) self.label.handler_block(self.handler_id) self.recentliststore.clear() for folder in self.recent: self.recentliststore.append([folder]) self.recentliststore.prepend([self.selectedfolder]) self.label.set_active(0) self.label.handler_unblock(self.handler_id) if not results[1]: pixbuf = gtk.icon_theme_get_default().load_icon("go-up", 24, 0) self.liststore.append([pixbuf, ".."]) subfolders = [] for folder in results[2]: subfolders.append(folder) subfolders.sort(key=caseInsensitive) for folder in subfolders: pixbuf = gtk.icon_theme_get_default().load_icon("folder", 24, 0) self.liststore.append([pixbuf, folder]) #self.iconview.set_item_width(-1) def subfolder_activated(self, widget, path): subfolder = self.liststore.get_value(self.liststore.get_iter(path),1) self.refillList(subfolder) def recent_chosed(self, combobox): model = combobox.get_model() index = combobox.get_active() if index != None: self.selectedfolder = str(model[index][0]) self.refillList("") class GtkUI(GtkPluginBase): error = None buttons = None addDialog = None mainWindow = None recent = [] def str2bool(self,v): return v.lower() in ("yes", "true", "t", "1") def enable(self): self.error = importError if self.error is None: self.initializeGUI() self.handleError() def disable(self): self.error = None component.get("Preferences").remove_page("Browse Button") component.get("PluginManager").deregister_hook("on_apply_prefs", self.on_apply_prefs) component.get("PluginManager").deregister_hook("on_show_prefs", self.on_show_prefs) for name in self.buttons.keys() : self.deleteButton(self.buttons[name]['widget']) self.buttons[name]['widget'] = None self.handleError() def handleError(self): if self.error is not None: showMessage(None, self.error) self.error = None def on_apply_prefs(self): config = { "RootDirPath":self.glade.get_widget("RootDir_Path").get_text().rstrip('\\').rstrip('/'), "DisableTraversal":str(self.glade.get_widget("RootDir_DisableTraversal").get_active()) } client.browsebutton.set_config(config) self.load_RootDirectory() def on_show_prefs(self): client.browsebutton.get_config().addCallback(self.cb_get_config) def cb_get_config(self, config): """callback for on show_prefs""" self.glade.get_widget("RootDir_Path").set_text(config["RootDirPath"]) self.glade.get_widget("RootDir_DisableTraversal").set_active(self.str2bool(config["DisableTraversal"])) def browseClicked(something): self.chooseFolder(self.glade.get_widget("RootDir_Path"), None) self.glade.get_widget("RootDir_Browse").connect("clicked", browseClicked) def save_recent(self): config = { "recent": tuple(self.recent) } client.browsebutton.set_config(config) def load_recent(self): client.browsebutton.get_config().addCallback(self.initialize_recent) def initialize_recent(self, config): """callback for load_recent""" self.recent = [] if "recent" in config: self.recent = list(config["recent"]) def load_RootDirectory(self): client.browsebutton.get_config().addCallback(self.initialize_RootDirectory) def initialize_RootDirectory(self, config): """callback for load_RootDirectory""" self.RootDirectory = "" if "RootDirPath" in config: self.RootDirectory = config["RootDirPath"] self.RootDirectoryDisableTraverse = False if "DisableTraversal" in config: self.RootDirectoryDisableTraverse = self.str2bool(config["DisableTraversal"]) def initializeGUI(self): self.glade = gtk.glade.XML(common.get_resource("config.glade")) self.load_recent() self.load_RootDirectory() component.get("Preferences").add_page("Browse Button", self.glade.get_widget("prefs_box")) component.get("PluginManager").register_hook("on_apply_prefs", self.on_apply_prefs) component.get("PluginManager").register_hook("on_show_prefs", self.on_show_prefs) self.buttons = { 'store' : { 'id': 'entry_download_path' , 'editbox': None, 'widget': None , 'window': None}, \ 'completed' : { 'id' : 'entry_move_completed_path' , 'editbox': None, 'widget': None , 'window': None}, \ 'completed_tab' : { 'id' : 'entry_move_completed' , 'editbox': None, 'widget': None , 'window': None} } self.makeButtons() self.addMoveMenu() self.handleError() def addMoveMenu(self): global menu torrentmenu = component.get("MenuBar").torrentmenu menu = gtk.ImageMenuItem(gtk.STOCK_SAVE_AS, 'Move Storage Advanced') menu.set_label("Move Storage") menu.show() menu.connect("activate", self.on_menu_activated, None) count = 0 #Remove the original move button for item in torrentmenu.get_children(): count = count + 1 if item.get_name() == "menuitem_move": torrentmenu.remove(item) break #Insert into original "move" position torrentmenu.insert(menu,count) def on_menu_activated(self, widget=None, data=None): client.core.get_torrent_status(component.get("TorrentView").get_selected_torrent(), ["save_path"]).addCallback(self.show_move_storage_dialog) def show_move_storage_dialog(self, status): glade = gtk.glade.XML(common.get_resource("myMove_storage_dialog.glade")) self.move_storage_dialog = glade.get_widget("move_storage_dialog") self.move_storage_dialog.set_transient_for(component.get("MainWindow").window) self.move_storage_dialog_entry = glade.get_widget("entry_destination") self.move_storage_browse_button = glade.get_widget("browse") self.move_storage_entry_destination = glade.get_widget("entry_destination") self.move_storage_dialog_entry.set_text(status["save_path"]) def on_dialog_response_event(widget, response_id): def on_core_result(result): # Delete references del self.move_storage_dialog del self.move_storage_dialog_entry if response_id == gtk.RESPONSE_OK: log.debug("Moving torrents to %s", self.move_storage_dialog_entry.get_text()) path = self.move_storage_dialog_entry.get_text() client.core.move_storage( component.get("TorrentView").get_selected_torrents(), path ).addCallback(on_core_result) self.move_storage_dialog.hide() def browseClicked(something): self.chooseFolder(self.move_storage_entry_destination, None) self.move_storage_dialog.connect("response", on_dialog_response_event) self.move_storage_browse_button.connect("clicked", browseClicked) self.move_storage_dialog.show() def addButton(self, editbox, onClickEvent): """Adds a Button to the editbox inside hbox container.""" if editbox is None: return None hbox = editbox.get_parent() if hbox is None: self.error = "hbox not found!" return None if hbox is None: return None image = gtk.Image() image.set_from_stock(gtk.STOCK_DIRECTORY, gtk.ICON_SIZE_BUTTON) button = gtk.Button() button.set_image(image) button.set_label("Browse..") button.set_size_request(50,-1) hbox.pack_end(button) button.show() button.connect("clicked", onClickEvent) return button def deleteButton(self, button): if button is not None: if button.parent is None: return None button.parent.remove(button) return True def findAddDialog(self): if self.addDialog is None: dialog = component.get("AddTorrentDialog") if dialog is None: self.error = "AddTorrentDialog not found!" return False self.addDialog = dialog.dialog return self.addDialog is not None def findMainWindow(self): if self.mainWindow is None: comp = component.get("MainWindow") if comp is None: self.error = "MainWindow not found!" return False self.mainWindow = comp.window return self.mainWindow is not None def findEditor(self, dialog, editbox, id): if dialog is None: return None if editbox is None: editbox = findwidget(dialog, id) if editbox is None: self.error = id + " not found!" return editbox def makeButtons(self): if not self.findMainWindow(): self.handleError() return False if not self.findAddDialog(): self.handleError() return False self.buttons['store']['window'] = self.addDialog self.buttons['completed']['window'] = self.addDialog self.buttons['completed_tab']['window'] = self.mainWindow for name in self.buttons.keys() : self.buttons[name]['editbox'] = self.findEditor(self.buttons[name]['window'], self.buttons[name]['editbox'], self.buttons[name]['id']) self.buttons[name]['widget'] = self.addButton(self.buttons[name]['editbox'], self.on_browse_button_clicked) def chooseFolder(self, editbox, parent): if self.RootDirectory: startDir = self.RootDirectory else: startDir = editbox.get_text() dialog = BrowseDialog(startDir, self.recent, parent, self.RootDirectory, self.RootDirectoryDisableTraverse) id = dialog.dialog.run() if id > 0: log.debug("RBB:folder chosen:"+dialog.selectedfolder) editbox.set_text(dialog.selectedfolder) log.debug("RBB:New content of "+editbox.get_name()+":"+editbox.get_text()) if self.recent.count(dialog.selectedfolder) > 0: self.recent.remove(dialog.selectedfolder) self.recent.insert(0, dialog.selectedfolder) while len(self.recent) > 10: self.recent.pop() self.save_recent() dialog.dialog.destroy() def on_browse_button_clicked(self, widget): for name in self.buttons.keys() : if widget == self.buttons[name]['widget']: return self.chooseFolder(self.buttons[name]['editbox'], self.buttons[name]['window'])
choperlizer/Dojima
refs/heads/master
dojima/model/ot/__init__.py
1
# Dojima, a markets client. # Copyright (C) 2012 Emery Hemingway # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import otapi from PyQt4 import QtCore class OTBaseModel(QtCore.QAbstractTableModel): COLUMNS = 2 ID, NAME = list(range(COLUMNS)) def columnCount(self, parent=None): if parent and parent.isValid(): return 0 return self.COLUMNS def parent(self): return QtCore.QModelIndex() def flags(self, index): flags = super(OTBaseModel, self).flags(index) if index.column == self.NAME: flags |= QtCore.Qt.ItemIsEditable return flags
mikewied/perfrunner
refs/heads/master
perfrunner/workloads/revAB/graph.py
7
import itertools from logger import logger from perfrunner.workloads.revAB.fittingCode import socialModels def generate_graph(users): logger.info('Generating graph') graph = socialModels.nearestNeighbor_mod(users, 0.90, 5) logger.info( 'Done: {} nodes, {} edges.' .format(graph.number_of_nodes(), graph.number_of_edges()) ) return graph class PersonIterator(object): def __init__(self, graph, graph_keys, start, step): self.graph = graph self.graph_keys = graph_keys self.start = start self.step = step @staticmethod def person_to_key(person): # Pad p to typical tel number length (12 chars). return u'{:012}'.format(person) @staticmethod def person_to_value(rng, person): # Should be same as key, but to speed up memory increase use a random # length between 12 and 400 chars. width = rng.randint(12, 400) return u'{:0{width}}'.format(person, width=width) def __iter__(self): for k in itertools.islice(self.graph_keys, self.start, None, self.step): yield k
Seanmcn/WineDB
refs/heads/master
wineDB/urls.py
1
"""djangoPoll URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url('', include('wine_db.urls', namespace="winedb")), url(r'^admin/', include(admin.site.urls)), ] # admin.site.site_header = 'Adminzzz'
mdaniel/intellij-community
refs/heads/master
python/testData/inspections/PyStringFormatInspection/NewStyleMappingKeyWithSubscriptionParenArg.py
29
"{foo[1]}".format(foo=(1, 2, 3)) "{foo[1]}".format(foo=({1: 1})) "{foo[1]}".format(foo=([1, 2, 3])) "{foo[a]}".format(foo=({"a": 1})) <warning descr="Too few arguments for format string">"{foo[3]}"</warning>.format(foo=(1, 2, 3)) <warning descr="Too few arguments for format string">"{foo[3]}"</warning>.format(foo=({1: 1})) <warning descr="Too few arguments for format string">"{foo[3]}"</warning>.format(foo=([1, 2, 3])) <warning descr="Too few arguments for format string">"{foo[b]}"</warning>.format(foo=({"a": 1}))
jk1/intellij-community
refs/heads/master
python/testData/completion/heavyStarPropagation/lib/_pkg0/_pkg0_0/_pkg0_0_1/_pkg0_0_1_0/_pkg0_0_1_0_0/_mod0_0_1_0_0_1.py
30
name0_0_1_0_0_1_0 = None name0_0_1_0_0_1_1 = None name0_0_1_0_0_1_2 = None name0_0_1_0_0_1_3 = None name0_0_1_0_0_1_4 = None
miho030/FoxVc
refs/heads/master
versions - 1.3.x/FoxVc Ver 1.3.0/Test Codes for Stabilize!/Code Backup.py
1
# +=======================================================================================+ # 사용자 시스템에 설치되어 있는 파이썬의 버전을 감지하고 각 버전에 최적화된 모듈 임포트함. # +=======================================================================================+ # 파이썬 버전에 따라 버전에 최적화된 모듈을 실행하는 부분 # sys모듈을 사용하여 설치된 파이썬 버전을 변수로 지정. # FoxVc을 실행하는 시스템에 파이썬 2버전 이상이 설치된경우. if FoxPyver[:1] == 2: print "[+] ", "You have Python2 !", "Start python 2 modules..\n" FoxVcpy2() else: # FoxVc을 실행하는 시스템에 파이썬 3버전 이상이 설치된경우. if FoxPyver[:1] == 3: print ("[+] ", "You have Python3 !", "Start python 3 modules..\n") FoxVcpy3() else: print (" ") print ("+==========================================================================+") print ("[ - Warning - ] Our FoxVc does not support less than the Python 2 version.") print ("[-] For smooth execution, please install Python version 2 or version 3.") print ("+==========================================================================+")
EducationForDevelopment/webapp
refs/heads/master
lib/werkzeug/http.py
317
# -*- coding: utf-8 -*- """ werkzeug.http ~~~~~~~~~~~~~ Werkzeug comes with a bunch of utilities that help Werkzeug to deal with HTTP data. Most of the classes and functions provided by this module are used by the wrappers, but they are useful on their own, too, especially if the response and request objects are not used. This covers some of the more HTTP centric features of WSGI, some other utilities such as cookie handling are documented in the `werkzeug.utils` module. :copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import re from time import time, gmtime try: from email.utils import parsedate_tz except ImportError: # pragma: no cover from email.Utils import parsedate_tz try: from urllib2 import parse_http_list as _parse_list_header except ImportError: # pragma: no cover from urllib.request import parse_http_list as _parse_list_header from datetime import datetime, timedelta from hashlib import md5 import base64 from werkzeug._internal import _cookie_quote, _make_cookie_domain, \ _cookie_parse_impl from werkzeug._compat import to_unicode, iteritems, text_type, \ string_types, try_coerce_native, to_bytes, PY2, \ integer_types # incorrect _cookie_charset = 'latin1' _accept_re = re.compile(r'([^\s;,]+)(?:[^,]*?;\s*q=(\d*(?:\.\d+)?))?') _token_chars = frozenset("!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" '^_`abcdefghijklmnopqrstuvwxyz|~') _etag_re = re.compile(r'([Ww]/)?(?:"(.*?)"|(.*?))(?:\s*,\s*|$)') _unsafe_header_chars = set('()<>@,;:\"/[]?={} \t') _quoted_string_re = r'"[^"\\]*(?:\\.[^"\\]*)*"' _option_header_piece_re = re.compile(r';\s*(%s|[^\s;=]+)\s*(?:=\s*(%s|[^;]+))?\s*' % (_quoted_string_re, _quoted_string_re)) _entity_headers = frozenset([ 'allow', 'content-encoding', 'content-language', 'content-length', 'content-location', 'content-md5', 'content-range', 'content-type', 'expires', 'last-modified' ]) _hop_by_hop_headers = frozenset([ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade' ]) HTTP_STATUS_CODES = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi Status', 226: 'IM Used', # see RFC 3229 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', # unused 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 418: 'I\'m a teapot', # see RFC 2324 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 426: 'Upgrade Required', 428: 'Precondition Required', # see RFC 6585 429: 'Too Many Requests', 431: 'Request Header Fields Too Large', 449: 'Retry With', # proprietary MS extension 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 507: 'Insufficient Storage', 510: 'Not Extended' } def wsgi_to_bytes(data): """coerce wsgi unicode represented bytes to real ones """ if isinstance(data, bytes): return data return data.encode('latin1') #XXX: utf8 fallback? def bytes_to_wsgi(data): assert isinstance(data, bytes), 'data must be bytes' if isinstance(data, str): return data else: return data.decode('latin1') def quote_header_value(value, extra_chars='', allow_token=True): """Quote a header value if necessary. .. versionadded:: 0.5 :param value: the value to quote. :param extra_chars: a list of extra characters to skip quoting. :param allow_token: if this is enabled token values are returned unchanged. """ if isinstance(value, bytes): value = bytes_to_wsgi(value) value = str(value) if allow_token: token_chars = _token_chars | set(extra_chars) if set(value).issubset(token_chars): return value return '"%s"' % value.replace('\\', '\\\\').replace('"', '\\"') def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. .. versionadded:: 0.5 :param value: the header value to unquote. """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] # if this is a filename and the starting characters look like # a UNC path, then just return the value without quotes. Using the # replace sequence below on a UNC path has the effect of turning # the leading double slash into a single slash and then # _fix_ie_filename() doesn't work correctly. See #458. if not is_filename or value[:2] != '\\\\': return value.replace('\\\\', '\\').replace('\\"', '"') return value def dump_options_header(header, options): """The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of options to append. """ segments = [] if header is not None: segments.append(header) for key, value in iteritems(options): if value is None: segments.append(key) else: segments.append('%s=%s' % (key, quote_header_value(value))) return '; '.join(segments) def dump_header(iterable, allow_token=True): """Dump an HTTP header again. This is the reversal of :func:`parse_list_header`, :func:`parse_set_header` and :func:`parse_dict_header`. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. >>> dump_header({'foo': 'bar baz'}) 'foo="bar baz"' >>> dump_header(('foo', 'bar baz')) 'foo, "bar baz"' :param iterable: the iterable or dict of values to quote. :param allow_token: if set to `False` tokens as values are disallowed. See :func:`quote_header_value` for more details. """ if isinstance(iterable, dict): items = [] for key, value in iteritems(iterable): if value is None: items.append(key) else: items.append('%s=%s' % ( key, quote_header_value(value, allow_token=allow_token) )) else: items = [quote_header_value(x, allow_token=allow_token) for x in iterable] return ', '.join(items) def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` """ result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result def parse_dict_header(value, cls=dict): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` arugment): >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. .. versionchanged:: 0.9 Added support for `cls` argument. :param value: a string with a dict header. :param cls: callable to use for storage of parsed results. :return: an instance of `cls` """ result = cls() if not isinstance(value, text_type): #XXX: validate value = bytes_to_wsgi(value) for item in _parse_list_header(value): if '=' not in item: result[item] = None continue name, value = item.split('=', 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result def parse_options_header(value): """Parse a ``Content-Type`` like header into a tuple with the content type and the options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should not be used to parse ``Cache-Control`` like headers that use a slightly different format. For these headers use the :func:`parse_dict_header` function. .. versionadded:: 0.5 :param value: the header to parse. :return: (str, options) """ def _tokenize(string): for match in _option_header_piece_re.finditer(string): key, value = match.groups() key = unquote_header_value(key) if value is not None: value = unquote_header_value(value, key == 'filename') yield key, value if not value: return '', {} parts = _tokenize(';' + value) name = next(parts)[0] extra = dict(parts) return name, extra def parse_accept_header(value, cls=None): """Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality with some additional accessor methods). The second parameter can be a subclass of :class:`Accept` that is created with the parsed values and returned. :param value: the accept header string to be parsed. :param cls: the wrapper class for the return value (can be :class:`Accept` or a subclass thereof) :return: an instance of `cls`. """ if cls is None: cls = Accept if not value: return cls(None) result = [] for match in _accept_re.finditer(value): quality = match.group(2) if not quality: quality = 1 else: quality = max(min(float(quality), 1), 0) result.append((match.group(1), quality)) return cls(result) def parse_cache_control_header(value, on_update=None, cls=None): """Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements. .. versionadded:: 0.5 The `cls` was added. If not specified an immutable :class:`~werkzeug.datastructures.RequestCacheControl` is returned. :param value: a cache control header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.CacheControl` object is changed. :param cls: the class for the returned object. By default :class:`~werkzeug.datastructures.RequestCacheControl` is used. :return: a `cls` object. """ if cls is None: cls = RequestCacheControl if not value: return cls(None, on_update) return cls(parse_dict_header(value), on_update) def parse_set_header(value, on_update=None): """Parse a set-like header and return a :class:`~werkzeug.datastructures.HeaderSet` object: >>> hs = parse_set_header('token, "quoted value"') The return value is an object that treats the items case-insensitively and keeps the order of the items: >>> 'TOKEN' in hs True >>> hs.index('quoted value') 1 >>> hs HeaderSet(['token', 'quoted value']) To create a header from the :class:`HeaderSet` again, use the :func:`dump_header` function. :param value: a set header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.HeaderSet` object is changed. :return: a :class:`~werkzeug.datastructures.HeaderSet` """ if not value: return HeaderSet(None, on_update) return HeaderSet(parse_list_header(value), on_update) def parse_authorization_header(value): """Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an :class:`~werkzeug.datastructures.Authorization` object. :param value: the authorization header to parse. :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`. """ if not value: return value = wsgi_to_bytes(value) try: auth_type, auth_info = value.split(None, 1) auth_type = auth_type.lower() except ValueError: return if auth_type == b'basic': try: username, password = base64.b64decode(auth_info).split(b':', 1) except Exception as e: return return Authorization('basic', {'username': bytes_to_wsgi(username), 'password': bytes_to_wsgi(password)}) elif auth_type == b'digest': auth_map = parse_dict_header(auth_info) for key in 'username', 'realm', 'nonce', 'uri', 'response': if not key in auth_map: return if 'qop' in auth_map: if not auth_map.get('nc') or not auth_map.get('cnonce'): return return Authorization('digest', auth_map) def parse_www_authenticate_header(value, on_update=None): """Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.WWWAuthenticate` object is changed. :return: a :class:`~werkzeug.datastructures.WWWAuthenticate` object. """ if not value: return WWWAuthenticate(on_update=on_update) try: auth_type, auth_info = value.split(None, 1) auth_type = auth_type.lower() except (ValueError, AttributeError): return WWWAuthenticate(value.strip().lower(), on_update=on_update) return WWWAuthenticate(auth_type, parse_dict_header(auth_info), on_update) def parse_if_range_header(value): """Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7 """ if not value: return IfRange() date = parse_date(value) if date is not None: return IfRange(date=date) # drop weakness information return IfRange(unquote_etag(value)[0]) def parse_range_header(value, make_inclusive=True): """Parses a range header into a :class:`~werkzeug.datastructures.Range` object. If the header is missing or malformed `None` is returned. `ranges` is a list of ``(start, stop)`` tuples where the ranges are non-inclusive. .. versionadded:: 0.7 """ if not value or '=' not in value: return None ranges = [] last_end = 0 units, rng = value.split('=', 1) units = units.strip().lower() for item in rng.split(','): item = item.strip() if '-' not in item: return None if item.startswith('-'): if last_end < 0: return None begin = int(item) end = None last_end = -1 elif '-' in item: begin, end = item.split('-', 1) begin = int(begin) if begin < last_end or last_end < 0: return None if end: end = int(end) + 1 if begin >= end: return None else: end = None last_end = end ranges.append((begin, end)) return Range(units, ranges) def parse_content_range_header(value, on_update=None): """Parses a range header into a :class:`~werkzeug.datastructures.ContentRange` object or `None` if parsing is not possible. .. versionadded:: 0.7 :param value: a content range header to be parsed. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.ContentRange` object is changed. """ if value is None: return None try: units, rangedef = (value or '').strip().split(None, 1) except ValueError: return None if '/' not in rangedef: return None rng, length = rangedef.split('/', 1) if length == '*': length = None elif length.isdigit(): length = int(length) else: return None if rng == '*': return ContentRange(units, None, None, length, on_update=on_update) elif '-' not in rng: return None start, stop = rng.split('-', 1) try: start = int(start) stop = int(stop) + 1 except ValueError: return None if is_byte_range_valid(start, stop, length): return ContentRange(units, start, stop, length, on_update=on_update) def quote_etag(etag, weak=False): """Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak". """ if '"' in etag: raise ValueError('invalid etag') etag = '"%s"' % etag if weak: etag = 'w/' + etag return etag def unquote_etag(etag): """Unquote a single etag: >>> unquote_etag('w/"bar"') ('bar', True) >>> unquote_etag('"bar"') ('bar', False) :param etag: the etag identifier to unquote. :return: a ``(etag, weak)`` tuple. """ if not etag: return None, None etag = etag.strip() weak = False if etag[:2] in ('w/', 'W/'): weak = True etag = etag[2:] if etag[:1] == etag[-1:] == '"': etag = etag[1:-1] return etag, weak def parse_etags(value): """Parse an etag header. :param value: the tag header to parse :return: an :class:`~werkzeug.datastructures.ETags` object. """ if not value: return ETags() strong = [] weak = [] end = len(value) pos = 0 while pos < end: match = _etag_re.match(value, pos) if match is None: break is_weak, quoted, raw = match.groups() if raw == '*': return ETags(star_tag=True) elif quoted: raw = quoted if is_weak: weak.append(raw) else: strong.append(raw) pos = match.end() return ETags(strong, weak) def generate_etag(data): """Generate an etag for some data.""" return md5(data).hexdigest() def parse_date(value): """Parse one of the following date formats into a datetime object: .. sourcecode:: text Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format If parsing fails the return value is `None`. :param value: a string with a supported date format. :return: a :class:`datetime.datetime` object. """ if value: t = parsedate_tz(value.strip()) if t is not None: try: year = t[0] # unfortunately that function does not tell us if two digit # years were part of the string, or if they were prefixed # with two zeroes. So what we do is to assume that 69-99 # refer to 1900, and everything below to 2000 if year >= 0 and year <= 68: year += 2000 elif year >= 69 and year <= 99: year += 1900 return datetime(*((year,) + t[1:7])) - \ timedelta(seconds=t[-1] or 0) except (ValueError, OverflowError): return None def _dump_date(d, delim): """Used for `http_date` and `cookie_date`.""" if d is None: d = gmtime() elif isinstance(d, datetime): d = d.utctimetuple() elif isinstance(d, (integer_types, float)): d = gmtime(d) return '%s, %02d%s%s%s%s %02d:%02d:%02d GMT' % ( ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[d.tm_wday], d.tm_mday, delim, ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')[d.tm_mon - 1], delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec ) def cookie_date(expires=None): """Formats the time to ensure compatibility with Netscape's cookie standard. Accepts a floating point number expressed in seconds since the epoch in, a datetime object or a timetuple. All times in UTC. The :func:`parse_date` function can be used to parse such a date. Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``. :param expires: If provided that date is used, otherwise the current. """ return _dump_date(expires, '-') def http_date(timestamp=None): """Formats the time to match the RFC1123 date format. Accepts a floating point number expressed in seconds since the epoch in, a datetime object or a timetuple. All times in UTC. The :func:`parse_date` function can be used to parse such a date. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``. :param timestamp: If provided that date is used, otherwise the current. """ return _dump_date(timestamp, ' ') def is_resource_modified(environ, etag=None, data=None, last_modified=None): """Convenience method for conditional requests. :param environ: the WSGI environment of the request to be checked. :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :param last_modified: an optional date of the last modification. :return: `True` if the resource was modified, otherwise `False`. """ if etag is None and data is not None: etag = generate_etag(data) elif data is not None: raise TypeError('both data and etag given') if environ['REQUEST_METHOD'] not in ('GET', 'HEAD'): return False unmodified = False if isinstance(last_modified, string_types): last_modified = parse_date(last_modified) # ensure that microsecond is zero because the HTTP spec does not transmit # that either and we might have some false positives. See issue #39 if last_modified is not None: last_modified = last_modified.replace(microsecond=0) modified_since = parse_date(environ.get('HTTP_IF_MODIFIED_SINCE')) if modified_since and last_modified and last_modified <= modified_since: unmodified = True if etag: if_none_match = parse_etags(environ.get('HTTP_IF_NONE_MATCH')) if if_none_match: unmodified = if_none_match.contains_raw(etag) return not unmodified def remove_entity_headers(headers, allowed=('expires', 'content-location')): """Remove all entity headers from a list or :class:`Headers` object. This operation works in-place. `Expires` and `Content-Location` headers are by default not removed. The reason for this is :rfc:`2616` section 10.3.5 which specifies some entity headers that should be sent. .. versionchanged:: 0.5 added `allowed` parameter. :param headers: a list or :class:`Headers` object. :param allowed: a list of headers that should still be allowed even though they are entity headers. """ allowed = set(x.lower() for x in allowed) headers[:] = [(key, value) for key, value in headers if not is_entity_header(key) or key.lower() in allowed] def remove_hop_by_hop_headers(headers): """Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or :class:`Headers` object. This operation works in-place. .. versionadded:: 0.5 :param headers: a list or :class:`Headers` object. """ headers[:] = [(key, value) for key, value in headers if not is_hop_by_hop_header(key)] def is_entity_header(header): """Check if a header is an entity header. .. versionadded:: 0.5 :param header: the header to test. :return: `True` if it's an entity header, `False` otherwise. """ return header.lower() in _entity_headers def is_hop_by_hop_header(header): """Check if a header is an HTTP/1.1 "Hop-by-Hop" header. .. versionadded:: 0.5 :param header: the header to test. :return: `True` if it's an entity header, `False` otherwise. """ return header.lower() in _hop_by_hop_headers def parse_cookie(header, charset='utf-8', errors='replace', cls=None): """Parse a cookie. Either from a string or WSGI environ. Per default encoding errors are ignored. If you want a different behavior you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a :exc:`HTTPUnicodeError` is raised. .. versionchanged:: 0.5 This function now returns a :class:`TypeConversionDict` instead of a regular dict. The `cls` parameter was added. :param header: the header to be used to parse the cookie. Alternatively this can be a WSGI environment. :param charset: the charset for the cookie values. :param errors: the error behavior for the charset decoding. :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`TypeConversionDict` is used. """ if isinstance(header, dict): header = header.get('HTTP_COOKIE', '') elif header is None: header = '' # If the value is an unicode string it's mangled through latin1. This # is done because on PEP 3333 on Python 3 all headers are assumed latin1 # which however is incorrect for cookies, which are sent in page encoding. # As a result we if isinstance(header, text_type): header = header.encode('latin1', 'replace') if cls is None: cls = TypeConversionDict def _parse_pairs(): for key, val in _cookie_parse_impl(header): key = to_unicode(key, charset, errors, allow_none_charset=True) val = to_unicode(val, charset, errors, allow_none_charset=True) yield try_coerce_native(key), val return cls(_parse_pairs()) def dump_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, charset='utf-8', sync_expires=True): """Creates a new Set-Cookie header without the ``Set-Cookie`` prefix The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too. On Python 3 the return value of this function will be a unicode string, on Python 2 it will be a native string. In both cases the return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. If a unicode string is returned it's tunneled through latin1 as required by PEP 3333. The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It's strongly recommended to not use non-ASCII values for the keys. :param max_age: should be a number of seconds, or `None` (default) if the cookie should last only as long as the client's browser session. Additionally `timedelta` objects are accepted, too. :param expires: should be a `datetime` object or unix timestamp. :param path: limits the cookie to a given path, per default it will span the whole domain. :param domain: Use this if you want to set a cross-domain cookie. For example, ``domain=".example.com"`` will set a cookie that is readable by the domain ``www.example.com``, ``foo.example.com`` etc. Otherwise, a cookie will only be readable by the domain that set it. :param secure: The cookie will only be available via HTTPS :param httponly: disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. :param charset: the encoding for unicode values. :param sync_expires: automatically set expires if max_age is defined but expires not. """ key = to_bytes(key, charset) value = to_bytes(value, charset) if path is not None: path = iri_to_uri(path, charset) domain = _make_cookie_domain(domain) if isinstance(max_age, timedelta): max_age = (max_age.days * 60 * 60 * 24) + max_age.seconds if expires is not None: if not isinstance(expires, string_types): expires = cookie_date(expires) elif max_age is not None and sync_expires: expires = to_bytes(cookie_date(time() + max_age)) buf = [key + b'=' + _cookie_quote(value)] # XXX: In theory all of these parameters that are not marked with `None` # should be quoted. Because stdlib did not quote it before I did not # want to introduce quoting there now. for k, v, q in ((b'Domain', domain, True), (b'Expires', expires, False,), (b'Max-Age', max_age, False), (b'Secure', secure, None), (b'HttpOnly', httponly, None), (b'Path', path, False)): if q is None: if v: buf.append(k) continue if v is None: continue tmp = bytearray(k) if not isinstance(v, (bytes, bytearray)): v = to_bytes(text_type(v), charset) if q: v = _cookie_quote(v) tmp += b'=' + v buf.append(bytes(tmp)) # The return value will be an incorrectly encoded latin1 header on # Python 3 for consistency with the headers object and a bytestring # on Python 2 because that's how the API makes more sense. rv = b'; '.join(buf) if not PY2: rv = rv.decode('latin1') return rv def is_byte_range_valid(start, stop, length): """Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7 """ if (start is None) != (stop is None): return False elif start is None: return length is None or length >= 0 elif length is None: return 0 <= start < stop elif start >= stop: return False return 0 <= start < length # circular dependency fun from werkzeug.datastructures import Accept, HeaderSet, ETags, Authorization, \ WWWAuthenticate, TypeConversionDict, IfRange, Range, ContentRange, \ RequestCacheControl # DEPRECATED # backwards compatible imports from werkzeug.datastructures import MIMEAccept, CharsetAccept, \ LanguageAccept, Headers from werkzeug.urls import iri_to_uri
zyguan/hdfs-raid
refs/heads/master
src/contrib/hod/hodlib/GridServices/__init__.py
182
#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. from mapred import MapReduce, MapReduceExternal from hdfs import Hdfs, HdfsExternal
catapult-project/catapult
refs/heads/master
third_party/gsutil/gslib/third_party/kms_apitools/cloudkms_v1_messages.py
5
"""Generated message classes for cloudkms version v1. Manages encryption for your cloud services the same way you do on-premises. You can generate, use, rotate, and destroy AES256 encryption keys. """ # NOTE: This file is autogenerated and should not be edited by hand. from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'cloudkms' class AuditConfig(_messages.Message): """Specifies the audit configuration for a service. The configuration determines which permission types are logged, and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each AuditConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service": "allServices" "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:foo@gmail.com" ] }, { "log_type": "DATA_WRITE", }, { "log_type": "ADMIN_READ", } ] }, { "service": "fooservice.googleapis.com" "audit_log_configs": [ { "log_type": "DATA_READ", }, { "log_type": "DATA_WRITE", "exempted_members": [ "user:bar@gmail.com" ] } ] } ] } For fooservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ logging. It also exempts foo@gmail.com from DATA_READ logging, and bar@gmail.com from DATA_WRITE logging. Fields: auditLogConfigs: The configuration for logging of each type of permission. Next ID: 4 exemptedMembers: A string attribute. service: Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. """ auditLogConfigs = _messages.MessageField('AuditLogConfig', 1, repeated=True) exemptedMembers = _messages.StringField(2, repeated=True) service = _messages.StringField(3) class AuditLogConfig(_messages.Message): """Provides the configuration for logging a type of permissions. Example: { "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:foo@gmail.com" ] }, { "log_type": "DATA_WRITE", } ] } This enables 'DATA_READ' and 'DATA_WRITE' logging, while exempting foo@gmail.com from DATA_READ logging. Enums: LogTypeValueValuesEnum: The log type that this config enables. Fields: exemptedMembers: Specifies the identities that do not cause logging for this type of permission. Follows the same format of Binding.members. logType: The log type that this config enables. """ class LogTypeValueValuesEnum(_messages.Enum): """The log type that this config enables. Values: LOG_TYPE_UNSPECIFIED: Default case. Should never be this. ADMIN_READ: Admin reads. Example: CloudIAM getIamPolicy DATA_WRITE: Data writes. Example: CloudSQL Users create DATA_READ: Data reads. Example: CloudSQL Users list """ LOG_TYPE_UNSPECIFIED = 0 ADMIN_READ = 1 DATA_WRITE = 2 DATA_READ = 3 exemptedMembers = _messages.StringField(1, repeated=True) logType = _messages.EnumField('LogTypeValueValuesEnum', 2) class Binding(_messages.Message): """Associates `members` with a `role`. Fields: condition: The condition that is associated with this binding. NOTE: an unsatisfied condition will not allow user access via current binding. Different bindings, including their conditions, are examined independently. This field is GOOGLE_INTERNAL. members: Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@gmail.com` or `joe@example.com`. * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other- app@appspot.gserviceaccount.com`. * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`. * `domain:{domain}`: A Google Apps domain name that represents all the users of that domain. For example, `google.com` or `example.com`. role: Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. Required """ condition = _messages.MessageField('Expr', 1) members = _messages.StringField(2, repeated=True) role = _messages.StringField(3) class CloudkmsProjectsLocationsGetRequest(_messages.Message): """A CloudkmsProjectsLocationsGetRequest object. Fields: name: Resource name for the location. """ name = _messages.StringField(1, required=True) class CloudkmsProjectsLocationsKeyRingsCreateRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCreateRequest object. Fields: keyRing: A KeyRing resource to be passed as the request body. keyRingId: Required. It must be unique within a location and match the regular expression `[a-zA-Z0-9_-]{1,63}` parent: Required. The resource name of the location associated with the KeyRings, in the format `projects/*/locations/*`. """ keyRing = _messages.MessageField('KeyRing', 1) keyRingId = _messages.StringField(2) parent = _messages.StringField(3, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysCreateRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysCreateRequest object. Fields: cryptoKey: A CryptoKey resource to be passed as the request body. cryptoKeyId: Required. It must be unique within a KeyRing and match the regular expression `[a-zA-Z0-9_-]{1,63}` parent: Required. The name of the KeyRing associated with the CryptoKeys. """ cryptoKey = _messages.MessageField('CryptoKey', 1) cryptoKeyId = _messages.StringField(2) parent = _messages.StringField(3, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsCreateRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsCreateRequest object. Fields: cryptoKeyVersion: A CryptoKeyVersion resource to be passed as the request body. parent: Required. The name of the CryptoKey associated with the CryptoKeyVersions. """ cryptoKeyVersion = _messages.MessageField('CryptoKeyVersion', 1) parent = _messages.StringField(2, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsDestroyRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsDestroyRequest object. Fields: destroyCryptoKeyVersionRequest: A DestroyCryptoKeyVersionRequest resource to be passed as the request body. name: The resource name of the CryptoKeyVersion to destroy. """ destroyCryptoKeyVersionRequest = _messages.MessageField('DestroyCryptoKeyVersionRequest', 1) name = _messages.StringField(2, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsGetRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsGetRequest object. Fields: name: The name of the CryptoKeyVersion to get. """ name = _messages.StringField(1, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsListRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsListRequest object. Fields: pageSize: Optional limit on the number of CryptoKeyVersions to include in the response. Further CryptoKeyVersions can subsequently be obtained by including the ListCryptoKeyVersionsResponse.next_page_token in a subsequent request. If unspecified, the server will pick an appropriate default. pageToken: Optional pagination token, returned earlier via ListCryptoKeyVersionsResponse.next_page_token. parent: Required. The resource name of the CryptoKey to list, in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*`. """ pageSize = _messages.IntegerField(1, variant=_messages.Variant.INT32) pageToken = _messages.StringField(2) parent = _messages.StringField(3, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsPatchRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsPatchRequest object. Fields: cryptoKeyVersion: A CryptoKeyVersion resource to be passed as the request body. name: Output only. The resource name for this CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*`. updateMask: Required list of fields to be updated in this request. """ cryptoKeyVersion = _messages.MessageField('CryptoKeyVersion', 1) name = _messages.StringField(2, required=True) updateMask = _messages.StringField(3) class CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsRestoreRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsRestoreRequest object. Fields: name: The resource name of the CryptoKeyVersion to restore. restoreCryptoKeyVersionRequest: A RestoreCryptoKeyVersionRequest resource to be passed as the request body. """ name = _messages.StringField(1, required=True) restoreCryptoKeyVersionRequest = _messages.MessageField('RestoreCryptoKeyVersionRequest', 2) class CloudkmsProjectsLocationsKeyRingsCryptoKeysDecryptRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysDecryptRequest object. Fields: decryptRequest: A DecryptRequest resource to be passed as the request body. name: Required. The resource name of the CryptoKey to use for decryption. The server will choose the appropriate version. """ decryptRequest = _messages.MessageField('DecryptRequest', 1) name = _messages.StringField(2, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysEncryptRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysEncryptRequest object. Fields: encryptRequest: A EncryptRequest resource to be passed as the request body. name: Required. The resource name of the CryptoKey or CryptoKeyVersion to use for encryption. If a CryptoKey is specified, the server will use its primary version. """ encryptRequest = _messages.MessageField('EncryptRequest', 1) name = _messages.StringField(2, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysGetIamPolicyRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysGetIamPolicyRequest object. Fields: resource: REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. """ resource = _messages.StringField(1, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysGetRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysGetRequest object. Fields: name: The name of the CryptoKey to get. """ name = _messages.StringField(1, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysListRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysListRequest object. Fields: pageSize: Optional limit on the number of CryptoKeys to include in the response. Further CryptoKeys can subsequently be obtained by including the ListCryptoKeysResponse.next_page_token in a subsequent request. If unspecified, the server will pick an appropriate default. pageToken: Optional pagination token, returned earlier via ListCryptoKeysResponse.next_page_token. parent: Required. The resource name of the KeyRing to list, in the format `projects/*/locations/*/keyRings/*`. """ pageSize = _messages.IntegerField(1, variant=_messages.Variant.INT32) pageToken = _messages.StringField(2) parent = _messages.StringField(3, required=True) class CloudkmsProjectsLocationsKeyRingsCryptoKeysPatchRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysPatchRequest object. Fields: cryptoKey: A CryptoKey resource to be passed as the request body. name: Output only. The resource name for this CryptoKey in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*`. updateMask: Required list of fields to be updated in this request. """ cryptoKey = _messages.MessageField('CryptoKey', 1) name = _messages.StringField(2, required=True) updateMask = _messages.StringField(3) class CloudkmsProjectsLocationsKeyRingsCryptoKeysSetIamPolicyRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysSetIamPolicyRequest object. Fields: resource: REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. setIamPolicyRequest: A SetIamPolicyRequest resource to be passed as the request body. """ resource = _messages.StringField(1, required=True) setIamPolicyRequest = _messages.MessageField('SetIamPolicyRequest', 2) class CloudkmsProjectsLocationsKeyRingsCryptoKeysTestIamPermissionsRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysTestIamPermissionsRequest object. Fields: resource: REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. testIamPermissionsRequest: A TestIamPermissionsRequest resource to be passed as the request body. """ resource = _messages.StringField(1, required=True) testIamPermissionsRequest = _messages.MessageField('TestIamPermissionsRequest', 2) class CloudkmsProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersionRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersionRequest object. Fields: name: The resource name of the CryptoKey to update. updateCryptoKeyPrimaryVersionRequest: A UpdateCryptoKeyPrimaryVersionRequest resource to be passed as the request body. """ name = _messages.StringField(1, required=True) updateCryptoKeyPrimaryVersionRequest = _messages.MessageField('UpdateCryptoKeyPrimaryVersionRequest', 2) class CloudkmsProjectsLocationsKeyRingsGetIamPolicyRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsGetIamPolicyRequest object. Fields: resource: REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. """ resource = _messages.StringField(1, required=True) class CloudkmsProjectsLocationsKeyRingsGetRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsGetRequest object. Fields: name: The name of the KeyRing to get. """ name = _messages.StringField(1, required=True) class CloudkmsProjectsLocationsKeyRingsListRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsListRequest object. Fields: pageSize: Optional limit on the number of KeyRings to include in the response. Further KeyRings can subsequently be obtained by including the ListKeyRingsResponse.next_page_token in a subsequent request. If unspecified, the server will pick an appropriate default. pageToken: Optional pagination token, returned earlier via ListKeyRingsResponse.next_page_token. parent: Required. The resource name of the location associated with the KeyRings, in the format `projects/*/locations/*`. """ pageSize = _messages.IntegerField(1, variant=_messages.Variant.INT32) pageToken = _messages.StringField(2) parent = _messages.StringField(3, required=True) class CloudkmsProjectsLocationsKeyRingsSetIamPolicyRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsSetIamPolicyRequest object. Fields: resource: REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. setIamPolicyRequest: A SetIamPolicyRequest resource to be passed as the request body. """ resource = _messages.StringField(1, required=True) setIamPolicyRequest = _messages.MessageField('SetIamPolicyRequest', 2) class CloudkmsProjectsLocationsKeyRingsTestIamPermissionsRequest(_messages.Message): """A CloudkmsProjectsLocationsKeyRingsTestIamPermissionsRequest object. Fields: resource: REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. testIamPermissionsRequest: A TestIamPermissionsRequest resource to be passed as the request body. """ resource = _messages.StringField(1, required=True) testIamPermissionsRequest = _messages.MessageField('TestIamPermissionsRequest', 2) class CloudkmsProjectsLocationsListRequest(_messages.Message): """A CloudkmsProjectsLocationsListRequest object. Fields: filter: The standard list filter. name: The resource that owns the locations collection, if applicable. pageSize: The standard list page size. pageToken: The standard list page token. """ filter = _messages.StringField(1) name = _messages.StringField(2, required=True) pageSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) pageToken = _messages.StringField(4) class CryptoKey(_messages.Message): """A CryptoKey represents a logical key that can be used for cryptographic operations. A CryptoKey is made up of one or more versions, which represent the actual key material used in cryptographic operations. Enums: PurposeValueValuesEnum: The immutable purpose of this CryptoKey. Currently, the only acceptable purpose is ENCRYPT_DECRYPT. Messages: LabelsValue: Labels with user defined metadata. Fields: createTime: Output only. The time at which this CryptoKey was created. labels: Labels with user defined metadata. name: Output only. The resource name for this CryptoKey in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*`. nextRotationTime: At next_rotation_time, the Key Management Service will automatically: 1. Create a new version of this CryptoKey. 2. Mark the new version as primary. Key rotations performed manually via CreateCryptoKeyVersion and UpdateCryptoKeyPrimaryVersion do not affect next_rotation_time. primary: Output only. A copy of the "primary" CryptoKeyVersion that will be used by Encrypt when this CryptoKey is given in EncryptRequest.name. The CryptoKey's primary version can be updated via UpdateCryptoKeyPrimaryVersion. purpose: The immutable purpose of this CryptoKey. Currently, the only acceptable purpose is ENCRYPT_DECRYPT. rotationPeriod: next_rotation_time will be advanced by this period when the service automatically rotates a key. Must be at least one day. If rotation_period is set, next_rotation_time must also be set. """ class PurposeValueValuesEnum(_messages.Enum): """The immutable purpose of this CryptoKey. Currently, the only acceptable purpose is ENCRYPT_DECRYPT. Values: CRYPTO_KEY_PURPOSE_UNSPECIFIED: Not specified. ENCRYPT_DECRYPT: CryptoKeys with this purpose may be used with Encrypt and Decrypt. """ CRYPTO_KEY_PURPOSE_UNSPECIFIED = 0 ENCRYPT_DECRYPT = 1 @encoding.MapUnrecognizedFields('additionalProperties') class LabelsValue(_messages.Message): """Labels with user defined metadata. Messages: AdditionalProperty: An additional property for a LabelsValue object. Fields: additionalProperties: Additional properties of type LabelsValue """ class AdditionalProperty(_messages.Message): """An additional property for a LabelsValue object. Fields: key: Name of the additional property. value: A string attribute. """ key = _messages.StringField(1) value = _messages.StringField(2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) createTime = _messages.StringField(1) labels = _messages.MessageField('LabelsValue', 2) name = _messages.StringField(3) nextRotationTime = _messages.StringField(4) primary = _messages.MessageField('CryptoKeyVersion', 5) purpose = _messages.EnumField('PurposeValueValuesEnum', 6) rotationPeriod = _messages.StringField(7) class CryptoKeyVersion(_messages.Message): """A CryptoKeyVersion represents an individual cryptographic key, and the associated key material. It can be used for cryptographic operations either directly, or via its parent CryptoKey, in which case the server will choose the appropriate version for the operation. For security reasons, the raw cryptographic key material represented by a CryptoKeyVersion can never be viewed or exported. It can only be used to encrypt or decrypt data when an authorized user or application invokes Cloud KMS. Enums: StateValueValuesEnum: The current state of the CryptoKeyVersion. Fields: createTime: Output only. The time at which this CryptoKeyVersion was created. destroyEventTime: Output only. The time this CryptoKeyVersion's key material was destroyed. Only present if state is DESTROYED. destroyTime: Output only. The time this CryptoKeyVersion's key material is scheduled for destruction. Only present if state is DESTROY_SCHEDULED. name: Output only. The resource name for this CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*`. state: The current state of the CryptoKeyVersion. """ class StateValueValuesEnum(_messages.Enum): """The current state of the CryptoKeyVersion. Values: CRYPTO_KEY_VERSION_STATE_UNSPECIFIED: Not specified. ENABLED: This version may be used in Encrypt and Decrypt requests. DISABLED: This version may not be used, but the key material is still available, and the version can be placed back into the ENABLED state. DESTROYED: This version is destroyed, and the key material is no longer stored. A version may not leave this state once entered. DESTROY_SCHEDULED: This version is scheduled for destruction, and will be destroyed soon. Call RestoreCryptoKeyVersion to put it back into the DISABLED state. """ CRYPTO_KEY_VERSION_STATE_UNSPECIFIED = 0 ENABLED = 1 DISABLED = 2 DESTROYED = 3 DESTROY_SCHEDULED = 4 createTime = _messages.StringField(1) destroyEventTime = _messages.StringField(2) destroyTime = _messages.StringField(3) name = _messages.StringField(4) state = _messages.EnumField('StateValueValuesEnum', 5) class DecryptRequest(_messages.Message): """Request message for KeyManagementService.Decrypt. Fields: additionalAuthenticatedData: Optional data that must match the data originally supplied in EncryptRequest.additional_authenticated_data. ciphertext: Required. The encrypted data originally returned in EncryptResponse.ciphertext. """ additionalAuthenticatedData = _messages.BytesField(1) ciphertext = _messages.BytesField(2) class DecryptResponse(_messages.Message): """Response message for KeyManagementService.Decrypt. Fields: plaintext: The decrypted data originally supplied in EncryptRequest.plaintext. """ plaintext = _messages.BytesField(1) class DestroyCryptoKeyVersionRequest(_messages.Message): """Request message for KeyManagementService.DestroyCryptoKeyVersion.""" class EncryptRequest(_messages.Message): """Request message for KeyManagementService.Encrypt. Fields: additionalAuthenticatedData: Optional data that, if specified, must also be provided during decryption through DecryptRequest.additional_authenticated_data. Must be no larger than 64KiB. plaintext: Required. The data to encrypt. Must be no larger than 64KiB. """ additionalAuthenticatedData = _messages.BytesField(1) plaintext = _messages.BytesField(2) class EncryptResponse(_messages.Message): """Response message for KeyManagementService.Encrypt. Fields: ciphertext: The encrypted data. name: The resource name of the CryptoKeyVersion used in encryption. """ ciphertext = _messages.BytesField(1) name = _messages.StringField(2) class Expr(_messages.Message): """Represents an expression text. Example: title: "User account presence" description: "Determines whether the request has a user account" expression: "size(request.user) > 0" Fields: description: An optional description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI. expression: Textual representation of an expression in Common Expression Language syntax. The application context of the containing message determines which well-known feature set of CEL is supported. location: An optional string indicating the location of the expression for error reporting, e.g. a file name and a position in the file. title: An optional title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs which allow to enter the expression. """ description = _messages.StringField(1) expression = _messages.StringField(2) location = _messages.StringField(3) title = _messages.StringField(4) class KeyRing(_messages.Message): """A KeyRing is a toplevel logical grouping of CryptoKeys. Fields: createTime: Output only. The time at which this KeyRing was created. name: Output only. The resource name for the KeyRing in the format `projects/*/locations/*/keyRings/*`. """ createTime = _messages.StringField(1) name = _messages.StringField(2) class ListCryptoKeyVersionsResponse(_messages.Message): """Response message for KeyManagementService.ListCryptoKeyVersions. Fields: cryptoKeyVersions: The list of CryptoKeyVersions. nextPageToken: A token to retrieve next page of results. Pass this value in ListCryptoKeyVersionsRequest.page_token to retrieve the next page of results. totalSize: The total number of CryptoKeyVersions that matched the query. """ cryptoKeyVersions = _messages.MessageField('CryptoKeyVersion', 1, repeated=True) nextPageToken = _messages.StringField(2) totalSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) class ListCryptoKeysResponse(_messages.Message): """Response message for KeyManagementService.ListCryptoKeys. Fields: cryptoKeys: The list of CryptoKeys. nextPageToken: A token to retrieve next page of results. Pass this value in ListCryptoKeysRequest.page_token to retrieve the next page of results. totalSize: The total number of CryptoKeys that matched the query. """ cryptoKeys = _messages.MessageField('CryptoKey', 1, repeated=True) nextPageToken = _messages.StringField(2) totalSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) class ListKeyRingsResponse(_messages.Message): """Response message for KeyManagementService.ListKeyRings. Fields: keyRings: The list of KeyRings. nextPageToken: A token to retrieve next page of results. Pass this value in ListKeyRingsRequest.page_token to retrieve the next page of results. totalSize: The total number of KeyRings that matched the query. """ keyRings = _messages.MessageField('KeyRing', 1, repeated=True) nextPageToken = _messages.StringField(2) totalSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) class ListLocationsResponse(_messages.Message): """The response message for Locations.ListLocations. Fields: locations: A list of locations that matches the specified filter in the request. nextPageToken: The standard List next-page token. """ locations = _messages.MessageField('Location', 1, repeated=True) nextPageToken = _messages.StringField(2) class Location(_messages.Message): """A resource that represents Google Cloud Platform location. Messages: LabelsValue: Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"} MetadataValue: Service-specific metadata. For example the available capacity at the given location. Fields: labels: Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"} locationId: The canonical id for this location. For example: `"us-east1"`. metadata: Service-specific metadata. For example the available capacity at the given location. name: Resource name for the location, which may vary between implementations. For example: `"projects/example-project/locations/us- east1"` """ @encoding.MapUnrecognizedFields('additionalProperties') class LabelsValue(_messages.Message): """Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"} Messages: AdditionalProperty: An additional property for a LabelsValue object. Fields: additionalProperties: Additional properties of type LabelsValue """ class AdditionalProperty(_messages.Message): """An additional property for a LabelsValue object. Fields: key: Name of the additional property. value: A string attribute. """ key = _messages.StringField(1) value = _messages.StringField(2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) @encoding.MapUnrecognizedFields('additionalProperties') class MetadataValue(_messages.Message): """Service-specific metadata. For example the available capacity at the given location. Messages: AdditionalProperty: An additional property for a MetadataValue object. Fields: additionalProperties: Properties of the object. Contains field @type with type URL. """ class AdditionalProperty(_messages.Message): """An additional property for a MetadataValue object. Fields: key: Name of the additional property. value: A extra_types.JsonValue attribute. """ key = _messages.StringField(1) value = _messages.MessageField('extra_types.JsonValue', 2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) labels = _messages.MessageField('LabelsValue', 1) locationId = _messages.StringField(2) metadata = _messages.MessageField('MetadataValue', 3) name = _messages.StringField(4) class Policy(_messages.Message): """Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. A `Policy` consists of a list of `bindings`. A `Binding` binds a list of `members` to a `role`, where the members can be user accounts, Google groups, Google domains, and service accounts. A `role` is a named list of permissions defined by IAM. **Example** { "bindings": [ { "role": "roles/owner", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-other- app@appspot.gserviceaccount.com", ] }, { "role": "roles/viewer", "members": ["user:sean@example.com"] } ] } For a description of IAM and its features, see the [IAM developer's guide](https://cloud.google.com/iam). Fields: auditConfigs: Specifies cloud audit logging configuration for this policy. bindings: Associates a list of `members` to a `role`. `bindings` with no members will result in an error. etag: `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy from overwriting each other. It is strongly suggested that systems make use of the `etag` in the read- modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected to put that etag in the request to `setIamPolicy` to ensure that their change will be applied to the same version of the policy. If no `etag` is provided in the call to `setIamPolicy`, then the existing policy is overwritten blindly. iamOwned: A boolean attribute. version: Version of the `Policy`. The default version is 0. """ auditConfigs = _messages.MessageField('AuditConfig', 1, repeated=True) bindings = _messages.MessageField('Binding', 2, repeated=True) etag = _messages.BytesField(3) iamOwned = _messages.BooleanField(4) version = _messages.IntegerField(5, variant=_messages.Variant.INT32) class RestoreCryptoKeyVersionRequest(_messages.Message): """Request message for KeyManagementService.RestoreCryptoKeyVersion.""" class SetIamPolicyRequest(_messages.Message): """Request message for `SetIamPolicy` method. Fields: policy: REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. updateMask: OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be modified. If no mask is provided, the following default mask is used: paths: "bindings, etag" This field is only used by Cloud IAM. """ policy = _messages.MessageField('Policy', 1) updateMask = _messages.StringField(2) class StandardQueryParameters(_messages.Message): """Query parameters accepted by all methods. Enums: FXgafvValueValuesEnum: V1 error format. AltValueValuesEnum: Data format for response. Fields: f__xgafv: V1 error format. access_token: OAuth access token. alt: Data format for response. bearer_token: OAuth bearer token. callback: JSONP fields: Selector specifying which fields to include in a partial response. key: API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. oauth_token: OAuth 2.0 token for the current user. pp: Pretty-print response. prettyPrint: Returns response with indentations and line breaks. quotaUser: Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. trace: A tracing token of the form "token:<tokenid>" to include in api requests. uploadType: Legacy upload protocol for media (e.g. "media", "multipart"). upload_protocol: Upload protocol for media (e.g. "raw", "multipart"). """ class AltValueValuesEnum(_messages.Enum): """Data format for response. Values: json: Responses with Content-Type of application/json media: Media download with context-dependent Content-Type proto: Responses with Content-Type of application/x-protobuf """ json = 0 media = 1 proto = 2 class FXgafvValueValuesEnum(_messages.Enum): """V1 error format. Values: _1: v1 error format _2: v2 error format """ _1 = 0 _2 = 1 f__xgafv = _messages.EnumField('FXgafvValueValuesEnum', 1) access_token = _messages.StringField(2) alt = _messages.EnumField('AltValueValuesEnum', 3, default=u'json') bearer_token = _messages.StringField(4) callback = _messages.StringField(5) fields = _messages.StringField(6) key = _messages.StringField(7) oauth_token = _messages.StringField(8) pp = _messages.BooleanField(9, default=True) prettyPrint = _messages.BooleanField(10, default=True) quotaUser = _messages.StringField(11) trace = _messages.StringField(12) uploadType = _messages.StringField(13) upload_protocol = _messages.StringField(14) class TestIamPermissionsRequest(_messages.Message): """Request message for `TestIamPermissions` method. Fields: permissions: The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). """ permissions = _messages.StringField(1, repeated=True) class TestIamPermissionsResponse(_messages.Message): """Response message for `TestIamPermissions` method. Fields: permissions: A subset of `TestPermissionsRequest.permissions` that the caller is allowed. """ permissions = _messages.StringField(1, repeated=True) class UpdateCryptoKeyPrimaryVersionRequest(_messages.Message): """Request message for KeyManagementService.UpdateCryptoKeyPrimaryVersion. Fields: cryptoKeyVersionId: The id of the child CryptoKeyVersion to use as primary. """ cryptoKeyVersionId = _messages.StringField(1) encoding.AddCustomJsonFieldMapping( StandardQueryParameters, 'f__xgafv', '$.xgafv') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_1', '1') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_2', '2')
jiwang576/incubator-airflow
refs/heads/master
airflow/operators/generic_transfer.py
46
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from airflow.hooks.base_hook import BaseHook class GenericTransfer(BaseOperator): """ Moves data from a connection to another, assuming that they both provide the required methods in their respective hooks. The source hook needs to expose a `get_records` method, and the destination a `insert_rows` method. This is mean to be used on small-ish datasets that fit in memory. :param sql: SQL query to execute against the source database :type sql: str :param destination_table: target table :type destination_table: str :param source_conn_id: source connection :type source_conn_id: str :param destination_conn_id: source connection :type destination_conn_id: str :param preoperator: sql statement or list of statements to be executed prior to loading the data :type preoperator: str or list of str """ template_fields = ('sql', 'destination_table', 'preoperator') template_ext = ('.sql', '.hql',) ui_color = '#b0f07c' @apply_defaults def __init__( self, sql, destination_table, source_conn_id, destination_conn_id, preoperator=None, *args, **kwargs): super(GenericTransfer, self).__init__(*args, **kwargs) self.sql = sql self.destination_table = destination_table self.source_conn_id = source_conn_id self.destination_conn_id = destination_conn_id self.preoperator = preoperator def execute(self, context): source_hook = BaseHook.get_hook(self.source_conn_id) logging.info("Extracting data from {}".format(self.source_conn_id)) logging.info("Executing: \n" + self.sql) results = source_hook.get_records(self.sql) destination_hook = BaseHook.get_hook(self.destination_conn_id) if self.preoperator: logging.info("Running preoperator") logging.info(self.preoperator) destination_hook.run(self.preoperator) logging.info("Inserting rows into {}".format(self.destination_conn_id)) destination_hook.insert_rows(table=self.destination_table, rows=results)
amkimian/Rapture
refs/heads/master
Apps/RaptureIntTests/src/test/python/structured.py
6
import raptureAPI import multipart import json import time import base64 # TODO These need to be parameters repo = '//nightly_python' strucRepoUri = 'structured:'+repo site = 'localhost:8665/rapture' username = 'rapture' password = 'rapture' rapture = raptureAPI.raptureAPI(site, username, password) config = "STRUCTURED { } USING POSTGRES { marvin=\"paranoid\" }" def test_structuredapi(): # Create a repo try: rapture.doStructured_DeleteStructuredRepo(strucRepoUri) except: assert True assert not rapture.doStructured_StructuredRepoExists(strucRepoUri) rapture.doStructured_CreateStructuredRepo(strucRepoUri, config) assert rapture.doStructured_StructuredRepoExists(strucRepoUri) assert config == rapture.doStructured_GetStructuredRepoConfig(strucRepoUri)['config'] # Create a table. Add and remove data table = repo + "/table" definition = {'id' : 'int', 'name' : 'varchar(255), PRIMARY KEY (id)'} rapture.doStructured_CreateTable(table, definition) row = {'id' : 42, 'name' : 'Don\'t Panic'} rapture.doStructured_InsertRow(table, row) contents = rapture.doStructured_SelectRows(table, None, None, None, None, -1) assert len(contents) == 1 assert contents[0] == row batch = [ {'id' : 11, 'name' : 'Ford Prefect'}, {'id' : 33, 'name' : 'Zaphod Beeblebrox'}, {'id' : 55, 'name' : 'Arthur Dent'}, {'id' : 44, 'name' : 'Slartibartfast'}, {'id' : 22, 'name' : 'Trillian'} ] rapture.doStructured_InsertRows(table, batch) contents = rapture.doStructured_SelectRows(table, None, None, None, None, -1) assert len(contents) == len(batch) + 1 rapture.doStructured_DeleteRows(table, "id=42") contents = rapture.doStructured_SelectRows(table, None, None, None, None, -1) assert len(contents) == len(batch) for f in contents: if f['id'] == 33: assert f['name'] == "Zaphod Beeblebrox" # Update a row rapture.doStructured_UpdateRows(table, {'id' : 33, 'name' : 'Zarniwoop'}, "id=33") contents = rapture.doStructured_SelectRows(table, None, None, None, None, -1) assert len(contents) == len(batch) for f in contents: if f['id'] == 33: assert f['name'] == "Zarniwoop" rapture.doStructured_DropTable(table) try: contents = rapture.doStructured_SelectRows(table, None, None, None, None, -1) assert False except: assert True # Good enough. Delete the repo. rapture.doStructured_DeleteStructuredRepo(strucRepoUri) assert not rapture.doStructured_StructuredRepoExists(strucRepoUri)
queria/my-tempest
refs/heads/juno
tempest/api/compute/v3/servers/test_servers.py
2
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.compute import base from tempest.common.utils import data_utils from tempest import test class ServersV3Test(base.BaseV3ComputeTest): @classmethod def resource_setup(cls): super(ServersV3Test, cls).resource_setup() cls.client = cls.servers_client def tearDown(self): self.clear_servers() super(ServersV3Test, self).tearDown() @test.attr(type='gate') def test_create_server_with_admin_password(self): # If an admin password is provided on server creation, the server's # root password should be set to that password. resp, server = self.create_test_server(admin_password='testpassword') # Verify the password is set correctly in the response self.assertEqual('testpassword', server['admin_password']) @test.attr(type='gate') def test_create_with_existing_server_name(self): # Creating a server with a name that already exists is allowed # TODO(sdague): clear out try, we do cleanup one layer up server_name = data_utils.rand_name('server') resp, server = self.create_test_server(name=server_name, wait_until='ACTIVE') id1 = server['id'] resp, server = self.create_test_server(name=server_name, wait_until='ACTIVE') id2 = server['id'] self.assertNotEqual(id1, id2, "Did not create a new server") resp, server = self.client.get_server(id1) name1 = server['name'] resp, server = self.client.get_server(id2) name2 = server['name'] self.assertEqual(name1, name2) @test.attr(type='gate') def test_create_specify_keypair(self): # Specify a keypair while creating a server key_name = data_utils.rand_name('key') resp, keypair = self.keypairs_client.create_keypair(key_name) resp, body = self.keypairs_client.list_keypairs() resp, server = self.create_test_server(key_name=key_name) self.assertEqual('202', resp['status']) self.client.wait_for_server_status(server['id'], 'ACTIVE') resp, server = self.client.get_server(server['id']) self.assertEqual(key_name, server['key_name']) @test.attr(type='gate') def test_update_server_name(self): # The server name should be changed to the the provided value resp, server = self.create_test_server(wait_until='ACTIVE') # Update the server with a new name resp, server = self.client.update_server(server['id'], name='newname') self.assertEqual(200, resp.status) self.client.wait_for_server_status(server['id'], 'ACTIVE') # Verify the name of the server has changed resp, server = self.client.get_server(server['id']) self.assertEqual('newname', server['name']) @test.attr(type='gate') def test_update_access_server_address(self): # The server's access addresses should reflect the provided values resp, server = self.create_test_server(wait_until='ACTIVE') # Update the IPv4 and IPv6 access addresses resp, body = self.client.update_server(server['id'], access_ip_v4='1.1.1.1', access_ip_v6='::babe:202:202') self.assertEqual(200, resp.status) self.client.wait_for_server_status(server['id'], 'ACTIVE') # Verify the access addresses have been updated resp, server = self.client.get_server(server['id']) self.assertEqual('1.1.1.1', server['os-access-ips:access_ip_v4']) self.assertEqual('::babe:202:202', server['os-access-ips:access_ip_v6']) @test.attr(type='gate') def test_create_server_with_ipv6_addr_only(self): # Create a server without an IPv4 address(only IPv6 address). resp, server = self.create_test_server(access_ip_v6='2001:2001::3') self.assertEqual('202', resp['status']) self.client.wait_for_server_status(server['id'], 'ACTIVE') resp, server = self.client.get_server(server['id']) self.assertEqual('2001:2001::3', server['os-access-ips:access_ip_v6'])
sudheesh001/oh-mainline
refs/heads/master
vendor/packages/mechanize/ez_setup.py
202
#!python """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import sys DEFAULT_VERSION = "0.6c11" DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb', 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b', 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a', 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618', 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac', 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5', 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4', 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c', 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b', 'setuptools-0.6c10-py2.3.egg': 'ce1e2ab5d3a0256456d9fc13800a7090', 'setuptools-0.6c10-py2.4.egg': '57d6d9d6e9b80772c59a53a8433a5dd4', 'setuptools-0.6c10-py2.5.egg': 'de46ac8b1c97c895572e5e8596aeb8c7', 'setuptools-0.6c10-py2.6.egg': '58ea40aef06da02ce641495523a0b7f5', 'setuptools-0.6c11-py2.3.egg': '2baeac6e13d414a9d28e7ba5b5a596de', 'setuptools-0.6c11-py2.4.egg': 'bd639f9b0eac4c42497034dec2ec0c2b', 'setuptools-0.6c11-py2.5.egg': '64c94f3bf7a72a13ec83e0b24f2749b2', 'setuptools-0.6c11-py2.6.egg': 'bfa92100bd772d5a213eedd356d64086', 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27', 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277', 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20', 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab', 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53', 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902', 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de', 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b', 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03', 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a', 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6', 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', } import sys, os try: from hashlib import md5 except ImportError: from md5 import md5 def _validate_md5(egg_name, data): if egg_name in md5_data: digest = md5(data).hexdigest() if digest != md5_data[egg_name]: print >>sys.stderr, ( "md5 validation of %s failed! (Possible download problem?)" % egg_name ) sys.exit(2) return data def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg try: import pkg_resources except ImportError: return do_download() try: pkg_resources.require("setuptools>="+version); return except pkg_resources.VersionConflict, e: if was_imported: print >>sys.stderr, ( "The required version of setuptools (>=%s) is not available, and\n" "can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" ) % (version, e.args[0]) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return do_download() except pkg_resources.DistributionNotFound: return do_download() def download_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay = 15 ): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ import urllib2, shutil egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) url = download_base + egg_name saveto = os.path.join(to_dir, egg_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: from distutils import log if delay: log.warn(""" --------------------------------------------------------------------------- This script requires setuptools version %s to run (even to display help). I will attempt to download it for you (from %s), but you may need to enable firewall access for this script first. I will start the download in %d seconds. (Note: if this machine does not have network access, please obtain the file %s and place it in this directory before rerunning this script.) ---------------------------------------------------------------------------""", version, download_base, delay, url ); from time import sleep; sleep(delay) log.warn("Downloading %s", url) src = urllib2.urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = _validate_md5(egg_name, src.read()) dst = open(saveto,"wb"); dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" try: import setuptools except ImportError: egg = None try: egg = download_setuptools(version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here finally: if egg and os.path.exists(egg): os.unlink(egg) else: if setuptools.__version__ == '0.0.1': print >>sys.stderr, ( "You have an obsolete version of setuptools installed. Please\n" "remove it from your system entirely before rerunning this script." ) sys.exit(2) req = "setuptools>="+version import pkg_resources try: pkg_resources.require(req) except pkg_resources.VersionConflict: try: from setuptools.command.easy_install import main except ImportError: from easy_install import main main(list(argv)+[download_setuptools(delay=0)]) sys.exit(0) # try to force an exit else: if argv: from setuptools.command.easy_install import main main(argv) else: print "Setuptools version",version,"or greater has been installed." print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = inspect.getsourcefile(sys.modules[__name__]) f = open(srcfile, 'rb'); src = f.read(); f.close() match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: print >>sys.stderr, "Internal error!" sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] f = open(srcfile,'w') f.write(src) f.close() if __name__=='__main__': if len(sys.argv)>2 and sys.argv[1]=='--md5update': update_md5(sys.argv[2:]) else: main(sys.argv[1:])
superchilli/webapp
refs/heads/master
venv/lib/python2.7/site-packages/alembic/testing/plugin/plugin_base.py
13
# plugin/plugin_base.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Testing extensions. this module is designed to work as a testing-framework-agnostic library, so that we can continue to support nose and also begin adding new functionality via py.test. NOTE: copied/adapted from SQLAlchemy master for backwards compatibility; this should be removable when Alembic targets SQLAlchemy 1.0.0 """ from __future__ import absolute_import try: # unitttest has a SkipTest also but pytest doesn't # honor it unless nose is imported too... from nose import SkipTest except ImportError: from pytest import skip SkipTest = skip.Exception import sys import re py3k = sys.version_info >= (3, 0) if py3k: import configparser else: import ConfigParser as configparser # late imports fixtures = None engines = None provision = None exclusions = None warnings = None assertions = None requirements = None config = None util = None file_config = None logging = None include_tags = set() exclude_tags = set() options = None def setup_options(make_option): make_option("--log-info", action="callback", type="string", callback=_log, help="turn on info logging for <LOG> (multiple OK)") make_option("--log-debug", action="callback", type="string", callback=_log, help="turn on debug logging for <LOG> (multiple OK)") make_option("--db", action="append", type="string", dest="db", help="Use prefab database uri. Multiple OK, " "first one is run by default.") make_option('--dbs', action='callback', callback=_list_dbs, help="List available prefab dbs") make_option("--dburi", action="append", type="string", dest="dburi", help="Database uri. Multiple OK, " "first one is run by default.") make_option("--dropfirst", action="store_true", dest="dropfirst", help="Drop all tables in the target database first") make_option("--backend-only", action="store_true", dest="backend_only", help="Run only tests marked with __backend__") make_option("--low-connections", action="store_true", dest="low_connections", help="Use a low number of distinct connections - " "i.e. for Oracle TNS") make_option("--write-idents", type="string", dest="write_idents", help="write out generated follower idents to <file>, " "when -n<num> is used") make_option("--reversetop", action="store_true", dest="reversetop", default=False, help="Use a random-ordering set implementation in the ORM " "(helps reveal dependency issues)") make_option("--requirements", action="callback", type="string", callback=_requirements_opt, help="requirements class for testing, overrides setup.cfg") make_option("--with-cdecimal", action="store_true", dest="cdecimal", default=False, help="Monkeypatch the cdecimal library into Python 'decimal' " "for all tests") make_option("--include-tag", action="callback", callback=_include_tag, type="string", help="Include tests with tag <tag>") make_option("--exclude-tag", action="callback", callback=_exclude_tag, type="string", help="Exclude tests with tag <tag>") make_option("--mysql-engine", action="store", dest="mysql_engine", default=None, help="Use the specified MySQL storage engine for all tables, " "default is a db-default/InnoDB combo.") def configure_follower(follower_ident): """Configure required state for a follower. This invokes in the parent process and typically includes database creation. """ from alembic.testing import provision provision.FOLLOWER_IDENT = follower_ident def memoize_important_follower_config(dict_): """Store important configuration we will need to send to a follower. This invokes in the parent process after normal config is set up. This is necessary as py.test seems to not be using forking, so we start with nothing in memory, *but* it isn't running our argparse callables, so we have to just copy all of that over. """ dict_['memoized_config'] = { 'include_tags': include_tags, 'exclude_tags': exclude_tags } def restore_important_follower_config(dict_): """Restore important configuration needed by a follower. This invokes in the follower process. """ include_tags.update(dict_['memoized_config']['include_tags']) exclude_tags.update(dict_['memoized_config']['exclude_tags']) def read_config(): global file_config file_config = configparser.ConfigParser() file_config.read(['setup.cfg', 'test.cfg']) def pre_begin(opt): """things to set up early, before coverage might be setup.""" global options options = opt for fn in pre_configure: fn(options, file_config) def set_coverage_flag(value): options.has_coverage = value def post_begin(): """things to set up later, once we know coverage is running.""" # Lazy setup of other options (post coverage) for fn in post_configure: fn(options, file_config) # late imports, has to happen after config as well # as nose plugins like coverage global util, fixtures, engines, exclusions, \ assertions, warnings, profiling,\ config, testing from alembic.testing import config, warnings, exclusions # noqa from alembic.testing import engines, fixtures # noqa from sqlalchemy import util # noqa warnings.setup_filters() def _log(opt_str, value, parser): global logging if not logging: import logging logging.basicConfig() if opt_str.endswith('-info'): logging.getLogger(value).setLevel(logging.INFO) elif opt_str.endswith('-debug'): logging.getLogger(value).setLevel(logging.DEBUG) def _list_dbs(*args): print("Available --db options (use --dburi to override)") for macro in sorted(file_config.options('db')): print("%20s\t%s" % (macro, file_config.get('db', macro))) sys.exit(0) def _requirements_opt(opt_str, value, parser): _setup_requirements(value) def _exclude_tag(opt_str, value, parser): exclude_tags.add(value.replace('-', '_')) def _include_tag(opt_str, value, parser): include_tags.add(value.replace('-', '_')) pre_configure = [] post_configure = [] def pre(fn): pre_configure.append(fn) return fn def post(fn): post_configure.append(fn) return fn @pre def _setup_options(opt, file_config): global options options = opt @pre def _monkeypatch_cdecimal(options, file_config): if options.cdecimal: import cdecimal sys.modules['decimal'] = cdecimal @post def _engine_uri(options, file_config): from alembic.testing import config from alembic.testing import provision if options.dburi: db_urls = list(options.dburi) else: db_urls = [] if options.db: for db_token in options.db: for db in re.split(r'[,\s]+', db_token): if db not in file_config.options('db'): raise RuntimeError( "Unknown URI specifier '%s'. " "Specify --dbs for known uris." % db) else: db_urls.append(file_config.get('db', db)) if not db_urls: db_urls.append(file_config.get('db', 'default')) for db_url in db_urls: cfg = provision.setup_config( db_url, options, file_config, provision.FOLLOWER_IDENT) if not config._current: cfg.set_as_current(cfg) @post def _requirements(options, file_config): requirement_cls = file_config.get('sqla_testing', "requirement_cls") _setup_requirements(requirement_cls) def _setup_requirements(argument): from alembic.testing import config if config.requirements is not None: return modname, clsname = argument.split(":") # importlib.import_module() only introduced in 2.7, a little # late mod = __import__(modname) for component in modname.split(".")[1:]: mod = getattr(mod, component) req_cls = getattr(mod, clsname) config.requirements = req_cls() @post def _prep_testing_database(options, file_config): from alembic.testing import config from alembic.testing.exclusions import against from sqlalchemy import schema from alembic import util if util.sqla_08: from sqlalchemy import inspect else: from sqlalchemy.engine.reflection import Inspector inspect = Inspector.from_engine if options.dropfirst: for cfg in config.Config.all_configs(): e = cfg.db inspector = inspect(e) try: view_names = inspector.get_view_names() except NotImplementedError: pass else: for vname in view_names: e.execute(schema._DropView( schema.Table(vname, schema.MetaData()) )) if config.requirements.schemas.enabled_for_config(cfg): try: view_names = inspector.get_view_names( schema="test_schema") except NotImplementedError: pass else: for vname in view_names: e.execute(schema._DropView( schema.Table(vname, schema.MetaData(), schema="test_schema") )) for tname in reversed(inspector.get_table_names( order_by="foreign_key")): e.execute(schema.DropTable( schema.Table(tname, schema.MetaData()) )) if config.requirements.schemas.enabled_for_config(cfg): for tname in reversed(inspector.get_table_names( order_by="foreign_key", schema="test_schema")): e.execute(schema.DropTable( schema.Table(tname, schema.MetaData(), schema="test_schema") )) if against(cfg, "postgresql") and util.sqla_100: from sqlalchemy.dialects import postgresql for enum in inspector.get_enums("*"): e.execute(postgresql.DropEnumType( postgresql.ENUM( name=enum['name'], schema=enum['schema']))) @post def _reverse_topological(options, file_config): if options.reversetop: from sqlalchemy.orm.util import randomize_unitofwork randomize_unitofwork() @post def _post_setup_options(opt, file_config): from alembic.testing import config config.options = options config.file_config = file_config def want_class(cls): if not issubclass(cls, fixtures.TestBase): return False elif cls.__name__.startswith('_'): return False elif config.options.backend_only and not getattr(cls, '__backend__', False): return False else: return True def want_method(cls, fn): if not fn.__name__.startswith("test_"): return False elif fn.__module__ is None: return False elif include_tags: return ( hasattr(cls, '__tags__') and exclusions.tags(cls.__tags__).include_test( include_tags, exclude_tags) ) or ( hasattr(fn, '_sa_exclusion_extend') and fn._sa_exclusion_extend.include_test( include_tags, exclude_tags) ) elif exclude_tags and hasattr(cls, '__tags__'): return exclusions.tags(cls.__tags__).include_test( include_tags, exclude_tags) elif exclude_tags and hasattr(fn, '_sa_exclusion_extend'): return fn._sa_exclusion_extend.include_test(include_tags, exclude_tags) else: return True def generate_sub_tests(cls, module): if getattr(cls, '__backend__', False): for cfg in _possible_configs_for_cls(cls): name = "%s_%s_%s" % (cls.__name__, cfg.db.name, cfg.db.driver) subcls = type( name, (cls, ), { "__only_on__": ("%s+%s" % (cfg.db.name, cfg.db.driver)), } ) setattr(module, name, subcls) yield subcls else: yield cls def start_test_class(cls): _do_skips(cls) _setup_engine(cls) def stop_test_class(cls): #from sqlalchemy import inspect #assert not inspect(testing.db).get_table_names() _restore_engine() def _restore_engine(): config._current.reset() def _setup_engine(cls): if getattr(cls, '__engine_options__', None): eng = engines.testing_engine(options=cls.__engine_options__) config._current.push_engine(eng) def before_test(test, test_module_name, test_class, test_name): pass def after_test(test): pass def _possible_configs_for_cls(cls, reasons=None): all_configs = set(config.Config.all_configs()) if cls.__unsupported_on__: spec = exclusions.db_spec(*cls.__unsupported_on__) for config_obj in list(all_configs): if spec(config_obj): all_configs.remove(config_obj) if getattr(cls, '__only_on__', None): spec = exclusions.db_spec(*util.to_list(cls.__only_on__)) for config_obj in list(all_configs): if not spec(config_obj): all_configs.remove(config_obj) if hasattr(cls, '__requires__'): requirements = config.requirements for config_obj in list(all_configs): for requirement in cls.__requires__: check = getattr(requirements, requirement) skip_reasons = check.matching_config_reasons(config_obj) if skip_reasons: all_configs.remove(config_obj) if reasons is not None: reasons.extend(skip_reasons) break if hasattr(cls, '__prefer_requires__'): non_preferred = set() requirements = config.requirements for config_obj in list(all_configs): for requirement in cls.__prefer_requires__: check = getattr(requirements, requirement) if not check.enabled_for_config(config_obj): non_preferred.add(config_obj) if all_configs.difference(non_preferred): all_configs.difference_update(non_preferred) return all_configs def _do_skips(cls): reasons = [] all_configs = _possible_configs_for_cls(cls, reasons) if getattr(cls, '__skip_if__', False): for c in getattr(cls, '__skip_if__'): if c(): raise SkipTest("'%s' skipped by %s" % ( cls.__name__, c.__name__) ) if not all_configs: if getattr(cls, '__backend__', False): msg = "'%s' unsupported for implementation '%s'" % ( cls.__name__, cls.__only_on__) else: msg = "'%s' unsupported on any DB implementation %s%s" % ( cls.__name__, ", ".join( "'%s(%s)+%s'" % ( config_obj.db.name, ".".join( str(dig) for dig in config_obj.db.dialect.server_version_info), config_obj.db.driver ) for config_obj in config.Config.all_configs() ), ", ".join(reasons) ) raise SkipTest(msg) elif hasattr(cls, '__prefer_backends__'): non_preferred = set() spec = exclusions.db_spec(*util.to_list(cls.__prefer_backends__)) for config_obj in all_configs: if not spec(config_obj): non_preferred.add(config_obj) if all_configs.difference(non_preferred): all_configs.difference_update(non_preferred) if config._current not in all_configs: _setup_config(all_configs.pop(), cls) def _setup_config(config_obj, ctx): config._current.push(config_obj)
yencarnacion/jaikuengine
refs/heads/master
common/test/clean.py
34
# -*- 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. from django import test from django.conf import settings from common import clean from common import exception from common import util from common.test import util as test_util class CleanTest(test.TestCase): normalize_data = [] good_data = [] bad_data = [] cleaner = staticmethod(lambda x: x) def _test_normalization(self, data): for t, example in data: try: result = self.cleaner(t) except exception.ValidationError, e: message = ("%s(%s) failed validation [%s]" % (self.cleaner.__name__, t, e)) raise AssertionError, message self.assertEqual(result, example) def test_normalization(self): self._test_normalization(self.normalize_data) def test_good_data(self): self._test_normalization([(x, x) for x in self.good_data]) def test_bad_data(self): for t in self.bad_data: self.assertRaises(exception.ValidationError, self.cleaner, t) class CleanBgRepeatTest(CleanTest): normalize_data = [ ('no-repeat', 'no-repeat'), ('', ''), ('repeat', ''), ('FooBar', ''), ] cleaner = staticmethod(clean.bg_repeat) class CleanBgColorTest(CleanTest): good_data = [ '#000000', '#123456', '#ffffff', '#EFEF00', 'red' ] bad_data = [ '123;', '#123"asd', ] cleaner = staticmethod(clean.bg_color) class CleanImageTest(CleanTest): good_data = [ '%s/bg_%s.jpg' % ('popular@example.com', '012340'), '%s/bg_%s.jpg' % ('popular@example.com', '0123af'), # How about a deterministic test: '%s/bg_%s.jpg' % ('popular@example.com', util.generate_uuid()), None ] bad_data = [ '%s/bg_%s.jpg' % ('popu@lar@example.com', '012340'), '%s/bg_%s.jpg' % ('popular@example.com', '0123afx'), ] normalize_data = [(x, x) for x in good_data] cleaner = staticmethod(clean.bg_image) class CleanChannelTest(CleanTest): normalize_data = [('channel', '#channel@example.com'), ('#channel', '#channel@example.com'), ('so', '#so@example.com'), ('#rty', '#rty@example.com'), ] good_data = ['#channel@example.com', '#so@example.com', '#45foo@example.com', ] bad_data = ['a', 'a' * 45, 'asd_', 'asd_f', '_asd', '123%#', '#!adsf', u'\xebasdf', 'ëdward', ] cleaner = staticmethod(clean.channel) class CleanUserTest(CleanTest): normalize_data = [('popular', 'popular@example.com'), ('so', 'so@example.com'), ] good_data = ['popular@example.com', 'so@example.com', '45foo@example.com', ] bad_data = ['a', 'a' * 45, 'asd_', 'asd_f', '_asd', '123%#', '#212', '!adsf', '#asdf', u'\xebasdf', '\xc3\xabdward' ] cleaner = staticmethod(clean.user) class CleanNickTest(CleanTest): normalize_data = (CleanUserTest.normalize_data + [('#channel', '#channel@example.com'), ('#rty', '#rty@example.com')] ) good_data = (CleanChannelTest.good_data + CleanUserTest.good_data) bad_data = (CleanChannelTest.bad_data) cleaner = staticmethod(clean.nick) class CleanRedirectToTest(CleanTest): normalize_data = [ ('http://www.gogle.com', '/'), ('https://www.gogle.com', '/'), ('foo\nbar', '/'), ('foo\rbar', '/'), ('ftp://' + settings.HOSTED_DOMAIN, '/'), (settings.HOSTED_DOMAIN, 'http://' + settings.HOSTED_DOMAIN), ] good_data = [ '/relative_url', 'http://' + settings.HOSTED_DOMAIN, 'http://foo.' + settings.HOSTED_DOMAIN, 'https://' + settings.HOSTED_DOMAIN, 'https://foo.' + settings.HOSTED_DOMAIN, 'http://' + settings.GAE_DOMAIN, 'http://foo.' + settings.GAE_DOMAIN, 'https://' + settings.GAE_DOMAIN, 'https://foo.' + settings.GAE_DOMAIN, ] cleaner = staticmethod(clean.redirect_to)
lchu94/classfinder
refs/heads/master
recommender/generate_recs.py
1
import math from django.core.cache import cache from django.db.models import Q from models import CompleteEnrollmentData, SharedClassesByMajor, SubjectInfo import get_new_classes, subject_info """ Create a matrix that records the number of students that took each pair of classes """ def create_shared_classes_table(major, all_classes, class_table): num_classes = len(all_classes) pairs = CompleteEnrollmentData.objects.filter(Q(major1=major) | Q(major2=major)).values_list("identifier","subject") # Only work with students declared in the given major # Create dictionary mapping each student to a list of classes taken student_class_dict = {} for identifier, cls in pairs: if identifier not in student_class_dict and cls in all_classes: student_class_dict[identifier] = [cls] elif cls in all_classes: student_class_dict[identifier].append(cls) matrix = [[0 for x in xrange(num_classes)] for y in xrange(num_classes)] for student, classes in student_class_dict.iteritems(): for sc1 in classes: for sc2 in classes: matrix[class_table[sc1]][class_table[sc2]] += 1 return matrix """ Determine the likelihood of a class being taken given the current term. """ def get_term_relevance_data(cur_term, new_classes): try: subject_info = SubjectInfo.objects.filter(subject__in=new_classes).values("subject", "title", cur_term, "total") except: print "Error connecting to SubjectInfo database table." term_data = {} class_titles = {} for row in subject_info: subject = row["subject"] class_titles[subject] = row["title"] cur_term_count = row[cur_term] + 1 total_count = row["total"] + 16 time_modifier = float(cur_term_count) / total_count term_data[subject] = time_modifier return term_data, class_titles """ Calculate the "importance" rating of one new class """ def calculate_rating(new_class, student_classes, class_table, shared_classes_table): rating = 1 for s in student_classes: index = class_table[s] total_number_class = shared_classes_table[index][index] if total_number_class == 0: break try: shared_number = int(shared_classes_table[class_table[new_class]][index]) rating *= math.exp(0.5 * shared_number / total_number_class) except: print (new_class, s) return rating """ Generate recommendations for a given student using the "importance" method. Recommendations are for the current semester and are based upon all classes taken by the student. TODO: error handling for invalid class? """ def generate_recommendations(major, cur_semester, student_classes): new_classes = get_new_classes.get_classes_to_take(major, student_classes) all_classes = student_classes + new_classes if major == '18_applied' or major == '18_general': major = '18' else: major = major.replace('_', ' ') class_table = {k:v for k, v in zip(all_classes, xrange(len(all_classes)))} shared_classes_table = create_shared_classes_table(major, all_classes, class_table) # consider caching # Calculate time (semester) relevance cur_term = "term%s" % cur_semester term_data, class_titles = get_term_relevance_data(cur_term, new_classes) # Calculate "importance" of each class that hasn't been taken by the student importance_ratings = {} for new_class in new_classes: rating = calculate_rating(new_class, student_classes, class_table, shared_classes_table) # try: # rating *= term_data[new_class] # time relevance # except: # pass importance_ratings[new_class] = rating # Create list of classes in order of popularity sorted_classes = sorted(importance_ratings, key=importance_ratings.get, reverse=True) recs = [] for c in sorted_classes[:20]: try: title = class_titles[c] except: try: title = subject_info.get_online_info(c)['title'] except: title = "" recs.append((c, title)) return recs
mazulo/SGT
refs/heads/master
sgt/cash_register/tests.py
24123
from django.test import TestCase # Create your tests here.
elahejalalpour/ELRyu
refs/heads/master
ryu/lib/packet/stream_parser.py
58
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from abc import ABCMeta, abstractmethod import six @six.add_metaclass(ABCMeta) class StreamParser(object): """Streaming parser base class. An instance of a subclass of this class is used to extract messages from a raw byte stream. It's designed to be used for data read from a transport which doesn't preserve message boundaries. A typical example of such a transport is TCP. """ class TooSmallException(Exception): pass def __init__(self): self._q = bytearray() def parse(self, data): """Tries to extract messages from a raw byte stream. The data argument would be python bytes newly read from the input stream. Returns an ordered list of extracted messages. It can be an empty list. The rest of data which doesn't produce a complete message is kept internally and will be used when more data is come. I.e. next time this method is called again. """ self._q.append(data) msgs = [] while True: try: msg, self._q = self.try_parse(self._q) except self.TooSmallException: break msgs.append(msg) return msgs @abstractmethod def try_parse(self, q): """Try to extract a message from the given bytes. This is an override point for subclasses. This method tries to extract a message from bytes given by the argument. Raises TooSmallException if the given data is not enough to extract a complete message but there's still a chance to extract a message if more data is come later. """ pass
invisiblek/python-for-android
refs/heads/master
python3-alpha/python3-src/Lib/argparse.py
45
# Author: Steven J. Bethard <steven.bethard@gmail.com>. """Command-line parsing library This module is an optparse-inspired command-line parsing library that: - handles both optional and positional arguments - produces highly informative usage messages - supports parsers that dispatch to sub-parsers The following is a simple usage example that sums integers from the command-line and writes the result to a file:: parser = argparse.ArgumentParser( description='sum the integers at the command line') parser.add_argument( 'integers', metavar='int', nargs='+', type=int, help='an integer to be summed') parser.add_argument( '--log', default=sys.stdout, type=argparse.FileType('w'), help='the file where the sum should be written') args = parser.parse_args() args.log.write('%s' % sum(args.integers)) args.log.close() The module contains the following public classes: - ArgumentParser -- The main entry point for command-line parsing. As the example above shows, the add_argument() method is used to populate the parser with actions for optional and positional arguments. Then the parse_args() method is invoked to convert the args at the command-line into an object with attributes. - ArgumentError -- The exception raised by ArgumentParser objects when there are errors with the parser's actions. Errors raised while parsing the command-line are caught by ArgumentParser and emitted as command-line messages. - FileType -- A factory for defining types of files to be created. As the example above shows, instances of FileType are typically passed as the type= argument of add_argument() calls. - Action -- The base class for parser actions. Typically actions are selected by passing strings like 'store_true' or 'append_const' to the action= argument of add_argument(). However, for greater customization of ArgumentParser actions, subclasses of Action may be defined and passed as the action= argument. - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, ArgumentDefaultsHelpFormatter -- Formatter classes which may be passed as the formatter_class= argument to the ArgumentParser constructor. HelpFormatter is the default, RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser not to change the formatting for help text, and ArgumentDefaultsHelpFormatter adds information about argument defaults to the help. All other classes in this module are considered implementation details. (Also note that HelpFormatter and RawDescriptionHelpFormatter are only considered public as object names -- the API of the formatter objects is still considered an implementation detail.) """ __version__ = '1.1' __all__ = [ 'ArgumentParser', 'ArgumentError', 'ArgumentTypeError', 'FileType', 'HelpFormatter', 'ArgumentDefaultsHelpFormatter', 'RawDescriptionHelpFormatter', 'RawTextHelpFormatter', 'Namespace', 'Action', 'ONE_OR_MORE', 'OPTIONAL', 'PARSER', 'REMAINDER', 'SUPPRESS', 'ZERO_OR_MORE', ] import collections as _collections import copy as _copy import os as _os import re as _re import sys as _sys import textwrap as _textwrap from gettext import gettext as _, ngettext def _callable(obj): return hasattr(obj, '__call__') or hasattr(obj, '__bases__') SUPPRESS = '==SUPPRESS==' OPTIONAL = '?' ZERO_OR_MORE = '*' ONE_OR_MORE = '+' PARSER = 'A...' REMAINDER = '...' _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' # ============================= # Utility functions and classes # ============================= class _AttributeHolder(object): """Abstract base class that provides __repr__. The __repr__ method returns a string in the format:: ClassName(attr=name, attr=name, ...) The attributes are determined either by a class-level attribute, '_kwarg_names', or by inspecting the instance __dict__. """ def __repr__(self): type_name = type(self).__name__ arg_strings = [] for arg in self._get_args(): arg_strings.append(repr(arg)) for name, value in self._get_kwargs(): arg_strings.append('%s=%r' % (name, value)) return '%s(%s)' % (type_name, ', '.join(arg_strings)) def _get_kwargs(self): return sorted(self.__dict__.items()) def _get_args(self): return [] def _ensure_value(namespace, name, value): if getattr(namespace, name, None) is None: setattr(namespace, name, value) return getattr(namespace, name) # =============== # Formatting Help # =============== class HelpFormatter(object): """Formatter for generating usage messages and argument help strings. Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail. """ def __init__(self, prog, indent_increment=2, max_help_position=24, width=None): # default setting for width if width is None: try: width = int(_os.environ['COLUMNS']) except (KeyError, ValueError): width = 80 width -= 2 self._prog = prog self._indent_increment = indent_increment self._max_help_position = max_help_position self._width = width self._current_indent = 0 self._level = 0 self._action_max_length = 0 self._root_section = self._Section(self, None) self._current_section = self._root_section self._whitespace_matcher = _re.compile(r'\s+') self._long_break_matcher = _re.compile(r'\n\n\n+') # =============================== # Section and indentation methods # =============================== def _indent(self): self._current_indent += self._indent_increment self._level += 1 def _dedent(self): self._current_indent -= self._indent_increment assert self._current_indent >= 0, 'Indent decreased below 0.' self._level -= 1 class _Section(object): def __init__(self, formatter, parent, heading=None): self.formatter = formatter self.parent = parent self.heading = heading self.items = [] def format_help(self): # format the indented section if self.parent is not None: self.formatter._indent() join = self.formatter._join_parts for func, args in self.items: func(*args) item_help = join([func(*args) for func, args in self.items]) if self.parent is not None: self.formatter._dedent() # return nothing if the section was empty if not item_help: return '' # add the heading if the section was non-empty if self.heading is not SUPPRESS and self.heading is not None: current_indent = self.formatter._current_indent heading = '%*s%s:\n' % (current_indent, '', self.heading) else: heading = '' # join the section-initial newline, the heading and the help return join(['\n', heading, item_help, '\n']) def _add_item(self, func, args): self._current_section.items.append((func, args)) # ======================== # Message building methods # ======================== def start_section(self, heading): self._indent() section = self._Section(self, self._current_section, heading) self._add_item(section.format_help, []) self._current_section = section def end_section(self): self._current_section = self._current_section.parent self._dedent() def add_text(self, text): if text is not SUPPRESS and text is not None: self._add_item(self._format_text, [text]) def add_usage(self, usage, actions, groups, prefix=None): if usage is not SUPPRESS: args = usage, actions, groups, prefix self._add_item(self._format_usage, args) def add_argument(self, action): if action.help is not SUPPRESS: # find all invocations get_invocation = self._format_action_invocation invocations = [get_invocation(action)] for subaction in self._iter_indented_subactions(action): invocations.append(get_invocation(subaction)) # update the maximum item length invocation_length = max([len(s) for s in invocations]) action_length = invocation_length + self._current_indent self._action_max_length = max(self._action_max_length, action_length) # add the item to the list self._add_item(self._format_action, [action]) def add_arguments(self, actions): for action in actions: self.add_argument(action) # ======================= # Help-formatting methods # ======================= def format_help(self): help = self._root_section.format_help() if help: help = self._long_break_matcher.sub('\n\n', help) help = help.strip('\n') + '\n' return help def _join_parts(self, part_strings): return ''.join([part for part in part_strings if part and part is not SUPPRESS]) def _format_usage(self, usage, actions, groups, prefix): if prefix is None: prefix = _('usage: ') # if usage is specified, use that if usage is not None: usage = usage % dict(prog=self._prog) # if no optionals or positionals are available, usage is just prog elif usage is None and not actions: usage = '%(prog)s' % dict(prog=self._prog) # if optionals and positionals are available, calculate usage elif usage is None: prog = '%(prog)s' % dict(prog=self._prog) # split optionals from positionals optionals = [] positionals = [] for action in actions: if action.option_strings: optionals.append(action) else: positionals.append(action) # build full usage string format = self._format_actions_usage action_usage = format(optionals + positionals, groups) usage = ' '.join([s for s in [prog, action_usage] if s]) # wrap the usage parts if it's too long text_width = self._width - self._current_indent if len(prefix) + len(usage) > text_width: # break usage into wrappable parts part_regexp = r'\(.*?\)+|\[.*?\]+|\S+' opt_usage = format(optionals, groups) pos_usage = format(positionals, groups) opt_parts = _re.findall(part_regexp, opt_usage) pos_parts = _re.findall(part_regexp, pos_usage) assert ' '.join(opt_parts) == opt_usage assert ' '.join(pos_parts) == pos_usage # helper for wrapping lines def get_lines(parts, indent, prefix=None): lines = [] line = [] if prefix is not None: line_len = len(prefix) - 1 else: line_len = len(indent) - 1 for part in parts: if line_len + 1 + len(part) > text_width: lines.append(indent + ' '.join(line)) line = [] line_len = len(indent) - 1 line.append(part) line_len += len(part) + 1 if line: lines.append(indent + ' '.join(line)) if prefix is not None: lines[0] = lines[0][len(indent):] return lines # if prog is short, follow it with optionals or positionals if len(prefix) + len(prog) <= 0.75 * text_width: indent = ' ' * (len(prefix) + len(prog) + 1) if opt_parts: lines = get_lines([prog] + opt_parts, indent, prefix) lines.extend(get_lines(pos_parts, indent)) elif pos_parts: lines = get_lines([prog] + pos_parts, indent, prefix) else: lines = [prog] # if prog is long, put it on its own line else: indent = ' ' * len(prefix) parts = opt_parts + pos_parts lines = get_lines(parts, indent) if len(lines) > 1: lines = [] lines.extend(get_lines(opt_parts, indent)) lines.extend(get_lines(pos_parts, indent)) lines = [prog] + lines # join lines into usage usage = '\n'.join(lines) # prefix with 'usage:' return '%s%s\n\n' % (prefix, usage) def _format_actions_usage(self, actions, groups): # find group indices and identify actions in groups group_actions = set() inserts = {} for group in groups: try: start = actions.index(group._group_actions[0]) except ValueError: continue else: end = start + len(group._group_actions) if actions[start:end] == group._group_actions: for action in group._group_actions: group_actions.add(action) if not group.required: if start in inserts: inserts[start] += ' [' else: inserts[start] = '[' inserts[end] = ']' else: if start in inserts: inserts[start] += ' (' else: inserts[start] = '(' inserts[end] = ')' for i in range(start + 1, end): inserts[i] = '|' # collect all actions format strings parts = [] for i, action in enumerate(actions): # suppressed arguments are marked with None # remove | separators for suppressed arguments if action.help is SUPPRESS: parts.append(None) if inserts.get(i) == '|': inserts.pop(i) elif inserts.get(i + 1) == '|': inserts.pop(i + 1) # produce all arg strings elif not action.option_strings: part = self._format_args(action, action.dest) # if it's in a group, strip the outer [] if action in group_actions: if part[0] == '[' and part[-1] == ']': part = part[1:-1] # add the action string to the list parts.append(part) # produce the first way to invoke the option in brackets else: option_string = action.option_strings[0] # if the Optional doesn't take a value, format is: # -s or --long if action.nargs == 0: part = '%s' % option_string # if the Optional takes a value, format is: # -s ARGS or --long ARGS else: default = action.dest.upper() args_string = self._format_args(action, default) part = '%s %s' % (option_string, args_string) # make it look optional if it's not required or in a group if not action.required and action not in group_actions: part = '[%s]' % part # add the action string to the list parts.append(part) # insert things at the necessary indices for i in sorted(inserts, reverse=True): parts[i:i] = [inserts[i]] # join all the action items with spaces text = ' '.join([item for item in parts if item is not None]) # clean up separators for mutually exclusive groups open = r'[\[(]' close = r'[\])]' text = _re.sub(r'(%s) ' % open, r'\1', text) text = _re.sub(r' (%s)' % close, r'\1', text) text = _re.sub(r'%s *%s' % (open, close), r'', text) text = _re.sub(r'\(([^|]*)\)', r'\1', text) text = text.strip() # return the text return text def _format_text(self, text): if '%(prog)' in text: text = text % dict(prog=self._prog) text_width = self._width - self._current_indent indent = ' ' * self._current_indent return self._fill_text(text, text_width, indent) + '\n\n' def _format_action(self, action): # determine the required width and the entry label help_position = min(self._action_max_length + 2, self._max_help_position) help_width = self._width - help_position action_width = help_position - self._current_indent - 2 action_header = self._format_action_invocation(action) # ho nelp; start on same line and add a final newline if not action.help: tup = self._current_indent, '', action_header action_header = '%*s%s\n' % tup # short action name; start on the same line and pad two spaces elif len(action_header) <= action_width: tup = self._current_indent, '', action_width, action_header action_header = '%*s%-*s ' % tup indent_first = 0 # long action name; start on the next line else: tup = self._current_indent, '', action_header action_header = '%*s%s\n' % tup indent_first = help_position # collect the pieces of the action help parts = [action_header] # if there was help for the action, add lines of help text if action.help: help_text = self._expand_help(action) help_lines = self._split_lines(help_text, help_width) parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) for line in help_lines[1:]: parts.append('%*s%s\n' % (help_position, '', line)) # or add a newline if the description doesn't end with one elif not action_header.endswith('\n'): parts.append('\n') # if there are any sub-actions, add their help as well for subaction in self._iter_indented_subactions(action): parts.append(self._format_action(subaction)) # return a single string return self._join_parts(parts) def _format_action_invocation(self, action): if not action.option_strings: metavar, = self._metavar_formatter(action, action.dest)(1) return metavar else: parts = [] # if the Optional doesn't take a value, format is: # -s, --long if action.nargs == 0: parts.extend(action.option_strings) # if the Optional takes a value, format is: # -s ARGS, --long ARGS else: default = action.dest.upper() args_string = self._format_args(action, default) for option_string in action.option_strings: parts.append('%s %s' % (option_string, args_string)) return ', '.join(parts) def _metavar_formatter(self, action, default_metavar): if action.metavar is not None: result = action.metavar elif action.choices is not None: choice_strs = [str(choice) for choice in action.choices] result = '{%s}' % ','.join(choice_strs) else: result = default_metavar def format(tuple_size): if isinstance(result, tuple): return result else: return (result, ) * tuple_size return format def _format_args(self, action, default_metavar): get_metavar = self._metavar_formatter(action, default_metavar) if action.nargs is None: result = '%s' % get_metavar(1) elif action.nargs == OPTIONAL: result = '[%s]' % get_metavar(1) elif action.nargs == ZERO_OR_MORE: result = '[%s [%s ...]]' % get_metavar(2) elif action.nargs == ONE_OR_MORE: result = '%s [%s ...]' % get_metavar(2) elif action.nargs == REMAINDER: result = '...' elif action.nargs == PARSER: result = '%s ...' % get_metavar(1) else: formats = ['%s' for _ in range(action.nargs)] result = ' '.join(formats) % get_metavar(action.nargs) return result def _expand_help(self, action): params = dict(vars(action), prog=self._prog) for name in list(params): if params[name] is SUPPRESS: del params[name] for name in list(params): if hasattr(params[name], '__name__'): params[name] = params[name].__name__ if params.get('choices') is not None: choices_str = ', '.join([str(c) for c in params['choices']]) params['choices'] = choices_str return self._get_help_string(action) % params def _iter_indented_subactions(self, action): try: get_subactions = action._get_subactions except AttributeError: pass else: self._indent() for subaction in get_subactions(): yield subaction self._dedent() def _split_lines(self, text, width): text = self._whitespace_matcher.sub(' ', text).strip() return _textwrap.wrap(text, width) def _fill_text(self, text, width, indent): text = self._whitespace_matcher.sub(' ', text).strip() return _textwrap.fill(text, width, initial_indent=indent, subsequent_indent=indent) def _get_help_string(self, action): return action.help class RawDescriptionHelpFormatter(HelpFormatter): """Help message formatter which retains any formatting in descriptions. Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail. """ def _fill_text(self, text, width, indent): return ''.join([indent + line for line in text.splitlines(True)]) class RawTextHelpFormatter(RawDescriptionHelpFormatter): """Help message formatter which retains formatting of all help text. Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail. """ def _split_lines(self, text, width): return text.splitlines() class ArgumentDefaultsHelpFormatter(HelpFormatter): """Help message formatter which adds default values to argument help. Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail. """ def _get_help_string(self, action): help = action.help if '%(default)' not in action.help: if action.default is not SUPPRESS: defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] if action.option_strings or action.nargs in defaulting_nargs: help += ' (default: %(default)s)' return help # ===================== # Options and Arguments # ===================== def _get_action_name(argument): if argument is None: return None elif argument.option_strings: return '/'.join(argument.option_strings) elif argument.metavar not in (None, SUPPRESS): return argument.metavar elif argument.dest not in (None, SUPPRESS): return argument.dest else: return None class ArgumentError(Exception): """An error from creating or using an argument (optional or positional). The string value of this exception is the message, augmented with information about the argument that caused it. """ def __init__(self, argument, message): self.argument_name = _get_action_name(argument) self.message = message def __str__(self): if self.argument_name is None: format = '%(message)s' else: format = 'argument %(argument_name)s: %(message)s' return format % dict(message=self.message, argument_name=self.argument_name) class ArgumentTypeError(Exception): """An error from trying to convert a command line string to a type.""" pass # ============== # Action classes # ============== class Action(_AttributeHolder): """Information about how to convert command line strings to Python objects. Action objects are used by an ArgumentParser to represent the information needed to parse a single argument from one or more strings from the command line. The keyword arguments to the Action constructor are also all attributes of Action instances. Keyword Arguments: - option_strings -- A list of command-line option strings which should be associated with this action. - dest -- The name of the attribute to hold the created object(s) - nargs -- The number of command-line arguments that should be consumed. By default, one argument will be consumed and a single value will be produced. Other values include: - N (an integer) consumes N arguments (and produces a list) - '?' consumes zero or one arguments - '*' consumes zero or more arguments (and produces a list) - '+' consumes one or more arguments (and produces a list) Note that the difference between the default and nargs=1 is that with the default, a single value will be produced, while with nargs=1, a list containing a single value will be produced. - const -- The value to be produced if the option is specified and the option uses an action that takes no values. - default -- The value to be produced if the option is not specified. - type -- The type which the command-line arguments should be converted to, should be one of 'string', 'int', 'float', 'complex' or a callable object that accepts a single string argument. If None, 'string' is assumed. - choices -- A container of values that should be allowed. If not None, after a command-line argument has been converted to the appropriate type, an exception will be raised if it is not a member of this collection. - required -- True if the action must always be specified at the command line. This is only meaningful for optional command-line arguments. - help -- The help string describing the argument. - metavar -- The name to be used for the option's argument with the help string. If None, the 'dest' value will be used as the name. """ def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None): self.option_strings = option_strings self.dest = dest self.nargs = nargs self.const = const self.default = default self.type = type self.choices = choices self.required = required self.help = help self.metavar = metavar def _get_kwargs(self): names = [ 'option_strings', 'dest', 'nargs', 'const', 'default', 'type', 'choices', 'help', 'metavar', ] return [(name, getattr(self, name)) for name in names] def __call__(self, parser, namespace, values, option_string=None): raise NotImplementedError(_('.__call__() not defined')) class _StoreAction(Action): def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None): if nargs == 0: raise ValueError('nargs for store actions must be > 0; if you ' 'have nothing to store, actions such as store ' 'true or store const may be more appropriate') if const is not None and nargs != OPTIONAL: raise ValueError('nargs must be %r to supply const' % OPTIONAL) super(_StoreAction, self).__init__( option_strings=option_strings, dest=dest, nargs=nargs, const=const, default=default, type=type, choices=choices, required=required, help=help, metavar=metavar) def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, values) class _StoreConstAction(Action): def __init__(self, option_strings, dest, const, default=None, required=False, help=None, metavar=None): super(_StoreConstAction, self).__init__( option_strings=option_strings, dest=dest, nargs=0, const=const, default=default, required=required, help=help) def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, self.const) class _StoreTrueAction(_StoreConstAction): def __init__(self, option_strings, dest, default=False, required=False, help=None): super(_StoreTrueAction, self).__init__( option_strings=option_strings, dest=dest, const=True, default=default, required=required, help=help) class _StoreFalseAction(_StoreConstAction): def __init__(self, option_strings, dest, default=True, required=False, help=None): super(_StoreFalseAction, self).__init__( option_strings=option_strings, dest=dest, const=False, default=default, required=required, help=help) class _AppendAction(Action): def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None): if nargs == 0: raise ValueError('nargs for append actions must be > 0; if arg ' 'strings are not supplying the value to append, ' 'the append const action may be more appropriate') if const is not None and nargs != OPTIONAL: raise ValueError('nargs must be %r to supply const' % OPTIONAL) super(_AppendAction, self).__init__( option_strings=option_strings, dest=dest, nargs=nargs, const=const, default=default, type=type, choices=choices, required=required, help=help, metavar=metavar) def __call__(self, parser, namespace, values, option_string=None): items = _copy.copy(_ensure_value(namespace, self.dest, [])) items.append(values) setattr(namespace, self.dest, items) class _AppendConstAction(Action): def __init__(self, option_strings, dest, const, default=None, required=False, help=None, metavar=None): super(_AppendConstAction, self).__init__( option_strings=option_strings, dest=dest, nargs=0, const=const, default=default, required=required, help=help, metavar=metavar) def __call__(self, parser, namespace, values, option_string=None): items = _copy.copy(_ensure_value(namespace, self.dest, [])) items.append(self.const) setattr(namespace, self.dest, items) class _CountAction(Action): def __init__(self, option_strings, dest, default=None, required=False, help=None): super(_CountAction, self).__init__( option_strings=option_strings, dest=dest, nargs=0, default=default, required=required, help=help) def __call__(self, parser, namespace, values, option_string=None): new_count = _ensure_value(namespace, self.dest, 0) + 1 setattr(namespace, self.dest, new_count) class _HelpAction(Action): def __init__(self, option_strings, dest=SUPPRESS, default=SUPPRESS, help=None): super(_HelpAction, self).__init__( option_strings=option_strings, dest=dest, default=default, nargs=0, help=help) def __call__(self, parser, namespace, values, option_string=None): parser.print_help() parser.exit() class _VersionAction(Action): def __init__(self, option_strings, version=None, dest=SUPPRESS, default=SUPPRESS, help="show program's version number and exit"): super(_VersionAction, self).__init__( option_strings=option_strings, dest=dest, default=default, nargs=0, help=help) self.version = version def __call__(self, parser, namespace, values, option_string=None): version = self.version if version is None: version = parser.version formatter = parser._get_formatter() formatter.add_text(version) parser.exit(message=formatter.format_help()) class _SubParsersAction(Action): class _ChoicesPseudoAction(Action): def __init__(self, name, aliases, help): metavar = dest = name if aliases: metavar += ' (%s)' % ', '.join(aliases) sup = super(_SubParsersAction._ChoicesPseudoAction, self) sup.__init__(option_strings=[], dest=dest, help=help, metavar=metavar) def __init__(self, option_strings, prog, parser_class, dest=SUPPRESS, help=None, metavar=None): self._prog_prefix = prog self._parser_class = parser_class self._name_parser_map = _collections.OrderedDict() self._choices_actions = [] super(_SubParsersAction, self).__init__( option_strings=option_strings, dest=dest, nargs=PARSER, choices=self._name_parser_map, help=help, metavar=metavar) def add_parser(self, name, **kwargs): # set prog from the existing prefix if kwargs.get('prog') is None: kwargs['prog'] = '%s %s' % (self._prog_prefix, name) aliases = kwargs.pop('aliases', ()) # create a pseudo-action to hold the choice help if 'help' in kwargs: help = kwargs.pop('help') choice_action = self._ChoicesPseudoAction(name, aliases, help) self._choices_actions.append(choice_action) # create the parser and add it to the map parser = self._parser_class(**kwargs) self._name_parser_map[name] = parser # make parser available under aliases also for alias in aliases: self._name_parser_map[alias] = parser return parser def _get_subactions(self): return self._choices_actions def __call__(self, parser, namespace, values, option_string=None): parser_name = values[0] arg_strings = values[1:] # set the parser name if requested if self.dest is not SUPPRESS: setattr(namespace, self.dest, parser_name) # select the parser try: parser = self._name_parser_map[parser_name] except KeyError: args = {'parser_name': parser_name, 'choices': ', '.join(self._name_parser_map)} msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args raise ArgumentError(self, msg) # parse all the remaining options into the namespace # store any unrecognized options on the object, so that the top # level parser can decide what to do with them namespace, arg_strings = parser.parse_known_args(arg_strings, namespace) if arg_strings: vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) # ============== # Type classes # ============== class FileType(object): """Factory for creating file object types Instances of FileType are typically passed as type= arguments to the ArgumentParser add_argument() method. Keyword Arguments: - mode -- A string indicating how the file is to be opened. Accepts the same values as the builtin open() function. - bufsize -- The file's desired buffer size. Accepts the same values as the builtin open() function. """ def __init__(self, mode='r', bufsize=-1): self._mode = mode self._bufsize = bufsize def __call__(self, string): # the special argument "-" means sys.std{in,out} if string == '-': if 'r' in self._mode: return _sys.stdin elif 'w' in self._mode: return _sys.stdout else: msg = _('argument "-" with mode %r') % self._mode raise ValueError(msg) # all other arguments are used as file names try: return open(string, self._mode, self._bufsize) except IOError as e: message = _("can't open '%s': %s") raise ArgumentTypeError(message % (string, e)) def __repr__(self): args = self._mode, self._bufsize args_str = ', '.join(repr(arg) for arg in args if arg != -1) return '%s(%s)' % (type(self).__name__, args_str) # =========================== # Optional and Positional Parsing # =========================== class Namespace(_AttributeHolder): """Simple object for storing attributes. Implements equality by attribute names and values, and provides a simple string representation. """ def __init__(self, **kwargs): for name in kwargs: setattr(self, name, kwargs[name]) def __eq__(self, other): return vars(self) == vars(other) def __ne__(self, other): return not (self == other) def __contains__(self, key): return key in self.__dict__ class _ActionsContainer(object): def __init__(self, description, prefix_chars, argument_default, conflict_handler): super(_ActionsContainer, self).__init__() self.description = description self.argument_default = argument_default self.prefix_chars = prefix_chars self.conflict_handler = conflict_handler # set up registries self._registries = {} # register actions self.register('action', None, _StoreAction) self.register('action', 'store', _StoreAction) self.register('action', 'store_const', _StoreConstAction) self.register('action', 'store_true', _StoreTrueAction) self.register('action', 'store_false', _StoreFalseAction) self.register('action', 'append', _AppendAction) self.register('action', 'append_const', _AppendConstAction) self.register('action', 'count', _CountAction) self.register('action', 'help', _HelpAction) self.register('action', 'version', _VersionAction) self.register('action', 'parsers', _SubParsersAction) # raise an exception if the conflict handler is invalid self._get_handler() # action storage self._actions = [] self._option_string_actions = {} # groups self._action_groups = [] self._mutually_exclusive_groups = [] # defaults storage self._defaults = {} # determines whether an "option" looks like a negative number self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$') # whether or not there are any optionals that look like negative # numbers -- uses a list so it can be shared and edited self._has_negative_number_optionals = [] # ==================== # Registration methods # ==================== def register(self, registry_name, value, object): registry = self._registries.setdefault(registry_name, {}) registry[value] = object def _registry_get(self, registry_name, value, default=None): return self._registries[registry_name].get(value, default) # ================================== # Namespace default accessor methods # ================================== def set_defaults(self, **kwargs): self._defaults.update(kwargs) # if these defaults match any existing arguments, replace # the previous default on the object with the new one for action in self._actions: if action.dest in kwargs: action.default = kwargs[action.dest] def get_default(self, dest): for action in self._actions: if action.dest == dest and action.default is not None: return action.default return self._defaults.get(dest, None) # ======================= # Adding argument actions # ======================= def add_argument(self, *args, **kwargs): """ add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...) """ # if no positional args are supplied or only one is supplied and # it doesn't look like an option string, parse a positional # argument chars = self.prefix_chars if not args or len(args) == 1 and args[0][0] not in chars: if args and 'dest' in kwargs: raise ValueError('dest supplied twice for positional argument') kwargs = self._get_positional_kwargs(*args, **kwargs) # otherwise, we're adding an optional argument else: kwargs = self._get_optional_kwargs(*args, **kwargs) # if no default was supplied, use the parser-level default if 'default' not in kwargs: dest = kwargs['dest'] if dest in self._defaults: kwargs['default'] = self._defaults[dest] elif self.argument_default is not None: kwargs['default'] = self.argument_default # create the action object, and add it to the parser action_class = self._pop_action_class(kwargs) if not _callable(action_class): raise ValueError('unknown action "%s"' % (action_class,)) action = action_class(**kwargs) # raise an error if the action type is not callable type_func = self._registry_get('type', action.type, action.type) if not _callable(type_func): raise ValueError('%r is not callable' % (type_func,)) # raise an error if the metavar does not match the type if hasattr(self, "_get_formatter"): try: self._get_formatter()._format_args(action, None) except TypeError: raise ValueError("length of metavar tuple does not match nargs") return self._add_action(action) def add_argument_group(self, *args, **kwargs): group = _ArgumentGroup(self, *args, **kwargs) self._action_groups.append(group) return group def add_mutually_exclusive_group(self, **kwargs): group = _MutuallyExclusiveGroup(self, **kwargs) self._mutually_exclusive_groups.append(group) return group def _add_action(self, action): # resolve any conflicts self._check_conflict(action) # add to actions list self._actions.append(action) action.container = self # index the action by any option strings it has for option_string in action.option_strings: self._option_string_actions[option_string] = action # set the flag if any option strings look like negative numbers for option_string in action.option_strings: if self._negative_number_matcher.match(option_string): if not self._has_negative_number_optionals: self._has_negative_number_optionals.append(True) # return the created action return action def _remove_action(self, action): self._actions.remove(action) def _add_container_actions(self, container): # collect groups by titles title_group_map = {} for group in self._action_groups: if group.title in title_group_map: msg = _('cannot merge actions - two groups are named %r') raise ValueError(msg % (group.title)) title_group_map[group.title] = group # map each action to its group group_map = {} for group in container._action_groups: # if a group with the title exists, use that, otherwise # create a new group matching the container's group if group.title not in title_group_map: title_group_map[group.title] = self.add_argument_group( title=group.title, description=group.description, conflict_handler=group.conflict_handler) # map the actions to their new group for action in group._group_actions: group_map[action] = title_group_map[group.title] # add container's mutually exclusive groups # NOTE: if add_mutually_exclusive_group ever gains title= and # description= then this code will need to be expanded as above for group in container._mutually_exclusive_groups: mutex_group = self.add_mutually_exclusive_group( required=group.required) # map the actions to their new mutex group for action in group._group_actions: group_map[action] = mutex_group # add all actions to this container or their group for action in container._actions: group_map.get(action, self)._add_action(action) def _get_positional_kwargs(self, dest, **kwargs): # make sure required is not specified if 'required' in kwargs: msg = _("'required' is an invalid argument for positionals") raise TypeError(msg) # mark positional arguments as required if at least one is # always required if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]: kwargs['required'] = True if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs: kwargs['required'] = True # return the keyword arguments with no option strings return dict(kwargs, dest=dest, option_strings=[]) def _get_optional_kwargs(self, *args, **kwargs): # determine short and long option strings option_strings = [] long_option_strings = [] for option_string in args: # error on strings that don't start with an appropriate prefix if not option_string[0] in self.prefix_chars: args = {'option': option_string, 'prefix_chars': self.prefix_chars} msg = _('invalid option string %(option)r: ' 'must start with a character %(prefix_chars)r') raise ValueError(msg % args) # strings starting with two prefix characters are long options option_strings.append(option_string) if option_string[0] in self.prefix_chars: if len(option_string) > 1: if option_string[1] in self.prefix_chars: long_option_strings.append(option_string) # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' dest = kwargs.pop('dest', None) if dest is None: if long_option_strings: dest_option_string = long_option_strings[0] else: dest_option_string = option_strings[0] dest = dest_option_string.lstrip(self.prefix_chars) if not dest: msg = _('dest= is required for options like %r') raise ValueError(msg % option_string) dest = dest.replace('-', '_') # return the updated keyword arguments return dict(kwargs, dest=dest, option_strings=option_strings) def _pop_action_class(self, kwargs, default=None): action = kwargs.pop('action', default) return self._registry_get('action', action, action) def _get_handler(self): # determine function from conflict handler string handler_func_name = '_handle_conflict_%s' % self.conflict_handler try: return getattr(self, handler_func_name) except AttributeError: msg = _('invalid conflict_resolution value: %r') raise ValueError(msg % self.conflict_handler) def _check_conflict(self, action): # find all options that conflict with this option confl_optionals = [] for option_string in action.option_strings: if option_string in self._option_string_actions: confl_optional = self._option_string_actions[option_string] confl_optionals.append((option_string, confl_optional)) # resolve any conflicts if confl_optionals: conflict_handler = self._get_handler() conflict_handler(action, confl_optionals) def _handle_conflict_error(self, action, conflicting_actions): message = ngettext('conflicting option string: %s', 'conflicting option strings: %s', len(conflicting_actions)) conflict_string = ', '.join([option_string for option_string, action in conflicting_actions]) raise ArgumentError(action, message % conflict_string) def _handle_conflict_resolve(self, action, conflicting_actions): # remove all conflicting options for option_string, action in conflicting_actions: # remove the conflicting option action.option_strings.remove(option_string) self._option_string_actions.pop(option_string, None) # if the option now has no option string, remove it from the # container holding it if not action.option_strings: action.container._remove_action(action) class _ArgumentGroup(_ActionsContainer): def __init__(self, container, title=None, description=None, **kwargs): # add any missing keyword arguments by checking the container update = kwargs.setdefault update('conflict_handler', container.conflict_handler) update('prefix_chars', container.prefix_chars) update('argument_default', container.argument_default) super_init = super(_ArgumentGroup, self).__init__ super_init(description=description, **kwargs) # group attributes self.title = title self._group_actions = [] # share most attributes with the container self._registries = container._registries self._actions = container._actions self._option_string_actions = container._option_string_actions self._defaults = container._defaults self._has_negative_number_optionals = \ container._has_negative_number_optionals self._mutually_exclusive_groups = container._mutually_exclusive_groups def _add_action(self, action): action = super(_ArgumentGroup, self)._add_action(action) self._group_actions.append(action) return action def _remove_action(self, action): super(_ArgumentGroup, self)._remove_action(action) self._group_actions.remove(action) class _MutuallyExclusiveGroup(_ArgumentGroup): def __init__(self, container, required=False): super(_MutuallyExclusiveGroup, self).__init__(container) self.required = required self._container = container def _add_action(self, action): if action.required: msg = _('mutually exclusive arguments must be optional') raise ValueError(msg) action = self._container._add_action(action) self._group_actions.append(action) return action def _remove_action(self, action): self._container._remove_action(action) self._group_actions.remove(action) class ArgumentParser(_AttributeHolder, _ActionsContainer): """Object for parsing command line strings into Python objects. Keyword Arguments: - prog -- The name of the program (default: sys.argv[0]) - usage -- A usage message (default: auto-generated from arguments) - description -- A description of what the program does - epilog -- Text following the argument descriptions - parents -- Parsers whose arguments should be copied into this one - formatter_class -- HelpFormatter class for printing help messages - prefix_chars -- Characters that prefix optional arguments - fromfile_prefix_chars -- Characters that prefix files containing additional arguments - argument_default -- The default value for all arguments - conflict_handler -- String indicating how to handle conflicts - add_help -- Add a -h/-help option """ def __init__(self, prog=None, usage=None, description=None, epilog=None, version=None, parents=[], formatter_class=HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True): if version is not None: import warnings warnings.warn( """The "version" argument to ArgumentParser is deprecated. """ """Please use """ """"add_argument(..., action='version', version="N", ...)" """ """instead""", DeprecationWarning) superinit = super(ArgumentParser, self).__init__ superinit(description=description, prefix_chars=prefix_chars, argument_default=argument_default, conflict_handler=conflict_handler) # default setting for prog if prog is None: prog = _os.path.basename(_sys.argv[0]) self.prog = prog self.usage = usage self.epilog = epilog self.version = version self.formatter_class = formatter_class self.fromfile_prefix_chars = fromfile_prefix_chars self.add_help = add_help add_group = self.add_argument_group self._positionals = add_group(_('positional arguments')) self._optionals = add_group(_('optional arguments')) self._subparsers = None # register types def identity(string): return string self.register('type', None, identity) # add help and version arguments if necessary # (using explicit default to override global argument_default) default_prefix = '-' if '-' in prefix_chars else prefix_chars[0] if self.add_help: self.add_argument( default_prefix+'h', default_prefix*2+'help', action='help', default=SUPPRESS, help=_('show this help message and exit')) if self.version: self.add_argument( default_prefix+'v', default_prefix*2+'version', action='version', default=SUPPRESS, version=self.version, help=_("show program's version number and exit")) # add parent arguments and defaults for parent in parents: self._add_container_actions(parent) try: defaults = parent._defaults except AttributeError: pass else: self._defaults.update(defaults) # ======================= # Pretty __repr__ methods # ======================= def _get_kwargs(self): names = [ 'prog', 'usage', 'description', 'version', 'formatter_class', 'conflict_handler', 'add_help', ] return [(name, getattr(self, name)) for name in names] # ================================== # Optional/Positional adding methods # ================================== def add_subparsers(self, **kwargs): if self._subparsers is not None: self.error(_('cannot have multiple subparser arguments')) # add the parser class to the arguments if it's not present kwargs.setdefault('parser_class', type(self)) if 'title' in kwargs or 'description' in kwargs: title = _(kwargs.pop('title', 'subcommands')) description = _(kwargs.pop('description', None)) self._subparsers = self.add_argument_group(title, description) else: self._subparsers = self._positionals # prog defaults to the usage message of this parser, skipping # optional arguments and with no "usage:" prefix if kwargs.get('prog') is None: formatter = self._get_formatter() positionals = self._get_positional_actions() groups = self._mutually_exclusive_groups formatter.add_usage(self.usage, positionals, groups, '') kwargs['prog'] = formatter.format_help().strip() # create the parsers action and add it to the positionals list parsers_class = self._pop_action_class(kwargs, 'parsers') action = parsers_class(option_strings=[], **kwargs) self._subparsers._add_action(action) # return the created parsers action return action def _add_action(self, action): if action.option_strings: self._optionals._add_action(action) else: self._positionals._add_action(action) return action def _get_optional_actions(self): return [action for action in self._actions if action.option_strings] def _get_positional_actions(self): return [action for action in self._actions if not action.option_strings] # ===================================== # Command line argument parsing methods # ===================================== def parse_args(self, args=None, namespace=None): args, argv = self.parse_known_args(args, namespace) if argv: msg = _('unrecognized arguments: %s') self.error(msg % ' '.join(argv)) return args def parse_known_args(self, args=None, namespace=None): # args default to the system args if args is None: args = _sys.argv[1:] # default Namespace built from parser defaults if namespace is None: namespace = Namespace() # add any action defaults that aren't present for action in self._actions: if action.dest is not SUPPRESS: if not hasattr(namespace, action.dest): if action.default is not SUPPRESS: default = action.default if isinstance(action.default, str): default = self._get_value(action, default) setattr(namespace, action.dest, default) # add any parser defaults that aren't present for dest in self._defaults: if not hasattr(namespace, dest): setattr(namespace, dest, self._defaults[dest]) # parse the arguments and exit if there are any errors try: namespace, args = self._parse_known_args(args, namespace) if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) return namespace, args except ArgumentError: err = _sys.exc_info()[1] self.error(str(err)) def _parse_known_args(self, arg_strings, namespace): # replace arg strings that are file references if self.fromfile_prefix_chars is not None: arg_strings = self._read_args_from_files(arg_strings) # map all mutually exclusive arguments to the other arguments # they can't occur with action_conflicts = {} for mutex_group in self._mutually_exclusive_groups: group_actions = mutex_group._group_actions for i, mutex_action in enumerate(mutex_group._group_actions): conflicts = action_conflicts.setdefault(mutex_action, []) conflicts.extend(group_actions[:i]) conflicts.extend(group_actions[i + 1:]) # find all option indices, and determine the arg_string_pattern # which has an 'O' if there is an option at an index, # an 'A' if there is an argument, or a '-' if there is a '--' option_string_indices = {} arg_string_pattern_parts = [] arg_strings_iter = iter(arg_strings) for i, arg_string in enumerate(arg_strings_iter): # all args after -- are non-options if arg_string == '--': arg_string_pattern_parts.append('-') for arg_string in arg_strings_iter: arg_string_pattern_parts.append('A') # otherwise, add the arg to the arg strings # and note the index if it was an option else: option_tuple = self._parse_optional(arg_string) if option_tuple is None: pattern = 'A' else: option_string_indices[i] = option_tuple pattern = 'O' arg_string_pattern_parts.append(pattern) # join the pieces together to form the pattern arg_strings_pattern = ''.join(arg_string_pattern_parts) # converts arg strings to the appropriate and then takes the action seen_actions = set() seen_non_default_actions = set() def take_action(action, argument_strings, option_string=None): seen_actions.add(action) argument_values = self._get_values(action, argument_strings) # error if this argument is not allowed with other previously # seen arguments, assuming that actions that use the default # value don't really count as "present" if argument_values is not action.default: seen_non_default_actions.add(action) for conflict_action in action_conflicts.get(action, []): if conflict_action in seen_non_default_actions: msg = _('not allowed with argument %s') action_name = _get_action_name(conflict_action) raise ArgumentError(action, msg % action_name) # take the action if we didn't receive a SUPPRESS value # (e.g. from a default) if argument_values is not SUPPRESS: action(self, namespace, argument_values, option_string) # function to convert arg_strings into an optional action def consume_optional(start_index): # get the optional identified at this index option_tuple = option_string_indices[start_index] action, option_string, explicit_arg = option_tuple # identify additional optionals in the same arg string # (e.g. -xyz is the same as -x -y -z if no args are required) match_argument = self._match_argument action_tuples = [] while True: # if we found no optional action, skip it if action is None: extras.append(arg_strings[start_index]) return start_index + 1 # if there is an explicit argument, try to match the # optional's string arguments to only this if explicit_arg is not None: arg_count = match_argument(action, 'A') # if the action is a single-dash option and takes no # arguments, try to parse more single-dash options out # of the tail of the option string chars = self.prefix_chars if arg_count == 0 and option_string[1] not in chars: action_tuples.append((action, [], option_string)) char = option_string[0] option_string = char + explicit_arg[0] new_explicit_arg = explicit_arg[1:] or None optionals_map = self._option_string_actions if option_string in optionals_map: action = optionals_map[option_string] explicit_arg = new_explicit_arg else: msg = _('ignored explicit argument %r') raise ArgumentError(action, msg % explicit_arg) # if the action expect exactly one argument, we've # successfully matched the option; exit the loop elif arg_count == 1: stop = start_index + 1 args = [explicit_arg] action_tuples.append((action, args, option_string)) break # error if a double-dash option did not use the # explicit argument else: msg = _('ignored explicit argument %r') raise ArgumentError(action, msg % explicit_arg) # if there is no explicit argument, try to match the # optional's string arguments with the following strings # if successful, exit the loop else: start = start_index + 1 selected_patterns = arg_strings_pattern[start:] arg_count = match_argument(action, selected_patterns) stop = start + arg_count args = arg_strings[start:stop] action_tuples.append((action, args, option_string)) break # add the Optional to the list and return the index at which # the Optional's string args stopped assert action_tuples for action, args, option_string in action_tuples: take_action(action, args, option_string) return stop # the list of Positionals left to be parsed; this is modified # by consume_positionals() positionals = self._get_positional_actions() # function to convert arg_strings into positional actions def consume_positionals(start_index): # match as many Positionals as possible match_partial = self._match_arguments_partial selected_pattern = arg_strings_pattern[start_index:] arg_counts = match_partial(positionals, selected_pattern) # slice off the appropriate arg strings for each Positional # and add the Positional and its args to the list for action, arg_count in zip(positionals, arg_counts): args = arg_strings[start_index: start_index + arg_count] start_index += arg_count take_action(action, args) # slice off the Positionals that we just parsed and return the # index at which the Positionals' string args stopped positionals[:] = positionals[len(arg_counts):] return start_index # consume Positionals and Optionals alternately, until we have # passed the last option string extras = [] start_index = 0 if option_string_indices: max_option_string_index = max(option_string_indices) else: max_option_string_index = -1 while start_index <= max_option_string_index: # consume any Positionals preceding the next option next_option_string_index = min([ index for index in option_string_indices if index >= start_index]) if start_index != next_option_string_index: positionals_end_index = consume_positionals(start_index) # only try to parse the next optional if we didn't consume # the option string during the positionals parsing if positionals_end_index > start_index: start_index = positionals_end_index continue else: start_index = positionals_end_index # if we consumed all the positionals we could and we're not # at the index of an option string, there were extra arguments if start_index not in option_string_indices: strings = arg_strings[start_index:next_option_string_index] extras.extend(strings) start_index = next_option_string_index # consume the next optional and any arguments for it start_index = consume_optional(start_index) # consume any positionals following the last Optional stop_index = consume_positionals(start_index) # if we didn't consume all the argument strings, there were extras extras.extend(arg_strings[stop_index:]) # if we didn't use all the Positional objects, there were too few # arg strings supplied. if positionals: self.error(_('too few arguments')) # make sure all required actions were present for action in self._actions: if action.required: if action not in seen_actions: name = _get_action_name(action) self.error(_('argument %s is required') % name) # make sure all required groups had one option present for group in self._mutually_exclusive_groups: if group.required: for action in group._group_actions: if action in seen_non_default_actions: break # if no actions were used, report the error else: names = [_get_action_name(action) for action in group._group_actions if action.help is not SUPPRESS] msg = _('one of the arguments %s is required') self.error(msg % ' '.join(names)) # return the updated namespace and the extra arguments return namespace, extras def _read_args_from_files(self, arg_strings): # expand arguments referencing files new_arg_strings = [] for arg_string in arg_strings: # for regular arguments, just add them back into the list if arg_string[0] not in self.fromfile_prefix_chars: new_arg_strings.append(arg_string) # replace arguments referencing files with the file content else: try: args_file = open(arg_string[1:]) try: arg_strings = [] for arg_line in args_file.read().splitlines(): for arg in self.convert_arg_line_to_args(arg_line): arg_strings.append(arg) arg_strings = self._read_args_from_files(arg_strings) new_arg_strings.extend(arg_strings) finally: args_file.close() except IOError: err = _sys.exc_info()[1] self.error(str(err)) # return the modified argument list return new_arg_strings def convert_arg_line_to_args(self, arg_line): return [arg_line] def _match_argument(self, action, arg_strings_pattern): # match the pattern for this action to the arg strings nargs_pattern = self._get_nargs_pattern(action) match = _re.match(nargs_pattern, arg_strings_pattern) # raise an exception if we weren't able to find a match if match is None: nargs_errors = { None: _('expected one argument'), OPTIONAL: _('expected at most one argument'), ONE_OR_MORE: _('expected at least one argument'), } default = ngettext('expected %s argument', 'expected %s arguments', action.nargs) % action.nargs msg = nargs_errors.get(action.nargs, default) raise ArgumentError(action, msg) # return the number of arguments matched return len(match.group(1)) def _match_arguments_partial(self, actions, arg_strings_pattern): # progressively shorten the actions list by slicing off the # final actions until we find a match result = [] for i in range(len(actions), 0, -1): actions_slice = actions[:i] pattern = ''.join([self._get_nargs_pattern(action) for action in actions_slice]) match = _re.match(pattern, arg_strings_pattern) if match is not None: result.extend([len(string) for string in match.groups()]) break # return the list of arg string counts return result def _parse_optional(self, arg_string): # if it's an empty string, it was meant to be a positional if not arg_string: return None # if it doesn't start with a prefix, it was meant to be positional if not arg_string[0] in self.prefix_chars: return None # if the option string is present in the parser, return the action if arg_string in self._option_string_actions: action = self._option_string_actions[arg_string] return action, arg_string, None # if it's just a single character, it was meant to be positional if len(arg_string) == 1: return None # if the option string before the "=" is present, return the action if '=' in arg_string: option_string, explicit_arg = arg_string.split('=', 1) if option_string in self._option_string_actions: action = self._option_string_actions[option_string] return action, option_string, explicit_arg # search through all possible prefixes of the option string # and all actions in the parser for possible interpretations option_tuples = self._get_option_tuples(arg_string) # if multiple actions match, the option string was ambiguous if len(option_tuples) > 1: options = ', '.join([option_string for action, option_string, explicit_arg in option_tuples]) args = {'option': arg_string, 'matches': options} msg = _('ambiguous option: %(option)s could match %(matches)s') self.error(msg % args) # if exactly one action matched, this segmentation is good, # so return the parsed action elif len(option_tuples) == 1: option_tuple, = option_tuples return option_tuple # if it was not found as an option, but it looks like a negative # number, it was meant to be positional # unless there are negative-number-like options if self._negative_number_matcher.match(arg_string): if not self._has_negative_number_optionals: return None # if it contains a space, it was meant to be a positional if ' ' in arg_string: return None # it was meant to be an optional but there is no such option # in this parser (though it might be a valid option in a subparser) return None, arg_string, None def _get_option_tuples(self, option_string): result = [] # option strings starting with two prefix characters are only # split at the '=' chars = self.prefix_chars if option_string[0] in chars and option_string[1] in chars: if '=' in option_string: option_prefix, explicit_arg = option_string.split('=', 1) else: option_prefix = option_string explicit_arg = None for option_string in self._option_string_actions: if option_string.startswith(option_prefix): action = self._option_string_actions[option_string] tup = action, option_string, explicit_arg result.append(tup) # single character options can be concatenated with their arguments # but multiple character options always have to have their argument # separate elif option_string[0] in chars and option_string[1] not in chars: option_prefix = option_string explicit_arg = None short_option_prefix = option_string[:2] short_explicit_arg = option_string[2:] for option_string in self._option_string_actions: if option_string == short_option_prefix: action = self._option_string_actions[option_string] tup = action, option_string, short_explicit_arg result.append(tup) elif option_string.startswith(option_prefix): action = self._option_string_actions[option_string] tup = action, option_string, explicit_arg result.append(tup) # shouldn't ever get here else: self.error(_('unexpected option string: %s') % option_string) # return the collected option tuples return result def _get_nargs_pattern(self, action): # in all examples below, we have to allow for '--' args # which are represented as '-' in the pattern nargs = action.nargs # the default (None) is assumed to be a single argument if nargs is None: nargs_pattern = '(-*A-*)' # allow zero or one arguments elif nargs == OPTIONAL: nargs_pattern = '(-*A?-*)' # allow zero or more arguments elif nargs == ZERO_OR_MORE: nargs_pattern = '(-*[A-]*)' # allow one or more arguments elif nargs == ONE_OR_MORE: nargs_pattern = '(-*A[A-]*)' # allow any number of options or arguments elif nargs == REMAINDER: nargs_pattern = '([-AO]*)' # allow one argument followed by any number of options or arguments elif nargs == PARSER: nargs_pattern = '(-*A[-AO]*)' # all others should be integers else: nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) # if this is an optional action, -- is not allowed if action.option_strings: nargs_pattern = nargs_pattern.replace('-*', '') nargs_pattern = nargs_pattern.replace('-', '') # return the pattern return nargs_pattern # ======================== # Value conversion methods # ======================== def _get_values(self, action, arg_strings): # for everything but PARSER args, strip out '--' if action.nargs not in [PARSER, REMAINDER]: arg_strings = [s for s in arg_strings if s != '--'] # optional argument produces a default when not present if not arg_strings and action.nargs == OPTIONAL: if action.option_strings: value = action.const else: value = action.default if isinstance(value, str): value = self._get_value(action, value) self._check_value(action, value) # when nargs='*' on a positional, if there were no command-line # args, use the default if it is anything other than None elif (not arg_strings and action.nargs == ZERO_OR_MORE and not action.option_strings): if action.default is not None: value = action.default else: value = arg_strings self._check_value(action, value) # single argument or optional argument produces a single value elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: arg_string, = arg_strings value = self._get_value(action, arg_string) self._check_value(action, value) # REMAINDER arguments convert all values, checking none elif action.nargs == REMAINDER: value = [self._get_value(action, v) for v in arg_strings] # PARSER arguments convert all values, but check only the first elif action.nargs == PARSER: value = [self._get_value(action, v) for v in arg_strings] self._check_value(action, value[0]) # all other types of nargs produce a list else: value = [self._get_value(action, v) for v in arg_strings] for v in value: self._check_value(action, v) # return the converted value return value def _get_value(self, action, arg_string): type_func = self._registry_get('type', action.type, action.type) if not _callable(type_func): msg = _('%r is not callable') raise ArgumentError(action, msg % type_func) # convert the value to the appropriate type try: result = type_func(arg_string) # ArgumentTypeErrors indicate errors except ArgumentTypeError: name = getattr(action.type, '__name__', repr(action.type)) msg = str(_sys.exc_info()[1]) raise ArgumentError(action, msg) # TypeErrors or ValueErrors also indicate errors except (TypeError, ValueError): name = getattr(action.type, '__name__', repr(action.type)) args = {'type': name, 'value': arg_string} msg = _('invalid %(type)s value: %(value)r') raise ArgumentError(action, msg % args) # return the converted value return result def _check_value(self, action, value): # converted value must be one of the choices (if specified) if action.choices is not None and value not in action.choices: args = {'value': value, 'choices': ', '.join(map(repr, action.choices))} msg = _('invalid choice: %(value)r (choose from %(choices)s)') raise ArgumentError(action, msg % args) # ======================= # Help-formatting methods # ======================= def format_usage(self): formatter = self._get_formatter() formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups) return formatter.format_help() def format_help(self): formatter = self._get_formatter() # usage formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups) # description formatter.add_text(self.description) # positionals, optionals and user-defined groups for action_group in self._action_groups: formatter.start_section(action_group.title) formatter.add_text(action_group.description) formatter.add_arguments(action_group._group_actions) formatter.end_section() # epilog formatter.add_text(self.epilog) # determine help from format above return formatter.format_help() def format_version(self): import warnings warnings.warn( 'The format_version method is deprecated -- the "version" ' 'argument to ArgumentParser is no longer supported.', DeprecationWarning) formatter = self._get_formatter() formatter.add_text(self.version) return formatter.format_help() def _get_formatter(self): return self.formatter_class(prog=self.prog) # ===================== # Help-printing methods # ===================== def print_usage(self, file=None): if file is None: file = _sys.stdout self._print_message(self.format_usage(), file) def print_help(self, file=None): if file is None: file = _sys.stdout self._print_message(self.format_help(), file) def print_version(self, file=None): import warnings warnings.warn( 'The print_version method is deprecated -- the "version" ' 'argument to ArgumentParser is no longer supported.', DeprecationWarning) self._print_message(self.format_version(), file) def _print_message(self, message, file=None): if message: if file is None: file = _sys.stderr file.write(message) # =============== # Exiting methods # =============== def exit(self, status=0, message=None): if message: self._print_message(message, _sys.stderr) _sys.exit(status) def error(self, message): """error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(_sys.stderr) args = {'prog': self.prog, 'message': message} self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
sassoftware/rbm
refs/heads/master
upsrv/url_sign.py
1
# # Copyright (c) SAS Institute 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. # """ Sign URLs in a way that can be validated by any mirror with the right key, without shared state. The following query parameters are added to the URL during signing: * e - When the URL expires, in seconds since the UNIX epoch * s - The actual signature. Must come last. """ import hashlib import hmac import time import urlparse from pyramid.util import strings_differ def sign_path(cfg, path): if not cfg.downloadSignatureKey: raise RuntimeError("At least one downloadSignatureKey must be configured") expires = int(time.time() + cfg.downloadSignatureExpiry) path += ('&' if '?' in path else '?') + 'e=%d' % expires mac = hmac.new(cfg.downloadSignatureKey[0], path, hashlib.sha1) path += '&s=' + mac.hexdigest() return path def verify_request(cfg, request): # Reconstruct the original path. Discard any query parameters that come # after the signature, because they can't be trusted. query = request.query_string if '&s=' not in query: # No signature return False query, sig = query.split('&s=', 1) sig = sig.split('&')[0].split(';')[0] path = request.path_info + '?' + query # Try all configured keys to find a match if not cfg.downloadSignatureKey: raise RuntimeError("At least one downloadSignatureKey must be configured") found = False for key in cfg.downloadSignatureKey: sig2 = hmac.new(key, path, hashlib.sha1).hexdigest() # Use constant-time comparison to avoid timing attacks. if not strings_differ(sig, sig2): found = True break if not found: # Signature not valid return False # Now look at the query parameters and ensure that all constraints are met. for name, value in urlparse.parse_qsl(query): if name == 'e': # Expiration expiry = int(value) if time.time() > expiry: return False # Everything checks out, return the constraints to the caller for # verification return True
mohamed--abdel-maksoud/chromium.src
refs/heads/nw12
chrome/test/ispy/common/mock_cloud_bucket.py
122
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Subclass of CloudBucket used for testing.""" import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) import cloud_bucket class MockCloudBucket(cloud_bucket.BaseCloudBucket): """Subclass of CloudBucket used for testing.""" def __init__(self): """Initializes the MockCloudBucket with its datastore. Returns: An instance of MockCloudBucket. """ self.datastore = {} def Reset(self): """Clears the MockCloudBucket's datastore.""" self.datastore = {} # override def UploadFile(self, path, contents, content_type): self.datastore[path] = contents # override def DownloadFile(self, path): if self.datastore.has_key(path): return self.datastore[path] else: raise cloud_bucket.FileNotFoundError # override def UpdateFile(self, path, contents): if not self.FileExists(path): raise cloud_bucket.FileNotFoundError self.UploadFile(path, contents, '') # override def RemoveFile(self, path): if self.datastore.has_key(path): self.datastore.pop(path) # override def FileExists(self, path): return self.datastore.has_key(path) # override def GetImageURL(self, path): if self.datastore.has_key(path): return path else: raise cloud_bucket.FileNotFoundError # override def GetAllPaths(self, prefix): return (item[0] for item in self.datastore.items() if item[0].startswith(prefix))
vbelakov/h2o
refs/heads/master
py/testdir_single_jvm/test_NN2_mnist.py
9
import unittest, time, sys, random, string sys.path.extend(['.','..','../..','py']) import h2o, h2o_gbm, h2o_cmd, h2o_import as h2i, h2o_browse as h2b class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): h2o.init(java_heap_GB=2) @classmethod def tearDownClass(cls): ###h2o.sleep(3600) h2o.tear_down_cloud() def test_NN_mnist(self): #h2b.browseTheCloud() csvPathname_train = 'mnist/train.csv.gz' csvPathname_test = 'mnist/test.csv.gz' hex_key = 'mnist_train.hex' validation_key = 'mnist_test.hex' timeoutSecs = 30 parseResult = h2i.import_parse(bucket='smalldata', path=csvPathname_train, schema='put', hex_key=hex_key, timeoutSecs=timeoutSecs) parseResultV = h2i.import_parse(bucket='smalldata', path=csvPathname_test, schema='put', hex_key=validation_key, timeoutSecs=timeoutSecs) inspect = h2o_cmd.runInspect(None, hex_key) print "\n" + csvPathname_train, \ " numRows:", "{:,}".format(inspect['numRows']), \ " numCols:", "{:,}".format(inspect['numCols']) response = inspect['numCols'] - 1 #Making random id identifier = ''.join(random.sample(string.ascii_lowercase + string.digits, 10)) model_key = 'nn_' + identifier + '.hex' kwargs = { 'ignored_cols' : None, 'response' : response, 'classification' : 1, 'activation' : 'RectifierWithDropout', 'input_dropout_ratio' : 0.2, 'hidden' : '117,131,129', 'adaptive_rate' : 0, 'rate' : 0.005, 'rate_annealing' : 1e-6, 'momentum_start' : 0.5, 'momentum_ramp' : 100000, 'momentum_stable' : 0.9, 'l1' : 0.00001, 'l2' : 0.0000001, 'seed' : 98037452452, 'loss' : 'CrossEntropy', 'max_w2' : 15, 'initial_weight_distribution' : 'UniformAdaptive', #'initial_weight_scale' : 0.01, 'epochs' : 2.0, 'destination_key' : model_key, 'validation' : validation_key, 'score_interval' : 10000 } expectedErr = 0.057 ## expected validation error for the above model relTol = 0.20 ## 20% rel. error tolerance due to Hogwild! timeoutSecs = 600 start = time.time() nn = h2o_cmd.runDeepLearning(parseResult=parseResult, timeoutSecs=timeoutSecs, **kwargs) print "neural net end on ", csvPathname_train, " and ", csvPathname_test, 'took', time.time() - start, 'seconds' predict_key = 'score_' + identifier + '.hex' kwargs = { 'data_key': validation_key, 'destination_key': predict_key, 'model_key': model_key } predictResult = h2o_cmd.runPredict(timeoutSecs=timeoutSecs, **kwargs) h2o_cmd.runInspect(key=predict_key, verbose=True) kwargs = { } predictCMResult = h2o.nodes[0].predict_confusion_matrix( actual=validation_key, vactual=response, predict=predict_key, vpredict='predict', timeoutSecs=timeoutSecs, **kwargs) cm = predictCMResult['cm'] print h2o_gbm.pp_cm(cm) actualErr = h2o_gbm.pp_cm_summary(cm)/100.; print "actual classification error:" + format(actualErr) print "expected classification error:" + format(expectedErr) if actualErr != expectedErr and abs((expectedErr - actualErr)/expectedErr) > relTol: raise Exception("Scored classification error of %s is not within %s %% relative error of %s" % (actualErr, float(relTol)*100, expectedErr)) if __name__ == '__main__': h2o.unit_main()
rousseab/pymatgen
refs/heads/master
pymatgen/io/cif.py
1
# coding: utf-8 from __future__ import division, unicode_literals """ Wrapper classes for Cif input and output from Structures. """ __author__ = "Shyue Ping Ong, Will Richards" __copyright__ = "Copyright 2011, The Materials Project" __version__ = "3.0" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __status__ = "Production" __date__ = "Sep 23, 2011" import math import re import textwrap import warnings from collections import OrderedDict, deque import six from six.moves import zip, cStringIO import numpy as np from functools import partial from inspect import getargspec from itertools import groupby from pymatgen.core.periodic_table import Element, Specie, get_el_sp, PeriodicTable from monty.io import zopen from pymatgen.util.coord_utils import in_coord_list_pbc from monty.string import remove_non_ascii from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.core.composition import Composition from pymatgen.core.operations import SymmOp from pymatgen.symmetry.groups import SpaceGroup, SYMM_DATA, TRANSLATIONS from pymatgen.symmetry.analyzer import SpacegroupAnalyzer ptable = PeriodicTable() sub_spgrp = partial(re.sub, r"[\s_]", "") space_groups = {sub_spgrp(k): k for k in SYMM_DATA['space_group_encoding'].keys()} space_groups.update({sub_spgrp(k): k for k in SYMM_DATA['space_group_encoding'].keys()}) class CifBlock(object): maxlen = 70 # not quite 80 so we can deal with semicolons and things def __init__(self, data, loops, header): """ Object for storing cif data. All data is stored in a single dictionary. Data inside loops are stored in lists in the data dictionary, and information on which keys are grouped together are stored in the loops attribute. Args: data: dict or OrderedDict of data to go into the cif. Values should be convertible to string, or lists of these if the key is in a loop loops: list of lists of keys, grouped by which loop they should appear in header: name of the block (appears after the data_ on the first line) """ self.loops = loops self.data = data # AJ says: CIF Block names cannot be more than 75 characters or you # get an Exception self.header = header[:74] def __getitem__(self, key): return self.data[key] def __str__(self): """ Returns the cif string for the data block """ s = ["data_{}".format(self.header)] keys = self.data.keys() written = [] for k in keys: if k in written: continue for l in self.loops: #search for a corresponding loop if k in l: s.append(self._loop_to_string(l)) written.extend(l) break if k not in written: #k didn't belong to a loop v = self._format_field(self.data[k]) if len(k) + len(v) + 3 < self.maxlen: s.append("{} {}".format(k, v)) else: s.extend([k, v]) return "\n".join(s) def _loop_to_string(self, loop): s = "loop_" for l in loop: s += '\n ' + l for fields in zip(*[self.data[k] for k in loop]): line = "\n" for val in map(self._format_field, fields): if val[0] == ";": s += line + "\n" + val line = "\n" elif len(line) + len(val) + 2 < self.maxlen: line += " " + val else: s += line line = '\n ' + val s += line return s def _format_field(self, v): v = v.__str__().strip() if len(v) > self.maxlen: return ';\n' + textwrap.fill(v, self.maxlen) + '\n;' #add quotes if necessary if (" " in v or v[0] == "_") \ and not (v[0] == "'" and v[-1] == "'") \ and not (v[0] == '"' and v[-1] == '"'): if "'" in v: q = '"' else: q = "'" v = q + v + q return v @classmethod def _process_string(cls, string): #remove comments string = re.sub("(\s|^)#.*$", "", string, flags=re.MULTILINE) #remove empty lines string = re.sub("^\s*\n", "", string, flags=re.MULTILINE) #remove non_ascii string = remove_non_ascii(string) #since line breaks in .cif files are mostly meaningless, #break up into a stream of tokens to parse, rejoining multiline #strings (between semicolons) q = deque() multiline = False ml = [] # this regex splits on spaces, except when in quotes. # starting quotes must not be preceded by non-whitespace # (these get eaten by the first expression) # ending quotes must not be followed by non-whitespace p = re.compile(r'''([^'"\s][\S]*)|'(.*?)'(?!\S)|"(.*?)"(?!\S)''') for l in string.splitlines(): if multiline: if l.startswith(";"): multiline = False q.append(" ".join(ml)) ml = [] l = l[1:].strip() else: ml.append(l) continue if l.startswith(";"): multiline = True ml.append(l[1:].strip()) else: for s in p.findall(l): # s is tuple. location of the data in the tuple # depends on whether it was quoted in the input q.append(s) return q @classmethod def from_string(cls, string): q = cls._process_string(string) header = q.popleft()[0][5:] data = OrderedDict() loops = [] while q: s = q.popleft() # cif keys aren't in quotes, so show up in s[0] if s[0] == "_eof": break if s[0].startswith("_"): data[s[0]] = "".join(q.popleft()) elif s[0].startswith("loop_"): columns = [] items = [] while q: s = q[0] if s[0].startswith("loop_") or not s[0].startswith("_"): break columns.append("".join(q.popleft())) data[columns[-1]] = [] while q: s = q[0] if s[0].startswith("loop_") or s[0].startswith("_"): break items.append("".join(q.popleft())) n = len(items) // len(columns) assert len(items) % n == 0 loops.append(columns) for k, v in zip(columns * n, items): data[k].append(v.strip()) elif "".join(s).strip() != "": warnings.warn("Possible error in cif format" " error at {}".format("".join(s).strip())) return cls(data, loops, header) class CifFile(object): """ Reads and parses CifBlocks from a .cif file """ def __init__(self, data, orig_string=None): """ Args: data: OrderedDict of CifBlock objects string: The original cif string """ self.data = data self.orig_string = orig_string def __str__(self): s = ["%s" % v for v in self.data.values()] comment = "#generated using pymatgen\n" return comment + "\n".join(s)+"\n" @classmethod def from_string(cls, string): d = OrderedDict() for x in re.split("^\s*data_", "x\n"+string, flags=re.MULTILINE | re.DOTALL)[1:]: c = CifBlock.from_string("data_"+x) d[c.header] = c return cls(d, string) @classmethod def from_file(cls, filename): with zopen(filename, "rt") as f: return cls.from_string(f.read()) class CifParser(object): """ Parses a cif file Args: filename (str): Cif filename. bzipped or gzipped cifs are fine too. occupancy_tolerance (float): If total occupancy of a site is between 1 and occupancy_tolerance, the occupancies will be scaled down to 1. """ def __init__(self, filename, occupancy_tolerance=1.): self._occupancy_tolerance = occupancy_tolerance if isinstance(filename, six.string_types): self._cif = CifFile.from_file(filename) else: self._cif = CifFile.from_string(filename.read()) @staticmethod def from_string(cif_string, occupancy_tolerance=1.): """ Creates a CifParser from a string. Args: cif_string (str): String representation of a CIF. occupancy_tolerance (float): If total occupancy of a site is between 1 and occupancy_tolerance, the occupancies will be scaled down to 1. Returns: CifParser """ stream = cStringIO(cif_string) return CifParser(stream, occupancy_tolerance) def _unique_coords(self, coords_in): """ Generate unique coordinates using coord and symmetry positions. """ coords = [] for tmp_coord in coords_in: for op in self.symmetry_operations: coord = op.operate(tmp_coord) coord = np.array([i - math.floor(i) for i in coord]) if not in_coord_list_pbc(coords, coord, atol=1e-3): coords.append(coord) return coords def get_lattice(self, data, length_strings=("a", "b", "c"), angle_strings=("alpha", "beta", "gamma"), lattice_type=None): """ Generate the lattice from the provided lattice parameters. In the absence of all six lattice parameters, the crystal system and necessary parameters are parsed """ try: lengths = [str2float(data["_cell_length_" + i]) for i in length_strings] angles = [str2float(data["_cell_angle_" + i]) for i in angle_strings] if not lattice_type: return Lattice.from_lengths_and_angles(lengths, angles) else: return getattr(Lattice, lattice_type)(*(lengths+angles)) except KeyError: #Missing Key search for cell setting for lattice_lable in ["_symmetry_cell_setting", "_space_group_crystal_system"]: if data.data.get(lattice_lable): lattice_type = data.data.get(lattice_lable).lower() try: required_args = getargspec(getattr(Lattice, lattice_type) ).args lengths = (l for l in length_strings if l in required_args) angles = (a for a in angle_strings if a in required_args) return self.get_lattice(data, lengths, angles, lattice_type=lattice_type) except AttributeError as exc: warnings.warn(exc) else: return None def get_symops(self, data): """ In order to generate symmetry equivalent positions, the symmetry operations are parsed. If the symops are not present, the space group symbol is parsed, and symops are generated. """ symops = [] for symmetry_label in ["_symmetry_equiv_pos_as_xyz", "_symmetry_equiv_pos_as_xyz_", "_space_group_symop_operation_xyz", "_space_group_symop_operation_xyz_"]: if data.data.get(symmetry_label): try: symops = [SymmOp.from_xyz_string(s) for s in data.data.get(symmetry_label)] break except ValueError: continue if not symops: # Try to parse symbol for symmetry_label in ["_symmetry_space_group_name_H-M", "_symmetry_space_group_name_H_M", "_symmetry_space_group_name_H-M_", "_symmetry_space_group_name_H_M_", "_space_group_name_Hall", "_space_group_name_Hall_", "_space_group_name_H-M_alt", "_space_group_name_H-M_alt_", "_symmetry_space_group_name_hall", "_symmetry_space_group_name_hall_", "_symmetry_space_group_name_h-m", "_symmetry_space_group_name_h-m_"]: if data.data.get(symmetry_label): try: spg = space_groups.get(sub_spgrp( data.data.get(symmetry_label))) if spg: symops = SpaceGroup(spg).symmetry_ops break except ValueError: continue if not symops: # Try to parse International number for symmetry_label in ["_space_group_IT_number", "_space_group_IT_number_", "_symmetry_Int_Tables_number", "_symmetry_Int_Tables_number_"]: if data.data.get(symmetry_label): try: symops = SpaceGroup.from_int_number(str2float( data.data.get(symmetry_label))).symmetry_ops break except ValueError: continue if not symops: warnings.warn("No _symmetry_equiv_pos_as_xyz type key found. " "Defaulting to P1.") symops = [SymmOp.from_xyz_string(s) for s in ['x', 'y', 'z']] return symops def parse_oxi_states(self, data): """ Parse oxidation states from data dictionary """ try: oxi_states = { data["_atom_type_symbol"][i]: str2float(data["_atom_type_oxidation_number"][i]) for i in range(len(data["_atom_type_symbol"]))} #attempt to strip oxidation state from _atom_type_symbol # in case the label does not contain an oxidation state for i, symbol in enumerate(data["_atom_type_symbol"]): oxi_states[re.sub(r"\d?[\+,\-]?$", "", symbol)] = \ str2float(data["_atom_type_oxidation_number"][i]) except (ValueError, KeyError): oxi_states = None return oxi_states def _get_structure(self, data, primitive, substitution_dictionary=None): """ Generate structure from part of the cif. """ # Symbols often representing #common representations for elements/water in cif files special_symbols = {"D":"D", "Hw":"H", "Ow":"O", "Wat":"O", "wat": "O"} elements = map(str, ptable.all_elements) lattice = self.get_lattice(data) self.symmetry_operations = self.get_symops(data) oxi_states = self.parse_oxi_states(data) coord_to_species = OrderedDict() def parse_symbol(sym): if substitution_dictionary: return substitution_dictionary.get(sym) else: m = re.findall(r"w?[A-Z][a-z]*", sym) if m and m != "?": return m[0] return "" for i in range(len(data["_atom_site_label"])): symbol = parse_symbol(data["_atom_site_label"][i]) if symbol: if symbol not in elements and symbol not in special_symbols: symbol = symbol[:2] else: continue # make sure symbol was properly parsed from _atom_site_label # otherwise get it from _atom_site_type_symbol try: if symbol in special_symbols: get_el_sp(special_symbols.get(symbol)) else: Element(symbol) except KeyError: # sometimes the site doesn't have the type_symbol. # we then hope the type_symbol can be parsed from the label if "_atom_site_type_symbol" in data.data.keys(): symbol = data["_atom_site_type_symbol"][i] if oxi_states is not None: if symbol in special_symbols: el = get_el_sp(special_symbols.get(symbol) + str(oxi_states[symbol])) else: el = Specie(symbol, oxi_states.get(symbol, 0)) else: el = get_el_sp(special_symbols.get(symbol) if \ symbol in special_symbols else symbol) x = str2float(data["_atom_site_fract_x"][i]) y = str2float(data["_atom_site_fract_y"][i]) z = str2float(data["_atom_site_fract_z"][i]) try: occu = str2float(data["_atom_site_occupancy"][i]) except (KeyError, ValueError): occu = 1 if occu > 0: coord = (x, y, z) if coord not in coord_to_species: coord_to_species[coord] = {el: occu} else: coord_to_species[coord][el] = occu coord_to_species = {k: Composition(v) for k, v in coord_to_species.items()} allspecies = [] allcoords = [] if coord_to_species.items(): for species, group in groupby( sorted(list(coord_to_species.items()), key=lambda x: x[1]), key=lambda x: x[1]): tmp_coords = [site[0] for site in group] coords = self._unique_coords(tmp_coords) allcoords.extend(coords) allspecies.extend(len(coords) * [species]) #rescale occupancies if necessary for species in allspecies: totaloccu = sum(species.values()) if 1 < totaloccu <= self._occupancy_tolerance: for key, value in six.iteritems(species): species[key] = value / totaloccu if allspecies and len(allspecies) == len(allcoords): struct = Structure(lattice, allspecies, allcoords) struct = struct.get_sorted_structure() if primitive: struct = struct.get_primitive_structure() struct = struct.get_reduced_structure() return struct def get_structures(self, primitive=True): """ Return list of structures in CIF file. primitive boolean sets whether a conventional cell structure or primitive cell structure is returned. Args: primitive (bool): Set to False to return conventional unit cells. Defaults to True. Returns: List of Structures. """ structures = [] for d in self._cif.data.values(): try: s = self._get_structure(d, primitive) if s: structures.append(s) except (KeyError, ValueError) as exc: # Warn the user (Errors should never pass silently) # A user reported a problem with cif files produced by Avogadro # in which the atomic coordinates are in Cartesian coords. warnings.warn(str(exc)) return structures def as_dict(self): d = OrderedDict() for k, v in self._cif.data.items(): d[k] = {} for k2, v2 in v.data.items(): d[k][k2] = v2 return d class CifWriter(object): """ A wrapper around CifFile to write CIF files from pymatgen structures. Args: struct (Structure): structure to write symprec (float): If not none, finds the symmetry of the structure and writes the cif with symmetry information. Passes symprec to the SpacegroupAnalyzer """ def __init__(self, struct, symprec=None): format_str = "{:.8f}" block = OrderedDict() loops = [] latt = struct.lattice comp = struct.composition no_oxi_comp = comp.element_composition spacegroup = ("P 1", 1) if symprec is not None: sf = SpacegroupAnalyzer(struct, symprec) spacegroup = (sf.get_spacegroup_symbol(), sf.get_spacegroup_number()) block["_symmetry_space_group_name_H-M"] = spacegroup[0] for cell_attr in ['a', 'b', 'c']: block["_cell_length_" + cell_attr] = format_str.format( getattr(latt, cell_attr)) for cell_attr in ['alpha', 'beta', 'gamma']: block["_cell_angle_" + cell_attr] = format_str.format( getattr(latt, cell_attr)) block["_symmetry_Int_Tables_number"] = spacegroup[1] block["_chemical_formula_structural"] = no_oxi_comp.reduced_formula block["_chemical_formula_sum"] = no_oxi_comp.formula block["_cell_volume"] = latt.volume.__str__() reduced_comp, fu = no_oxi_comp.get_reduced_composition_and_factor() block["_cell_formula_units_Z"] = str(int(fu)) if symprec is None: block["_symmetry_equiv_pos_site_id"] = ["1"] block["_symmetry_equiv_pos_as_xyz"] = ["x, y, z"] else: sf = SpacegroupAnalyzer(struct, symprec) def round_symm_trans(i): for t in TRANSLATIONS.values(): if abs(i - t) < symprec: return t if abs(i - round(i)) < symprec: return 0 raise ValueError("Invalid translation!") symmops = [] for op in sf.get_symmetry_operations(): v = op.translation_vector v = [round_symm_trans(i) for i in v] symmops.append(SymmOp.from_rotation_and_translation( op.rotation_matrix, v)) ops = [op.as_xyz_string() for op in symmops] block["_symmetry_equiv_pos_site_id"] = \ ["%d" % i for i in range(1, len(ops) + 1)] block["_symmetry_equiv_pos_as_xyz"] = ops loops.append(["_symmetry_equiv_pos_site_id", "_symmetry_equiv_pos_as_xyz"]) contains_oxidation = True try: symbol_to_oxinum = OrderedDict([ (el.__str__(), float(el.oxi_state)) for el in sorted(comp.elements)]) except AttributeError: symbol_to_oxinum = OrderedDict([(el.symbol, 0) for el in sorted(comp.elements)]) contains_oxidation = False if contains_oxidation: block["_atom_type_symbol"] = symbol_to_oxinum.keys() block["_atom_type_oxidation_number"] = symbol_to_oxinum.values() loops.append(["_atom_type_symbol", "_atom_type_oxidation_number"]) atom_site_type_symbol = [] atom_site_symmetry_multiplicity = [] atom_site_fract_x = [] atom_site_fract_y = [] atom_site_fract_z = [] atom_site_label = [] atom_site_occupancy = [] count = 1 if symprec is None: for site in struct: for sp, occu in site.species_and_occu.items(): atom_site_type_symbol.append(sp.__str__()) atom_site_symmetry_multiplicity.append("1") atom_site_fract_x.append("{0:f}".format(site.a)) atom_site_fract_y.append("{0:f}".format(site.b)) atom_site_fract_z.append("{0:f}".format(site.c)) atom_site_label.append("{}{}".format(sp.symbol, count)) atom_site_occupancy.append(occu.__str__()) count += 1 else: # The following just presents a deterministic ordering. unique_sites = [ (sorted(sites, key=lambda s: tuple([abs(x) for x in s.frac_coords]))[0], len(sites)) for sites in sf.get_symmetrized_structure().equivalent_sites ] for site, mult in sorted( unique_sites, key=lambda t: (t[0].species_and_occu.average_electroneg, -t[1], t[0].a, t[0].b, t[0].c)): for sp, occu in site.species_and_occu.items(): atom_site_type_symbol.append(sp.__str__()) atom_site_symmetry_multiplicity.append("%d" % mult) atom_site_fract_x.append("{0:f}".format(site.a)) atom_site_fract_y.append("{0:f}".format(site.b)) atom_site_fract_z.append("{0:f}".format(site.c)) atom_site_label.append("{}{}".format(sp.symbol, count)) atom_site_occupancy.append(occu.__str__()) count += 1 block["_atom_site_type_symbol"] = atom_site_type_symbol block["_atom_site_label"] = atom_site_label block["_atom_site_symmetry_multiplicity"] = \ atom_site_symmetry_multiplicity block["_atom_site_fract_x"] = atom_site_fract_x block["_atom_site_fract_y"] = atom_site_fract_y block["_atom_site_fract_z"] = atom_site_fract_z block["_atom_site_occupancy"] = atom_site_occupancy loops.append(["_atom_site_type_symbol", "_atom_site_label", "_atom_site_symmetry_multiplicity", "_atom_site_fract_x", "_atom_site_fract_y", "_atom_site_fract_z", "_atom_site_occupancy"]) d = OrderedDict() d[comp.reduced_formula] = CifBlock(block, loops, comp.reduced_formula) self._cf = CifFile(d) def __str__(self): """ Returns the cif as a string. """ return self._cf.__str__() def write_file(self, filename): """ Write the cif file. """ with zopen(filename, "wt") as f: f.write(self.__str__()) def str2float(text): """ Remove uncertainty brackets from strings and return the float. """ try: return float(re.sub("\(.+\)", "", text)) except TypeError: if isinstance(text, list) and len(text) == 1: return float(re.sub("\(.+\)", "", text[0]))
Designist/audacity
refs/heads/master
lib-src/lv2/lv2/plugins/eg-fifths.lv2/waflib/Tools/vala.py
276
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import os.path,shutil,re from waflib import Context,Task,Utils,Logs,Options,Errors from waflib.TaskGen import extension,taskgen_method from waflib.Configure import conf class valac(Task.Task): vars=["VALAC","VALAC_VERSION","VALAFLAGS"] ext_out=['.h'] def run(self): cmd=[self.env['VALAC']]+self.env['VALAFLAGS'] cmd.extend([a.abspath()for a in self.inputs]) ret=self.exec_command(cmd,cwd=self.outputs[0].parent.abspath()) if ret: return ret for x in self.outputs: if id(x.parent)!=id(self.outputs[0].parent): shutil.move(self.outputs[0].parent.abspath()+os.sep+x.name,x.abspath()) if self.generator.dump_deps_node: self.generator.dump_deps_node.write('\n'.join(self.generator.packages)) return ret valac=Task.update_outputs(valac) @taskgen_method def init_vala_task(self): self.profile=getattr(self,'profile','gobject') if self.profile=='gobject': self.uselib=Utils.to_list(getattr(self,'uselib',[])) if not'GOBJECT'in self.uselib: self.uselib.append('GOBJECT') def addflags(flags): self.env.append_value('VALAFLAGS',flags) if self.profile: addflags('--profile=%s'%self.profile) if hasattr(self,'threading'): if self.profile=='gobject': if not'GTHREAD'in self.uselib: self.uselib.append('GTHREAD') else: Logs.warn("Profile %s means no threading support"%self.profile) self.threading=False if self.threading: addflags('--threading') valatask=self.valatask self.is_lib='cprogram'not in self.features if self.is_lib: addflags('--library=%s'%self.target) h_node=self.path.find_or_declare('%s.h'%self.target) valatask.outputs.append(h_node) addflags('--header=%s'%h_node.name) valatask.outputs.append(self.path.find_or_declare('%s.vapi'%self.target)) if getattr(self,'gir',None): gir_node=self.path.find_or_declare('%s.gir'%self.gir) addflags('--gir=%s'%gir_node.name) valatask.outputs.append(gir_node) self.vala_target_glib=getattr(self,'vala_target_glib',getattr(Options.options,'vala_target_glib',None)) if self.vala_target_glib: addflags('--target-glib=%s'%self.vala_target_glib) addflags(['--define=%s'%x for x in getattr(self,'vala_defines',[])]) packages_private=Utils.to_list(getattr(self,'packages_private',[])) addflags(['--pkg=%s'%x for x in packages_private]) def _get_api_version(): api_version='1.0' if hasattr(Context.g_module,'API_VERSION'): version=Context.g_module.API_VERSION.split(".") if version[0]=="0": api_version="0."+version[1] else: api_version=version[0]+".0" return api_version self.includes=Utils.to_list(getattr(self,'includes',[])) self.uselib=self.to_list(getattr(self,'uselib',[])) valatask.install_path=getattr(self,'install_path','') valatask.vapi_path=getattr(self,'vapi_path','${DATAROOTDIR}/vala/vapi') valatask.pkg_name=getattr(self,'pkg_name',self.env['PACKAGE']) valatask.header_path=getattr(self,'header_path','${INCLUDEDIR}/%s-%s'%(valatask.pkg_name,_get_api_version())) valatask.install_binding=getattr(self,'install_binding',True) self.packages=packages=Utils.to_list(getattr(self,'packages',[])) self.vapi_dirs=vapi_dirs=Utils.to_list(getattr(self,'vapi_dirs',[])) includes=[] if hasattr(self,'use'): local_packages=Utils.to_list(self.use)[:] seen=[] while len(local_packages)>0: package=local_packages.pop() if package in seen: continue seen.append(package) try: package_obj=self.bld.get_tgen_by_name(package) except Errors.WafError: continue package_name=package_obj.target package_node=package_obj.path package_dir=package_node.path_from(self.path) for task in package_obj.tasks: for output in task.outputs: if output.name==package_name+".vapi": valatask.set_run_after(task) if package_name not in packages: packages.append(package_name) if package_dir not in vapi_dirs: vapi_dirs.append(package_dir) if package_dir not in includes: includes.append(package_dir) if hasattr(package_obj,'use'): lst=self.to_list(package_obj.use) lst.reverse() local_packages=[pkg for pkg in lst if pkg not in seen]+local_packages addflags(['--pkg=%s'%p for p in packages]) for vapi_dir in vapi_dirs: v_node=self.path.find_dir(vapi_dir) if not v_node: Logs.warn('Unable to locate Vala API directory: %r'%vapi_dir) else: addflags('--vapidir=%s'%v_node.abspath()) addflags('--vapidir=%s'%v_node.get_bld().abspath()) self.dump_deps_node=None if self.is_lib and self.packages: self.dump_deps_node=self.path.find_or_declare('%s.deps'%self.target) valatask.outputs.append(self.dump_deps_node) self.includes.append(self.bld.srcnode.abspath()) self.includes.append(self.bld.bldnode.abspath()) for include in includes: try: self.includes.append(self.path.find_dir(include).abspath()) self.includes.append(self.path.find_dir(include).get_bld().abspath()) except AttributeError: Logs.warn("Unable to locate include directory: '%s'"%include) if self.is_lib and valatask.install_binding: headers_list=[o for o in valatask.outputs if o.suffix()==".h"] try: self.install_vheader.source=headers_list except AttributeError: self.install_vheader=self.bld.install_files(valatask.header_path,headers_list,self.env) vapi_list=[o for o in valatask.outputs if(o.suffix()in(".vapi",".deps"))] try: self.install_vapi.source=vapi_list except AttributeError: self.install_vapi=self.bld.install_files(valatask.vapi_path,vapi_list,self.env) gir_list=[o for o in valatask.outputs if o.suffix()=='.gir'] try: self.install_gir.source=gir_list except AttributeError: self.install_gir=self.bld.install_files(getattr(self,'gir_path','${DATAROOTDIR}/gir-1.0'),gir_list,self.env) @extension('.vala','.gs') def vala_file(self,node): try: valatask=self.valatask except AttributeError: valatask=self.valatask=self.create_task('valac') self.init_vala_task() valatask.inputs.append(node) c_node=node.change_ext('.c') valatask.outputs.append(c_node) self.source.append(c_node) @conf def find_valac(self,valac_name,min_version): valac=self.find_program(valac_name,var='VALAC') try: output=self.cmd_and_log(valac+' --version') except Exception: valac_version=None else: ver=re.search(r'\d+.\d+.\d+',output).group(0).split('.') valac_version=tuple([int(x)for x in ver]) self.msg('Checking for %s version >= %r'%(valac_name,min_version),valac_version,valac_version and valac_version>=min_version) if valac and valac_version<min_version: self.fatal("%s version %r is too old, need >= %r"%(valac_name,valac_version,min_version)) self.env['VALAC_VERSION']=valac_version return valac @conf def check_vala(self,min_version=(0,8,0),branch=None): if not branch: branch=min_version[:2] try: find_valac(self,'valac-%d.%d'%(branch[0],branch[1]),min_version) except self.errors.ConfigurationError: find_valac(self,'valac',min_version) @conf def check_vala_deps(self): if not self.env['HAVE_GOBJECT']: pkg_args={'package':'gobject-2.0','uselib_store':'GOBJECT','args':'--cflags --libs'} if getattr(Options.options,'vala_target_glib',None): pkg_args['atleast_version']=Options.options.vala_target_glib self.check_cfg(**pkg_args) if not self.env['HAVE_GTHREAD']: pkg_args={'package':'gthread-2.0','uselib_store':'GTHREAD','args':'--cflags --libs'} if getattr(Options.options,'vala_target_glib',None): pkg_args['atleast_version']=Options.options.vala_target_glib self.check_cfg(**pkg_args) def configure(self): self.load('gnu_dirs') self.check_vala_deps() self.check_vala() self.env.VALAFLAGS=['-C','--quiet'] def options(opt): opt.load('gnu_dirs') valaopts=opt.add_option_group('Vala Compiler Options') valaopts.add_option('--vala-target-glib',default=None,dest='vala_target_glib',metavar='MAJOR.MINOR',help='Target version of glib for Vala GObject code generation')
hal0x2328/neo-python
refs/heads/master
neo/SmartContract/tests/test_sc_debug_events.py
1
import os from boa_test.tests.boa_test import BoaTest from boa.compiler import Compiler from neo.Prompt.Commands.BuildNRun import TestBuild from neo.EventHub import events, SmartContractEvent from neo.Settings import settings class TestNotifyDebugEvents(BoaTest): dispatched_events = [] execution_success = False script = None @classmethod def setUpClass(cls): super(TestNotifyDebugEvents, cls).setUpClass() output = Compiler.instance().load('%s/sc_debug_events.py' % os.path.dirname(__file__)).default cls.script = output.write() settings.set_log_smart_contract_events(False) def on_info_event(self, evt): self.dispatched_events.append(evt) def on_execution(self, evt): self.execution_success = evt.execution_success def setUp(self): self.dispatched_events = [] self.execution_success = False events.on(SmartContractEvent.RUNTIME_NOTIFY, self.on_info_event) events.on(SmartContractEvent.RUNTIME_LOG, self.on_info_event) events.on(SmartContractEvent.EXECUTION, self.on_execution) def tearDown(self): events.off(SmartContractEvent.RUNTIME_NOTIFY, self.on_info_event) events.off(SmartContractEvent.RUNTIME_LOG, self.on_info_event) events.off(SmartContractEvent.EXECUTION, self.on_execution) def test_validate_normal_behaviour(self): """ Test that 'sc-debug-notify' is off by default and the output produces out of order messaging on successful SC execution. """ settings.set_emit_notify_events_on_sc_execution_error(False) tx, results, total_ops, engine = TestBuild(self.script, [['my_arg0']], self.GetWallet1(), '10', '07') self.assertTrue(self.execution_success) self.assertEqual('my_arg0', self.dispatched_events[0].event_payload.Value) self.assertEqual(SmartContractEvent.RUNTIME_LOG, self.dispatched_events[0].event_type) self.assertEqual('Start main', self.dispatched_events[1].event_payload.Value.decode()) self.assertEqual(SmartContractEvent.RUNTIME_NOTIFY, self.dispatched_events[1].event_type) def test_validate_normal_behaviour2(self): """ Test that 'sc-debug-notify' is off by default and that no notifications are logged when SC execution fails. """ settings.set_emit_notify_events_on_sc_execution_error(False) # test should fail because we try to access index an index for a 0 length argument tx, results, total_ops, engine = TestBuild(self.script, [''], self.GetWallet1(), '10', '07') self.assertFalse(self.execution_success) self.assertEqual(0, len(self.dispatched_events)) def test_debug_notify_events(self): """ Test that we still output all Notify events prior to the point of failure when SC execution fails. """ settings.set_emit_notify_events_on_sc_execution_error(True) # test should fail because we try to access index an index for a 0 length argument tx, results, total_ops, engine = TestBuild(self.script, [''], self.GetWallet1(), '10', '07') self.assertFalse(self.execution_success) self.assertEqual(SmartContractEvent.RUNTIME_NOTIFY, self.dispatched_events[0].event_type) self.assertEqual('Start main', self.dispatched_events[0].event_payload.Value.decode()) self.assertEqual(1, len(self.dispatched_events))
aosprey/rose
refs/heads/master
lib/python/rose/apps/rose_arch.py
1
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # (C) British Crown Copyright 2012-8 Met Office. # # This file is part of Rose, a framework for meteorological suites. # # Rose 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. # # Rose 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 Rose. If not, see <http://www.gnu.org/licenses/>. # ---------------------------------------------------------------------------- """Builtin application: rose_arch: transform and archive suite files.""" import errno from glob import glob import os import re from rose.app_run import ( BuiltinApp, ConfigValueError, CompulsoryConfigValueError) from rose.checksum import get_checksum, get_checksum_func from rose.env import env_var_process, UnboundEnvironmentVariableError from rose.popen import RosePopenError from rose.reporter import Event from rose.scheme_handler import SchemeHandlersManager import shlex import sqlite3 import sys from tempfile import mkdtemp from time import gmtime, strftime, time class RoseArchDuplicateError(ConfigValueError): """An exception raised if duplicate archive targets are provided.""" ERROR_FORMAT = '%s: duplicate archive target%s: "%s"' class RoseArchValueError(KeyError): """An error raised on a bad value.""" ERROR_FORMAT = "%s: bad %s: %s: %s: %s" def __str__(self): return self.ERROR_FORMAT % self.args class RoseArchEvent(Event): """Event raised on an archiving target.""" def __str__(self): target = self.args[0] t_info = "" if len(self.args) > 1: times = self.args[1] t_init, t_tran, t_arch = times t_info = ", t(init)=%s, dt(tran)=%ds, dt(arch)=%ds" % ( strftime("%Y-%m-%dT%H:%M:%SZ", gmtime(t_init)), t_tran - t_init, t_arch - t_tran ) ret_code_str = "" if len(self.args) > 2 and self.args[2] is not None: ret_code_str = ", ret-code=%d" % self.args[2] ret = "%s %s [compress=%s%s%s]" % ( target.status, target.name, target.compress_scheme, t_info, ret_code_str) if target.status != target.ST_OLD: for source in sorted(target.sources.values(), lambda s1, s2: cmp(s1.name, s2.name)): ret += "\n%s\t%s (%s)" % ( target.status, source.name, source.orig_name) return ret class RoseArchApp(BuiltinApp): """Transform and archive files generated by suite tasks.""" SCHEME = "rose_arch" SECTION = "arch" def run(self, app_runner, conf_tree, opts, args, uuid, work_files): """Transform and archive suite files. This application is designed to work under "rose task-run" in a suite. """ dao = RoseArchDAO() suite_name = os.getenv("ROSE_SUITE_NAME") if not suite_name: return suite_dir = app_runner.suite_engine_proc.get_suite_dir(suite_name) cwd = os.getcwd() app_runner.fs_util.chdir(suite_dir) try: return self._run(dao, app_runner, conf_tree.node) finally: app_runner.fs_util.chdir(cwd) dao.close() def _run(self, dao, app_runner, config): """Transform and archive suite files. This application is designed to work under "rose task-run" in a suite. """ compress_manager = SchemeHandlersManager( [os.path.dirname(os.path.dirname(sys.modules["rose"].__file__))], "rose.apps.rose_arch_compressions", ["compress_sources"], None, app_runner) # Set up the targets s_key_tails = set() targets = [] for t_key, t_node in sorted(config.value.items()): if t_node.is_ignored() or ":" not in t_key: continue s_key_head, s_key_tail = t_key.split(":", 1) if s_key_head != self.SECTION or not s_key_tail: continue # Determine target path. s_key_tail = t_key.split(":", 1)[1] try: s_key_tail = env_var_process(s_key_tail) except UnboundEnvironmentVariableError as exc: raise ConfigValueError([t_key, ""], "", exc) # If parenthesised target is optional. is_compulsory_target = True if s_key_tail.startswith("(") and s_key_tail.endswith(")"): s_key_tail = s_key_tail[1:-1] is_compulsory_target = False # Don't permit duplicate targets. if s_key_tail in s_key_tails: raise RoseArchDuplicateError([t_key], '', s_key_tail) else: s_key_tails.add(s_key_tail) target = self._run_target_setup( app_runner, compress_manager, config, t_key, s_key_tail, t_node, is_compulsory_target) old_target = dao.select(target.name) if old_target is None or old_target != target: dao.delete(target) else: target.status = target.ST_OLD targets.append(target) targets.sort(key=lambda target: target.name) # Delete from database items that are no longer relevant dao.delete_all(filter_targets=targets) # Update the targets for target in targets: self._run_target_update(dao, app_runner, compress_manager, target) return [target.status for target in targets].count( RoseArchTarget.ST_BAD) def _run_target_setup( self, app_runner, compress_manager, config, t_key, s_key_tail, t_node, is_compulsory_target=True): """Helper for _run. Set up a target.""" target_prefix = self._get_conf( config, t_node, "target-prefix", default="") target = RoseArchTarget(target_prefix + s_key_tail) target.command_format = self._get_conf( config, t_node, "command-format", compulsory=True) try: target.command_format % {"sources": "", "target": ""} except KeyError as exc: target.status = target.ST_BAD app_runner.handle_event( RoseArchValueError( target.name, "command-format", target.command_format, type(exc).__name__, exc ) ) target.source_edit_format = self._get_conf( config, t_node, "source-edit-format", default="") try: target.source_edit_format % {"in": "", "out": ""} except KeyError as exc: target.status = target.ST_BAD app_runner.handle_event( RoseArchValueError( target.name, "source-edit-format", target.source_edit_format, type(exc).__name__, exc ) ) update_check_str = self._get_conf(config, t_node, "update-check") try: checksum_func = get_checksum_func(update_check_str) except ValueError as exc: raise RoseArchValueError( target.name, "update-check", update_check_str, type(exc).__name__, exc) source_prefix = self._get_conf( config, t_node, "source-prefix", default="") for source_glob in shlex.split( self._get_conf(config, t_node, "source", compulsory=True)): is_compulsory_source = is_compulsory_target if source_glob.startswith("(") and source_glob.endswith(")"): source_glob = source_glob[1:-1] is_compulsory_source = False paths = glob(source_prefix + source_glob) if not paths: exc = OSError(errno.ENOENT, os.strerror(errno.ENOENT), source_prefix + source_glob) app_runner.handle_event(ConfigValueError( [t_key, "source"], source_glob, exc)) if is_compulsory_source: target.status = target.ST_BAD continue for path in paths: # N.B. source_prefix may not be a directory name = path[len(source_prefix):] for path_, checksum, _ in get_checksum(path, checksum_func): if checksum is None: # is directory continue if path_: target.sources[checksum] = RoseArchSource( checksum, os.path.join(name, path_), os.path.join(path, path_)) else: # path is a file target.sources[checksum] = RoseArchSource( checksum, name, path) if not target.sources: if is_compulsory_target: target.status = target.ST_BAD else: target.status = target.ST_NULL target.compress_scheme = self._get_conf(config, t_node, "compress") if not target.compress_scheme: target_base = target.name if "/" in target.name: target_base = target.name.rsplit("/", 1)[1] if "." in target_base: tail = target_base.split(".", 1)[1] if compress_manager.get_handler(tail): target.compress_scheme = tail elif compress_manager.get_handler(target.compress_scheme) is None: app_runner.handle_event(ConfigValueError( [t_key, "compress"], target.compress_scheme, KeyError(target.compress_scheme))) target.status = target.ST_BAD rename_format = self._get_conf(config, t_node, "rename-format") if rename_format: rename_parser_str = self._get_conf(config, t_node, "rename-parser") if rename_parser_str: try: rename_parser = re.compile(rename_parser_str) except re.error as exc: raise RoseArchValueError( target.name, "rename-parser", rename_parser_str, type(exc).__name__, exc) else: rename_parser = None for source in target.sources.values(): dict_ = { "cycle": os.getenv("ROSE_TASK_CYCLE_TIME"), "name": source.name} if rename_parser: match = rename_parser.match(source.name) if match: dict_.update(match.groupdict()) try: source.name = rename_format % dict_ except (KeyError, ValueError) as exc: raise RoseArchValueError( target.name, "rename-format", rename_format, type(exc).__name__, exc) return target @classmethod def _run_target_update(cls, dao, app_runner, compress_manager, target): """Helper for _run. Update a target.""" if target.status == target.ST_OLD: app_runner.handle_event(RoseArchEvent(target)) return if target.status in (target.ST_BAD, target.ST_NULL): # boolean to int target.command_rc = int(target.status == target.ST_BAD) if target.status == target.ST_BAD: level = Event.FAIL else: level = Event.DEFAULT event = RoseArchEvent(target) app_runner.handle_event(event) app_runner.handle_event(event, kind=Event.KIND_ERR, level=level) return target.command_rc = 1 dao.insert(target) work_dir = mkdtemp() times = [time()] * 3 # init, transformed, archived ret_code = None try: # Rename/edit sources target.status = target.ST_BAD rename_required = False for source in target.sources.values(): if source.name != source.orig_name: rename_required = True break if rename_required or target.source_edit_format: for source in target.sources.values(): source.path = os.path.join(work_dir, source.name) app_runner.fs_util.makedirs( os.path.dirname(source.path)) if target.source_edit_format: command = target.source_edit_format % { "in": source.orig_path, "out": source.path} app_runner.popen.run_ok(command, shell=True) else: app_runner.fs_util.symlink(source.orig_path, source.path) # Compress sources if target.compress_scheme: handler = compress_manager.get_handler( target.compress_scheme) handler.compress_sources(target, work_dir) times[1] = time() # transformed time # Run archive command sources = [] if target.work_source_path: sources = [target.work_source_path] else: for source in target.sources.values(): sources.append(source.path) command = target.command_format % { "sources": app_runner.popen.list_to_shell_str(sources), "target": app_runner.popen.list_to_shell_str([target.name])} ret_code, out, err = app_runner.popen.run(command, shell=True) times[2] = time() # archived time if ret_code: app_runner.handle_event( RosePopenError([command], ret_code, out, err)) else: target.status = target.ST_NEW app_runner.handle_event(err, kind=Event.KIND_ERR) app_runner.handle_event(out) target.command_rc = ret_code dao.update_command_rc(target) finally: app_runner.fs_util.delete(work_dir) event = RoseArchEvent(target, times, ret_code) app_runner.handle_event(event) if target.status in (target.ST_BAD, target.ST_NULL): app_runner.handle_event( event, kind=Event.KIND_ERR, level=Event.FAIL) def _get_conf(self, r_node, t_node, key, compulsory=False, default=None): """Return the value of a configuration.""" value = t_node.get_value( [key], r_node.get_value([self.SECTION, key], default=default)) if compulsory and not value: raise CompulsoryConfigValueError([key], None, KeyError(key)) if value: try: value = env_var_process(value) except UnboundEnvironmentVariableError as exc: raise ConfigValueError([key], value, exc) return value class RoseArchTarget(object): """An archive target.""" ST_OLD = "=" ST_NEW = "+" ST_BAD = "!" ST_NULL = "0" def __init__(self, name): self.name = name self.compress_scheme = None self.command_format = None self.command_rc = 0 self.sources = {} # checksum: RoseArchSource self.source_edit_format = None self.status = None self.work_source_path = None def __eq__(self, other): if id(self) != id(other): for key in ["name", "compress_scheme", "command_format", "command_rc", "sources", "source_edit_format"]: if getattr(self, key) != getattr(other, key, None): return False return True def __ne__(self, other): return not self.__eq__(other) class RoseArchSource(object): """An archive source.""" def __init__(self, checksum, orig_name, orig_path=None): self.checksum = checksum self.orig_name = orig_name self.orig_path = orig_path self.name = self.orig_name self.path = self.orig_path def __eq__(self, other): if id(self) != id(other): for key in ["checksum", "name"]: if getattr(self, key) != getattr(other, key, None): return False return True def __ne__(self, other): return not self.__eq__(other) class RoseArchDAO(object): """Data access object for incremental mode.""" FILE_NAME = ".rose-arch.db" T_SOURCES = "sources" T_TARGETS = "targets" def __init__(self): self.file_name = os.path.abspath(self.FILE_NAME) self.conn = None self.create() def close(self): """Close connection to the SQLite database file.""" if self.conn is not None: self.conn.close() self.conn = None def get_conn(self): """Connect to the SQLite database file.""" if self.conn is None: self.conn = sqlite3.connect(self.file_name) return self.conn def create(self): """Create the database file if it does not exist.""" if not os.path.exists(self.file_name): conn = self.get_conn() conn.execute("""CREATE TABLE """ + self.T_TARGETS + """ ( target_name TEXT, compress_scheme TEXT, command_format TEXT, command_rc INT, source_edit_format TEXT, PRIMARY KEY(target_name))""") conn.execute("""CREATE TABLE """ + self.T_SOURCES + """ ( target_name TEXT, source_name TEXT, checksum TEXT, UNIQUE(target_name, checksum))""") conn.commit() def delete(self, target): """Remove target from the database.""" conn = self.get_conn() for name in [self.T_TARGETS, self.T_SOURCES]: conn.execute("DELETE FROM " + name + " WHERE target_name==?", [target.name]) conn.commit() def delete_all(self, filter_targets): """Remove all but those matching filter_targets from the database.""" conn = self.get_conn() where = "" stmt_args = [] if filter_targets: stmt_fragments = [] for filter_target in filter_targets: stmt_fragments.append("target_name != ?") stmt_args.append(filter_target.name) where += " WHERE " + " AND ".join(stmt_fragments) for name in [self.T_TARGETS, self.T_SOURCES]: conn.execute("DELETE FROM " + name + where, stmt_args) conn.commit() def insert(self, target): """Insert a target in the database.""" conn = self.get_conn() t_stmt = "INSERT INTO " + self.T_TARGETS + " VALUES (?, ?, ?, ?, ?)" t_stmt_args = [target.name, target.compress_scheme, target.command_format, target.command_rc, target.source_edit_format] conn.execute(t_stmt, t_stmt_args) sh_stmt = r"INSERT INTO " + self.T_SOURCES + " VALUES (?, ?, ?)" sh_stmt_args = [target.name] for checksum, source in target.sources.items(): conn.execute(sh_stmt, sh_stmt_args + [source.name, checksum]) conn.commit() def select(self, target_name): """Query database for target_name. On success, reconstruct the target as an instance of RoseArchTarget and return it. Return None on failure. """ conn = self.get_conn() t_stmt = ( "SELECT " + "compress_scheme,command_format,command_rc,source_edit_format " + "FROM " + self.T_TARGETS + " WHERE target_name==?" ) t_stmt_args = [target_name] for row in conn.execute(t_stmt, t_stmt_args): target = RoseArchTarget(target_name) (target.compress_scheme, target.command_format, target.command_rc, target.source_edit_format) = row break else: return None s_stmt = ("SELECT source_name,checksum FROM " + self.T_SOURCES + " WHERE target_name==?") s_stmt_args = [target_name] for s_row in conn.execute(s_stmt, s_stmt_args): source_name, checksum = s_row target.sources[checksum] = RoseArchSource(checksum, source_name) return target def update_command_rc(self, target): """Update the command return code of a target in the database.""" conn = self.get_conn() conn.execute("UPDATE " + self.T_TARGETS + " SET command_rc=?" + " WHERE target_name==?", [target.command_rc, target.name]) conn.commit()
visualputty/Landing-Lights
refs/heads/master
djangotoolbox/fields.py
5
# All fields except for BlobField written by Jonas Haag <jonas@lophus.org> from django.db import models from django.core.exceptions import ValidationError from django.utils.importlib import import_module __all__ = ('RawField', 'ListField', 'DictField', 'SetField', 'BlobField', 'EmbeddedModelField') class _HandleAssignment(object): """ A placeholder class that provides a way to set the attribute on the model. """ def __init__(self, field): self.field = field def __get__(self, obj, type=None): if obj is None: raise AttributeError('Can only be accessed via an instance.') return obj.__dict__[self.field.name] def __set__(self, obj, value): obj.__dict__[self.field.name] = self.field.to_python(value) class RawField(models.Field): """ Generic field to store anything your database backend allows you to. """ def get_internal_type(self): return 'RawField' class AbstractIterableField(models.Field): """ Abstract field for fields for storing iterable data type like ``list``, ``set`` and ``dict``. You can pass an instance of a field as the first argument. If you do, the iterable items will be piped through the passed field's validation and conversion routines, converting the items to the appropriate data type. """ def __init__(self, item_field=None, *args, **kwargs): if item_field is None: item_field = RawField() self.item_field = item_field default = kwargs.get('default', None if kwargs.get('null') else ()) if default is not None and not callable(default): # ensure a new object is created every time the default is accessed kwargs['default'] = lambda: self._type(default) super(AbstractIterableField, self).__init__(*args, **kwargs) def contribute_to_class(self, cls, name): self.item_field.model = cls self.item_field.name = name super(AbstractIterableField, self).contribute_to_class(cls, name) metaclass = getattr(self.item_field, '__metaclass__', None) if issubclass(metaclass, models.SubfieldBase): setattr(cls, self.name, _HandleAssignment(self)) def db_type(self, connection): item_db_type = self.item_field.db_type(connection=connection) return '%s:%s' % (self.__class__.__name__, item_db_type) def _convert(self, func, values, *args, **kwargs): if isinstance(values, (list, tuple, set)): return self._type(func(value, *args, **kwargs) for value in values) return values def to_python(self, value): return self._convert(self.item_field.to_python, value) def pre_save(self, model_instance, add): class fake_instance(object): pass fake_instance = fake_instance() def wrapper(value): assert not hasattr(self.item_field, 'attname') fake_instance.value = value self.item_field.attname = 'value' try: return self.item_field.pre_save(fake_instance, add) finally: del self.item_field.attname return self._convert(wrapper, getattr(model_instance, self.attname)) def get_db_prep_value(self, value, connection, prepared=False): return self._convert(self.item_field.get_db_prep_value, value, connection=connection, prepared=prepared) def get_db_prep_save(self, value, connection): return self._convert(self.item_field.get_db_prep_save, value, connection=connection) # TODO/XXX: Remove this once we have a cleaner solution def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): if hasattr(value, 'as_lookup_value'): value = value.as_lookup_value(self, lookup_type, connection) return value def validate(self, values, model_instance): try: iter(values) except TypeError: raise ValidationError('Value of type %r is not iterable' % type(values)) def formfield(self, **kwargs): raise NotImplementedError('No form field implemented for %r' % type(self)) class ListField(AbstractIterableField): """ Field representing a Python ``list``. If the optional keyword argument `ordering` is given, it must be a callable that is passed to :meth:`list.sort` as `key` argument. If `ordering` is given, the items in the list will be sorted before sending them to the database. """ _type = list def __init__(self, *args, **kwargs): self.ordering = kwargs.pop('ordering', None) if self.ordering is not None and not callable(self.ordering): raise TypeError("'ordering' has to be a callable or None, " "not of type %r" % type(self.ordering)) super(ListField, self).__init__(*args, **kwargs) def _convert(self, func, values, *args, **kwargs): values = super(ListField, self)._convert(func, values, *args, **kwargs) if values is not None and self.ordering is not None: values.sort(key=self.ordering) return values class SetField(AbstractIterableField): """ Field representing a Python ``set``. """ _type = set class DictField(AbstractIterableField): """ Field representing a Python ``dict``. The field type conversions described in :class:`AbstractIterableField` only affect values of the dictionary, not keys. Depending on the backend, keys that aren't strings might not be allowed. """ _type = dict def _convert(self, func, values, *args, **kwargs): if values is None: return None return dict((key, func(value, *args, **kwargs)) for key, value in values.iteritems()) def validate(self, values, model_instance): if not isinstance(values, dict): raise ValidationError('Value is of type %r. Should be a dict.' % type(values)) class BlobField(models.Field): """ A field for storing blobs of binary data. The value might either be a string (or something that can be converted to a string), or a file-like object. In the latter case, the object has to provide a ``read`` method from which the blob is read. """ def get_internal_type(self): return 'BlobField' def formfield(self, **kwargs): # A file widget is provided, but use model FileField or ImageField # for storing specific files most of the time from .widgets import BlobWidget from django.forms import FileField defaults = {'form_class': FileField, 'widget': BlobWidget} defaults.update(kwargs) return super(BlobField, self).formfield(**defaults) def get_db_prep_value(self, value, connection, prepared=False): if hasattr(value, 'read'): return value.read() else: return str(value) def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): raise TypeError("BlobFields do not support lookups") def value_to_string(self, obj): return str(self._get_val_from_obj(obj)) class EmbeddedModelField(models.Field): """ Field that allows you to embed a model instance. :param model: (optional) The model class that shall be embedded (may also be passed as string similar to relation fields) """ __metaclass__ = models.SubfieldBase def __init__(self, embedded_model=None, *args, **kwargs): self.embedded_model = embedded_model kwargs.setdefault('default', None) super(EmbeddedModelField, self).__init__(*args, **kwargs) def db_type(self, connection): return 'DictField:RawField' def _set_model(self, model): # EmbeddedModelFields are not contribute[d]_to_class if using within # ListFields (and friends), so we can only know the model field is # used in when the IterableField sets our 'model' attribute in its # contribute_to_class method. # We need to know the model to generate a valid key for the lookup. if model is not None and isinstance(self.embedded_model, basestring): # The model argument passed to __init__ was a string, so we need # to make sure to resolve that string to the corresponding model # class, similar to relation fields. We abuse some of the # relation fields' code to do the lookup here: def _resolve_lookup(self_, resolved_model, model): self.embedded_model = resolved_model from django.db.models.fields.related import add_lazy_relation add_lazy_relation(model, self, self.embedded_model, _resolve_lookup) self._model = model model = property(lambda self:self._model, _set_model) def pre_save(self, model_instance, add): embedded_instance = super(EmbeddedModelField, self).pre_save(model_instance, add) if embedded_instance is None: return None, None if self.embedded_model is not None and \ not isinstance(embedded_instance, self.embedded_model): raise TypeError("Expected instance of type %r, not %r" % (type(self.embedded_model), type(embedded_instance))) data = dict((field.name, field.pre_save(embedded_instance, add)) for field in embedded_instance._meta.fields) return embedded_instance, data def get_db_prep_value(self, (embedded_instance, embedded_dict), **kwargs): if embedded_dict is None: return None values = {} for name, value in embedded_dict.iteritems(): field = embedded_instance._meta.get_field(name) values[field.column] = field.get_db_prep_value(value, **kwargs) if self.embedded_model is None: values.update({'_module' : embedded_instance.__class__.__module__, '_model' : embedded_instance.__class__.__name__}) return values # TODO/XXX: Remove this once we have a cleaner solution def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): if hasattr(value, 'as_lookup_value'): value = value.as_lookup_value(self, lookup_type, connection) return value def to_python(self, values): if not isinstance(values, dict): return values module, model = values.pop('_module', None), values.pop('_model', None) if module is not None: return getattr(import_module(module), model)(**values) return self.embedded_model(**values)
invitu/odoomrp-wip
refs/heads/8.0
procurement_plan_mrp/__init__.py
240
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from . import models from . import wizard
peterfpeterson/mantid-usage
refs/heads/master
generate_report.py
1
#!/usr/bin/env python from __future__ import (absolute_import, division, print_function, unicode_literals) import json import matplotlib.pyplot as plt import os import pandas as pd class Report(object): def __init__(self, website, version="0.0", downloads="0"): self.website = website self.version = version self.downloads = downloads def __repr__(self): return "[%s:%s:%s]" % (self.website, self.version, str(self.downloads)) class SourceforgeReport(Report): def __init__(self, filename): super(SourceforgeReport, self).__init__("sourceforge") shortname = os.path.split(filename)[-1].replace('.json','') self.version = shortname.replace('sourceforge-', '') with open(filename, 'r') as handle: doc = json.load(handle) self.downloads = doc['total'] class GithubReport(Report): def __init__(self, releasedoc, shortenVersion=True): super(GithubReport, self).__init__("github") self.version = releasedoc['tag_name'].replace('v','') if shortenVersion: self.version = '.'.join(self.version.split('.')[:2]) self.downloads = 0 for asset in releasedoc['assets']: self.downloads += asset['download_count'] def combineGithubVersions(orig): splitted = {} for item in orig: if item.version in splitted: splitted[item.version].downloads += item.downloads else: splitted[item.version] = item return splitted.values() def parseGithub(filename): with open(filename, 'r') as handle: doc = json.load(handle) items = [] for release in doc: items.append(GithubReport(release)) return combineGithubVersions(items) direc = os.path.abspath(os.curdir) print("Finding json files in", direc) jsonfilenames = [name for name in os.listdir(direc) \ if name.endswith(".json")] items = [] for filename in jsonfilenames: if filename.startswith("sourceforge"): items.append(SourceforgeReport(filename)) elif filename.startswith("github"): items.extend(parseGithub(filename)) # key:[sourceforge.downloads, github.downloads] versions={} indexes = {'sourceforge':0, 'github':1} for item in items: if item.version not in versions: versions[item.version] = [0,0] index = indexes[item.website] versions[item.version][index] = item.downloads # data = pd.DataFrame(versions) keys = versions.keys() keys.sort() with open('versions.csv', 'w') as handle: handle.write(','.join(['versions', 'sourceforge', 'github'])+"\n") for key in keys: stuff = [str(downloads) for downloads in versions[key]] stuff.insert(0, key) handle.write(','.join(stuff) + "\n") data = pd.read_csv('versions.csv',index_col='versions') data.plot(kind='bar', stacked=True) plt.show()
kapadia/usgs
refs/heads/master
setup.py
2
from codecs import open as codecs_open from setuptools import setup, find_packages # Parse the version from the fiona/rasterio module. with open('usgs/__init__.py') as f: for line in f: if line.find("__version__") >= 0: version = line.split("=")[1].strip() version = version.strip('"') version = version.strip("'") continue setup(name='usgs', version=version, description=u"Access the USGS inventory service", classifiers=[], keywords='', author=u"Amit Kapadia", author_email='amit@planet.com', url='https://github.com/kapadia/usgs', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, package_data={'usgs': ['data/datasets.json']}, zip_safe=False, install_requires=[ 'click>=4.0', 'requests>=2.7.0', 'requests_futures>=0.9.5' ], extras_require={ 'test': ['pytest', 'mock'], }, entry_points=""" [console_scripts] usgs=usgs.scripts.cli:usgs """ )
IKholopov/HackUPC2017
refs/heads/master
hackupc/env/lib/python3.5/site-packages/future/moves/tkinter/filedialog.py
94
from __future__ import absolute_import from future.utils import PY3 if PY3: from tkinter.filedialog import * else: try: from FileDialog import * except ImportError: raise ImportError('The FileDialog module is missing. Does your Py2 ' 'installation include tkinter?')
yhe39/crosswalk-test-suite
refs/heads/master
webapi/tct-csp-w3c-tests/csp-py/csp_font-src_cross-origin_allowed-manual.py
30
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]) _CSP = "font-src " + 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_font-src_cross-origin_allowed</title> <link rel="author" title="Intel" href="http://www.intel.com"/> <link rel="help" href="http://www.w3.org/TR/2012/CR-CSP-20121115/#font-src"/> <meta name="flags" content=""/> <meta charset="utf-8"/> <style> @font-face { font-family: Canvas; src: url('""" + url1 + """/tests/csp/support/w3c/CanvasTest.ttf'); } #test { font-family: Canvas; } </style> </head> <body> <p>Test passes if the two lines are different in font</p> <div id="test">1234 ABCD</div> <div>1234 ABCD</div> </body> </html> """
totalgee/supercollider
refs/heads/master
editors/sced/sced/ConfigurationDialog.py
46
# sced (SuperCollider mode for gedit) # Copyright 2009 Artem Popov and other contributors (see AUTHORS) # # sced is free software: # you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gobject import gtk def on_pref_widget_notify_sensitive(widget, spec): label = widget.get_data("pref-label") if label is not None: label.set_sensitive(widget.props.sensitive) # FIXME: implement custom widget (or custom widget sequence) as well def create_pref_section(title, wlabels=[], custom=[]): vbox = gtk.VBox(spacing=6) label = gobject.new(gtk.Label, label="<b>%s</b>" % title, use_markup=True, xalign=0) vbox.pack_start(label, expand=False) label.show() align = gobject.new(gtk.Alignment, left_padding=12) vbox.pack_start(align, expand=False) align.show() table = gobject.new(gtk.Table, n_rows=len(wlabels) + len(custom), n_columns=2, row_spacing=6, column_spacing=12) align.add(table) table.show() for i in range(len(wlabels)): l, widget = wlabels[i] label = gobject.new(gtk.Label, label=l, xalign=0) widget.connect("notify::sensitive", on_pref_widget_notify_sensitive) widget.set_data("pref-label", label) if l is not None: table.attach(label, 0, 1, i, i + 1, xoptions=gtk.FILL, yoptions=gtk.FILL) table.attach(widget, 1, 2, i, i + 1, xoptions=gtk.EXPAND | gtk.FILL, yoptions=gtk.FILL) else: table.attach(widget, 0, 2, i, i + 1, xoptions=gtk.EXPAND | gtk.FILL, yoptions=gtk.FILL) table.show_all() return vbox # FIXME: fix notification class ConfigurationDialog(gtk.Dialog): __gsignals__ = { "response": "override", } # __gsignals__ def __init__(self, plugin): gtk.Dialog.__init__(self, title=_("Configure sced"), flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, buttons=(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) self.__settings = plugin.settings self.__create_page_general() def __create_page_general(self): self.__runtime_fc = gobject.new(gtk.FileChooserButton, title=_("Choose runtime folder"), action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER) folder = self.__settings.props.runtime_folder if folder is not None: self.__runtime_fc.set_current_folder(folder) self.__runtime_fc.connect("current-folder-changed", self.__on_fc_selection_changed) #self.__settings.connect("notify::runtime-folder", # self.__on_runtime_folder_changed) section = create_pref_section("Interpreter options", [ ("Runtime folder:", self.__runtime_fc), ]) section.props.border_width = 12 self.vbox.add(section) section.show() def __on_fc_selection_changed(self, button): folder = button.get_current_folder() self.__settings.props.runtime_folder = folder #def __on_runtime_folder_changed(self, *args): # self.__runtime_fc.set_current_folder(self.__settings.props.runtime_folder) def do_response(self, response): self.destroy()
SANDEISON/Python
refs/heads/master
03 - Atacando os tipos básicos/02 - Manipulando textos em Python com Strings/01-String.py
2
# Aspas de varios tipos x = 'abacate' y="mecdonald's" #constante multilinha com codigo html form = ''' <html> <head> <title> Teste </title> </head> <body> <p> Testando </p> </body> </html> ''' #Fatiamento de String z = "0123456789" print(z) print(z[0:2]) print(z[1:2]) print(z[2:4]) print(z[0:5]) print(z[0:2]) print(z[1:8]) print(z[:2]) print(z[4:]) print(z[4:-1]) print(z[-4:-1]) print(z[:]) #Incremento no fatiamento texto = "Agora estamos quase la !!!!" print (texto) print(texto[::2]) print("Texto Invertido ",texto[::-1])
FAANG/faang-methylation
refs/heads/master
workflowbs/src/pygraph/algorithms/filters/null.py
26
# Copyright (c) 2008-2009 Pedro Matiello <pmatiello@gmail.com> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """ Null searching filter. """ class null(object): """ Null search filter. """ def __init__(self): """ Initialize the filter. """ self.graph = None self.spanning_tree = None def configure(self, graph, spanning_tree): """ Configure the filter. @type graph: graph @param graph: Graph. @type spanning_tree: dictionary @param spanning_tree: Spanning tree. """ self.graph = graph self.spanning_tree = spanning_tree def __call__(self, node, parent): """ Decide if the given node should be included in the search process. @type node: node @param node: Given node. @type parent: node @param parent: Given node's parent in the spanning tree. @rtype: boolean @return: Whether the given node should be included in the search process. """ return True
andreparrish/python-for-android
refs/heads/master
python3-alpha/python3-src/Lib/test/test_threading.py
47
# Very rudimentary test of threading module import test.support from test.support import verbose, strip_python_stderr, import_module import random import re import sys _thread = import_module('_thread') threading = import_module('threading') import time import unittest import weakref import os from test.script_helper import assert_python_ok, assert_python_failure import subprocess from test import lock_tests # A trivial mutable counter. class Counter(object): def __init__(self): self.value = 0 def inc(self): self.value += 1 def dec(self): self.value -= 1 def get(self): return self.value class TestThread(threading.Thread): def __init__(self, name, testcase, sema, mutex, nrunning): threading.Thread.__init__(self, name=name) self.testcase = testcase self.sema = sema self.mutex = mutex self.nrunning = nrunning def run(self): delay = random.random() / 10000.0 if verbose: print('task %s will run for %.1f usec' % (self.name, delay * 1e6)) with self.sema: with self.mutex: self.nrunning.inc() if verbose: print(self.nrunning.get(), 'tasks are running') self.testcase.assertTrue(self.nrunning.get() <= 3) time.sleep(delay) if verbose: print('task', self.name, 'done') with self.mutex: self.nrunning.dec() self.testcase.assertTrue(self.nrunning.get() >= 0) if verbose: print('%s is finished. %d tasks are running' % (self.name, self.nrunning.get())) class BaseTestCase(unittest.TestCase): def setUp(self): self._threads = test.support.threading_setup() def tearDown(self): test.support.threading_cleanup(*self._threads) test.support.reap_children() class ThreadTests(BaseTestCase): # Create a bunch of threads, let each do some work, wait until all are # done. def test_various_ops(self): # This takes about n/3 seconds to run (about n/3 clumps of tasks, # times about 1 second per clump). NUMTASKS = 10 # no more than 3 of the 10 can run at once sema = threading.BoundedSemaphore(value=3) mutex = threading.RLock() numrunning = Counter() threads = [] for i in range(NUMTASKS): t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) threads.append(t) self.assertEqual(t.ident, None) self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t))) t.start() if verbose: print('waiting for all tasks to complete') for t in threads: t.join(NUMTASKS) self.assertTrue(not t.is_alive()) self.assertNotEqual(t.ident, 0) self.assertFalse(t.ident is None) self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>', repr(t))) if verbose: print('all tasks done') self.assertEqual(numrunning.get(), 0) def test_ident_of_no_threading_threads(self): # The ident still must work for the main thread and dummy threads. self.assertFalse(threading.currentThread().ident is None) def f(): ident.append(threading.currentThread().ident) done.set() done = threading.Event() ident = [] _thread.start_new_thread(f, ()) done.wait() self.assertFalse(ident[0] is None) # Kill the "immortal" _DummyThread del threading._active[ident[0]] # run with a small(ish) thread stack size (256kB) def test_various_ops_small_stack(self): if verbose: print('with 256kB thread stack size...') try: threading.stack_size(262144) except _thread.error: raise unittest.SkipTest( 'platform does not support changing thread stack size') self.test_various_ops() threading.stack_size(0) # run with a large thread stack size (1MB) def test_various_ops_large_stack(self): if verbose: print('with 1MB thread stack size...') try: threading.stack_size(0x100000) except _thread.error: raise unittest.SkipTest( 'platform does not support changing thread stack size') self.test_various_ops() threading.stack_size(0) def test_foreign_thread(self): # Check that a "foreign" thread can use the threading module. def f(mutex): # Calling current_thread() forces an entry for the foreign # thread to get made in the threading._active map. threading.current_thread() mutex.release() mutex = threading.Lock() mutex.acquire() tid = _thread.start_new_thread(f, (mutex,)) # Wait for the thread to finish. mutex.acquire() self.assertIn(tid, threading._active) self.assertIsInstance(threading._active[tid], threading._DummyThread) del threading._active[tid] # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) # exposed at the Python level. This test relies on ctypes to get at it. def test_PyThreadState_SetAsyncExc(self): ctypes = import_module("ctypes") set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc class AsyncExc(Exception): pass exception = ctypes.py_object(AsyncExc) # First check it works when setting the exception from the same thread. tid = _thread.get_ident() try: result = set_async_exc(ctypes.c_long(tid), exception) # The exception is async, so we might have to keep the VM busy until # it notices. while True: pass except AsyncExc: pass else: # This code is unreachable but it reflects the intent. If we wanted # to be smarter the above loop wouldn't be infinite. self.fail("AsyncExc not raised") try: self.assertEqual(result, 1) # one thread state modified except UnboundLocalError: # The exception was raised too quickly for us to get the result. pass # `worker_started` is set by the thread when it's inside a try/except # block waiting to catch the asynchronously set AsyncExc exception. # `worker_saw_exception` is set by the thread upon catching that # exception. worker_started = threading.Event() worker_saw_exception = threading.Event() class Worker(threading.Thread): def run(self): self.id = _thread.get_ident() self.finished = False try: while True: worker_started.set() time.sleep(0.1) except AsyncExc: self.finished = True worker_saw_exception.set() t = Worker() t.daemon = True # so if this fails, we don't hang Python at shutdown t.start() if verbose: print(" started worker thread") # Try a thread id that doesn't make sense. if verbose: print(" trying nonsensical thread id") result = set_async_exc(ctypes.c_long(-1), exception) self.assertEqual(result, 0) # no thread states modified # Now raise an exception in the worker thread. if verbose: print(" waiting for worker thread to get started") ret = worker_started.wait() self.assertTrue(ret) if verbose: print(" verifying worker hasn't exited") self.assertTrue(not t.finished) if verbose: print(" attempting to raise asynch exception in worker") result = set_async_exc(ctypes.c_long(t.id), exception) self.assertEqual(result, 1) # one thread state modified if verbose: print(" waiting for worker to say it caught the exception") worker_saw_exception.wait(timeout=10) self.assertTrue(t.finished) if verbose: print(" all OK -- joining worker") if t.finished: t.join() # else the thread is still running, and we have no way to kill it def test_limbo_cleanup(self): # Issue 7481: Failure to start thread should cleanup the limbo map. def fail_new_thread(*args): raise threading.ThreadError() _start_new_thread = threading._start_new_thread threading._start_new_thread = fail_new_thread try: t = threading.Thread(target=lambda: None) self.assertRaises(threading.ThreadError, t.start) self.assertFalse( t in threading._limbo, "Failed to cleanup _limbo map on failure of Thread.start().") finally: threading._start_new_thread = _start_new_thread def test_finalize_runnning_thread(self): # Issue 1402: the PyGILState_Ensure / _Release functions may be called # very late on python exit: on deallocation of a running thread for # example. import_module("ctypes") rc, out, err = assert_python_failure("-c", """if 1: import ctypes, sys, time, _thread # This lock is used as a simple event variable. ready = _thread.allocate_lock() ready.acquire() # Module globals are cleared before __del__ is run # So we save the functions in class dict class C: ensure = ctypes.pythonapi.PyGILState_Ensure release = ctypes.pythonapi.PyGILState_Release def __del__(self): state = self.ensure() self.release(state) def waitingThread(): x = C() ready.release() time.sleep(100) _thread.start_new_thread(waitingThread, ()) ready.acquire() # Be sure the other thread is waiting. sys.exit(42) """) self.assertEqual(rc, 42) def test_finalize_with_trace(self): # Issue1733757 # Avoid a deadlock when sys.settrace steps into threading._shutdown assert_python_ok("-c", """if 1: import sys, threading # A deadlock-killer, to prevent the # testsuite to hang forever def killer(): import os, time time.sleep(2) print('program blocked; aborting') os._exit(2) t = threading.Thread(target=killer) t.daemon = True t.start() # This is the trace function def func(frame, event, arg): threading.current_thread() return func sys.settrace(func) """) def test_join_nondaemon_on_shutdown(self): # Issue 1722344 # Raising SystemExit skipped threading._shutdown rc, out, err = assert_python_ok("-c", """if 1: import threading from time import sleep def child(): sleep(1) # As a non-daemon thread we SHOULD wake up and nothing # should be torn down yet print("Woke up, sleep function is:", sleep) threading.Thread(target=child).start() raise SystemExit """) self.assertEqual(out.strip(), b"Woke up, sleep function is: <built-in function sleep>") self.assertEqual(err, b"") def test_enumerate_after_join(self): # Try hard to trigger #1703448: a thread is still returned in # threading.enumerate() after it has been join()ed. enum = threading.enumerate old_interval = sys.getswitchinterval() try: for i in range(1, 100): sys.setswitchinterval(i * 0.0002) t = threading.Thread(target=lambda: None) t.start() t.join() l = enum() self.assertNotIn(t, l, "#1703448 triggered after %d trials: %s" % (i, l)) finally: sys.setswitchinterval(old_interval) def test_no_refcycle_through_target(self): class RunSelfFunction(object): def __init__(self, should_raise): # The links in this refcycle from Thread back to self # should be cleaned up when the thread completes. self.should_raise = should_raise self.thread = threading.Thread(target=self._run, args=(self,), kwargs={'yet_another':self}) self.thread.start() def _run(self, other_ref, yet_another): if self.should_raise: raise SystemExit cyclic_object = RunSelfFunction(should_raise=False) weak_cyclic_object = weakref.ref(cyclic_object) cyclic_object.thread.join() del cyclic_object self.assertIsNone(weak_cyclic_object(), msg=('%d references still around' % sys.getrefcount(weak_cyclic_object()))) raising_cyclic_object = RunSelfFunction(should_raise=True) weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) raising_cyclic_object.thread.join() del raising_cyclic_object self.assertIsNone(weak_raising_cyclic_object(), msg=('%d references still around' % sys.getrefcount(weak_raising_cyclic_object()))) def test_old_threading_api(self): # Just a quick sanity check to make sure the old method names are # still present t = threading.Thread() t.isDaemon() t.setDaemon(True) t.getName() t.setName("name") t.isAlive() e = threading.Event() e.isSet() threading.activeCount() def test_repr_daemon(self): t = threading.Thread() self.assertFalse('daemon' in repr(t)) t.daemon = True self.assertTrue('daemon' in repr(t)) class ThreadJoinOnShutdown(BaseTestCase): # Between fork() and exec(), only async-safe functions are allowed (issues # #12316 and #11870), and fork() from a worker thread is known to trigger # problems with some operating systems (issue #3863): skip problematic tests # on platforms known to behave badly. platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', 'os2emx') def _run_and_join(self, script): script = """if 1: import sys, os, time, threading # a thread, which waits for the main program to terminate def joiningfunc(mainthread): mainthread.join() print('end of thread') # stdout is fully buffered because not a tty, we have to flush # before exit. sys.stdout.flush() \n""" + script rc, out, err = assert_python_ok("-c", script) data = out.decode().replace('\r', '') self.assertEqual(data, "end of main\nend of thread\n") def test_1_join_on_shutdown(self): # The usual case: on exit, wait for a non-daemon thread script = """if 1: import os t = threading.Thread(target=joiningfunc, args=(threading.current_thread(),)) t.start() time.sleep(0.1) print('end of main') """ self._run_and_join(script) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_2_join_in_forked_process(self): # Like the test above, but from a forked interpreter script = """if 1: childpid = os.fork() if childpid != 0: os.waitpid(childpid, 0) sys.exit(0) t = threading.Thread(target=joiningfunc, args=(threading.current_thread(),)) t.start() print('end of main') """ self._run_and_join(script) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_3_join_in_forked_from_thread(self): # Like the test above, but fork() was called from a worker thread # In the forked process, the main Thread object must be marked as stopped. script = """if 1: main_thread = threading.current_thread() def worker(): childpid = os.fork() if childpid != 0: os.waitpid(childpid, 0) sys.exit(0) t = threading.Thread(target=joiningfunc, args=(main_thread,)) print('end of main') t.start() t.join() # Should not block: main_thread is already stopped w = threading.Thread(target=worker) w.start() """ self._run_and_join(script) def assertScriptHasOutput(self, script, expected_output): rc, out, err = assert_python_ok("-c", script) data = out.decode().replace('\r', '') self.assertEqual(data, expected_output) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_4_joining_across_fork_in_worker_thread(self): # There used to be a possible deadlock when forking from a child # thread. See http://bugs.python.org/issue6643. # The script takes the following steps: # - The main thread in the parent process starts a new thread and then # tries to join it. # - The join operation acquires the Lock inside the thread's _block # Condition. (See threading.py:Thread.join().) # - We stub out the acquire method on the condition to force it to wait # until the child thread forks. (See LOCK ACQUIRED HERE) # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS # HERE) # - The main thread of the parent process enters Condition.wait(), # which releases the lock on the child thread. # - The child process returns. Without the necessary fix, when the # main thread of the child process (which used to be the child thread # in the parent process) attempts to exit, it will try to acquire the # lock in the Thread._block Condition object and hang, because the # lock was held across the fork. script = """if 1: import os, time, threading finish_join = False start_fork = False def worker(): # Wait until this thread's lock is acquired before forking to # create the deadlock. global finish_join while not start_fork: time.sleep(0.01) # LOCK HELD: Main thread holds lock across this call. childpid = os.fork() finish_join = True if childpid != 0: # Parent process just waits for child. os.waitpid(childpid, 0) # Child process should just return. w = threading.Thread(target=worker) # Stub out the private condition variable's lock acquire method. # This acquires the lock and then waits until the child has forked # before returning, which will release the lock soon after. If # someone else tries to fix this test case by acquiring this lock # before forking instead of resetting it, the test case will # deadlock when it shouldn't. condition = w._block orig_acquire = condition.acquire call_count_lock = threading.Lock() call_count = 0 def my_acquire(): global call_count global start_fork orig_acquire() # LOCK ACQUIRED HERE start_fork = True if call_count == 0: while not finish_join: time.sleep(0.01) # WORKER THREAD FORKS HERE with call_count_lock: call_count += 1 condition.acquire = my_acquire w.start() w.join() print('end of main') """ self.assertScriptHasOutput(script, "end of main\n") @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_5_clear_waiter_locks_to_avoid_crash(self): # Check that a spawned thread that forks doesn't segfault on certain # platforms, namely OS X. This used to happen if there was a waiter # lock in the thread's condition variable's waiters list. Even though # we know the lock will be held across the fork, it is not safe to # release locks held across forks on all platforms, so releasing the # waiter lock caused a segfault on OS X. Furthermore, since locks on # OS X are (as of this writing) implemented with a mutex + condition # variable instead of a semaphore, while we know that the Python-level # lock will be acquired, we can't know if the internal mutex will be # acquired at the time of the fork. script = """if True: import os, time, threading start_fork = False def worker(): # Wait until the main thread has attempted to join this thread # before continuing. while not start_fork: time.sleep(0.01) childpid = os.fork() if childpid != 0: # Parent process just waits for child. (cpid, rc) = os.waitpid(childpid, 0) assert cpid == childpid assert rc == 0 print('end of worker thread') else: # Child process should just return. pass w = threading.Thread(target=worker) # Stub out the private condition variable's _release_save method. # This releases the condition's lock and flips the global that # causes the worker to fork. At this point, the problematic waiter # lock has been acquired once by the waiter and has been put onto # the waiters list. condition = w._block orig_release_save = condition._release_save def my_release_save(): global start_fork orig_release_save() # Waiter lock held here, condition lock released. start_fork = True condition._release_save = my_release_save w.start() w.join() print('end of main thread') """ output = "end of worker thread\nend of main thread\n" self.assertScriptHasOutput(script, output) def test_6_daemon_threads(self): # Check that a daemon thread cannot crash the interpreter on shutdown # by manipulating internal structures that are being disposed of in # the main thread. script = """if True: import os import random import sys import time import threading thread_has_run = set() def random_io(): '''Loop for a while sleeping random tiny amounts and doing some I/O.''' while True: in_f = open(os.__file__, 'rb') stuff = in_f.read(200) null_f = open(os.devnull, 'wb') null_f.write(stuff) time.sleep(random.random() / 1995) null_f.close() in_f.close() thread_has_run.add(threading.current_thread()) def main(): count = 0 for _ in range(40): new_thread = threading.Thread(target=random_io) new_thread.daemon = True new_thread.start() count += 1 while len(thread_has_run) < count: time.sleep(0.001) # Trigger process shutdown sys.exit(0) main() """ rc, out, err = assert_python_ok('-c', script) self.assertFalse(err) class ThreadingExceptionTests(BaseTestCase): # A RuntimeError should be raised if Thread.start() is called # multiple times. def test_start_thread_again(self): thread = threading.Thread() thread.start() self.assertRaises(RuntimeError, thread.start) def test_joining_current_thread(self): current_thread = threading.current_thread() self.assertRaises(RuntimeError, current_thread.join); def test_joining_inactive_thread(self): thread = threading.Thread() self.assertRaises(RuntimeError, thread.join) def test_daemonize_active_thread(self): thread = threading.Thread() thread.start() self.assertRaises(RuntimeError, setattr, thread, "daemon", True) @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem') def test_recursion_limit(self): # Issue 9670 # test that excessive recursion within a non-main thread causes # an exception rather than crashing the interpreter on platforms # like Mac OS X or FreeBSD which have small default stack sizes # for threads script = """if True: import threading def recurse(): return recurse() def outer(): try: recurse() except RuntimeError: pass w = threading.Thread(target=outer) w.start() w.join() print('end of main thread') """ expected_output = "end of main thread\n" p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) stdout, stderr = p.communicate() data = stdout.decode().replace('\r', '') self.assertEqual(p.returncode, 0, "Unexpected error") self.assertEqual(data, expected_output) class LockTests(lock_tests.LockTests): locktype = staticmethod(threading.Lock) class PyRLockTests(lock_tests.RLockTests): locktype = staticmethod(threading._PyRLock) class CRLockTests(lock_tests.RLockTests): locktype = staticmethod(threading._CRLock) class EventTests(lock_tests.EventTests): eventtype = staticmethod(threading.Event) class ConditionAsRLockTests(lock_tests.RLockTests): # An Condition uses an RLock by default and exports its API. locktype = staticmethod(threading.Condition) class ConditionTests(lock_tests.ConditionTests): condtype = staticmethod(threading.Condition) class SemaphoreTests(lock_tests.SemaphoreTests): semtype = staticmethod(threading.Semaphore) class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): semtype = staticmethod(threading.BoundedSemaphore) class BarrierTests(lock_tests.BarrierTests): barriertype = staticmethod(threading.Barrier) def test_main(): test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests, ConditionAsRLockTests, ConditionTests, SemaphoreTests, BoundedSemaphoreTests, ThreadTests, ThreadJoinOnShutdown, ThreadingExceptionTests, BarrierTests ) if __name__ == "__main__": test_main()
qedi-r/home-assistant
refs/heads/dev
homeassistant/components/heatmiser/__init__.py
36
"""The heatmiser component."""
oluwex/eCaretaker
refs/heads/master
eCaretakerWeb/tests.py
24123
from django.test import TestCase # Create your tests here.
moonbeamxp/ns-3
refs/heads/master
src/lte/bindings/callbacks_list.py
8
callback_classes = [ ['void', 'ns3::Ptr<ns3::Packet const>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'unsigned short', 'ns3::Ptr<ns3::SpectrumValue>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::Packet>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::DlInfoListElement_s', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'std::list<ns3::Ptr<ns3::LteControlMessage>, std::allocator<ns3::Ptr<ns3::LteControlMessage> > >', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::UlInfoListElement_s', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['bool', 'ns3::Ptr<ns3::Packet>', 'ns3::Address const&', 'ns3::Address const&', 'unsigned short', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::Socket>', 'ns3::Address const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['bool', 'ns3::Ptr<ns3::Socket>', 'ns3::Address const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ]
darksylinc/qt-creator
refs/heads/master
tests/system/suite_qtquick/tst_qtquick_creation3/test.py
1
############################################################################# ## ## Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ## Contact: http://www.qt-project.org/legal ## ## This file is part of Qt Creator. ## ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance with the commercial license agreement provided with the ## Software or, alternatively, in accordance with the terms contained in ## a written agreement between you and Digia. For licensing terms and ## conditions see http://qt.digia.com/licensing. For further information ## use the contact form at http://qt.digia.com/contact-us. ## ## GNU Lesser General Public License Usage ## Alternatively, this file may be used under the terms of the GNU Lesser ## General Public License version 2.1 as published by the Free Software ## Foundation and appearing in the file LICENSE.LGPL included in the ## packaging of this file. Please review the following information to ## ensure the GNU Lesser General Public License version 2.1 requirements ## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ## ## In addition, as a special exception, Digia gives you certain additional ## rights. These rights are described in the Digia Qt LGPL Exception ## version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ## ############################################################################# source("../../shared/qtcreator.py") def main(): startApplication("qtcreator" + SettingsPath) if not startedWithoutPluginError(): return for quickVersion in ["1.1", "2.1", "2.2"]: # using a temporary directory won't mess up a potentially existing workingDir = tempDir() projectName = createNewQtQuickUI(workingDir, quickVersion) test.log("Running project Qt Quick %s UI" % quickVersion) qmlViewer = modifyRunSettingsForHookIntoQtQuickUI(1, workingDir, projectName, 11223, quickVersion) if qmlViewer!=None: qmlViewerPath = os.path.dirname(qmlViewer) qmlViewer = os.path.basename(qmlViewer) result = addExecutableAsAttachableAUT(qmlViewer, 11223) allowAppThroughWinFW(qmlViewerPath, qmlViewer, None) if result: result = runAndCloseApp(True, qmlViewer, 11223, sType=SubprocessType.QT_QUICK_UI, quickVersion=quickVersion) else: result = runAndCloseApp(sType=SubprocessType.QT_QUICK_UI) removeExecutableAsAttachableAUT(qmlViewer, 11223) deleteAppFromWinFW(qmlViewerPath, qmlViewer) else: result = runAndCloseApp(sType=SubprocessType.QT_QUICK_UI) if result == None: checkCompile() else: logApplicationOutput() invokeMenuItem("File", "Close All Projects and Editors") invokeMenuItem("File", "Exit")
oguz298/FTL-Kernel
refs/heads/New2
tools/perf/tests/attr.py
3174
#! /usr/bin/python import os import sys import glob import optparse import tempfile import logging import shutil import ConfigParser class Fail(Exception): def __init__(self, test, msg): self.msg = msg self.test = test def getMsg(self): return '\'%s\' - %s' % (self.test.path, self.msg) class Unsup(Exception): def __init__(self, test): self.test = test def getMsg(self): return '\'%s\'' % self.test.path class Event(dict): terms = [ 'cpu', 'flags', 'type', 'size', 'config', 'sample_period', 'sample_type', 'read_format', 'disabled', 'inherit', 'pinned', 'exclusive', 'exclude_user', 'exclude_kernel', 'exclude_hv', 'exclude_idle', 'mmap', 'comm', 'freq', 'inherit_stat', 'enable_on_exec', 'task', 'watermark', 'precise_ip', 'mmap_data', 'sample_id_all', 'exclude_host', 'exclude_guest', 'exclude_callchain_kernel', 'exclude_callchain_user', 'wakeup_events', 'bp_type', 'config1', 'config2', 'branch_sample_type', 'sample_regs_user', 'sample_stack_user', ] def add(self, data): for key, val in data: log.debug(" %s = %s" % (key, val)) self[key] = val def __init__(self, name, data, base): log.debug(" Event %s" % name); self.name = name; self.group = '' self.add(base) self.add(data) def compare_data(self, a, b): # Allow multiple values in assignment separated by '|' a_list = a.split('|') b_list = b.split('|') for a_item in a_list: for b_item in b_list: if (a_item == b_item): return True elif (a_item == '*') or (b_item == '*'): return True return False def equal(self, other): for t in Event.terms: log.debug(" [%s] %s %s" % (t, self[t], other[t])); if not self.has_key(t) or not other.has_key(t): return False if not self.compare_data(self[t], other[t]): return False return True def diff(self, other): for t in Event.terms: if not self.has_key(t) or not other.has_key(t): continue if not self.compare_data(self[t], other[t]): log.warning("expected %s=%s, got %s" % (t, self[t], other[t])) # Test file description needs to have following sections: # [config] # - just single instance in file # - needs to specify: # 'command' - perf command name # 'args' - special command arguments # 'ret' - expected command return value (0 by default) # # [eventX:base] # - one or multiple instances in file # - expected values assignments class Test(object): def __init__(self, path, options): parser = ConfigParser.SafeConfigParser() parser.read(path) log.warning("running '%s'" % path) self.path = path self.test_dir = options.test_dir self.perf = options.perf self.command = parser.get('config', 'command') self.args = parser.get('config', 'args') try: self.ret = parser.get('config', 'ret') except: self.ret = 0 self.expect = {} self.result = {} log.debug(" loading expected events"); self.load_events(path, self.expect) def is_event(self, name): if name.find("event") == -1: return False else: return True def load_events(self, path, events): parser_event = ConfigParser.SafeConfigParser() parser_event.read(path) # The event record section header contains 'event' word, # optionaly followed by ':' allowing to load 'parent # event' first as a base for section in filter(self.is_event, parser_event.sections()): parser_items = parser_event.items(section); base_items = {} # Read parent event if there's any if (':' in section): base = section[section.index(':') + 1:] parser_base = ConfigParser.SafeConfigParser() parser_base.read(self.test_dir + '/' + base) base_items = parser_base.items('event') e = Event(section, parser_items, base_items) events[section] = e def run_cmd(self, tempdir): cmd = "PERF_TEST_ATTR=%s %s %s -o %s/perf.data %s" % (tempdir, self.perf, self.command, tempdir, self.args) ret = os.WEXITSTATUS(os.system(cmd)) log.info(" '%s' ret %d " % (cmd, ret)) if ret != int(self.ret): raise Unsup(self) def compare(self, expect, result): match = {} log.debug(" compare"); # For each expected event find all matching # events in result. Fail if there's not any. for exp_name, exp_event in expect.items(): exp_list = [] log.debug(" matching [%s]" % exp_name) for res_name, res_event in result.items(): log.debug(" to [%s]" % res_name) if (exp_event.equal(res_event)): exp_list.append(res_name) log.debug(" ->OK") else: log.debug(" ->FAIL"); log.debug(" match: [%s] matches %s" % (exp_name, str(exp_list))) # we did not any matching event - fail if (not exp_list): exp_event.diff(res_event) raise Fail(self, 'match failure'); match[exp_name] = exp_list # For each defined group in the expected events # check we match the same group in the result. for exp_name, exp_event in expect.items(): group = exp_event.group if (group == ''): continue for res_name in match[exp_name]: res_group = result[res_name].group if res_group not in match[group]: raise Fail(self, 'group failure') log.debug(" group: [%s] matches group leader %s" % (exp_name, str(match[group]))) log.debug(" matched") def resolve_groups(self, events): for name, event in events.items(): group_fd = event['group_fd']; if group_fd == '-1': continue; for iname, ievent in events.items(): if (ievent['fd'] == group_fd): event.group = iname log.debug('[%s] has group leader [%s]' % (name, iname)) break; def run(self): tempdir = tempfile.mkdtemp(); try: # run the test script self.run_cmd(tempdir); # load events expectation for the test log.debug(" loading result events"); for f in glob.glob(tempdir + '/event*'): self.load_events(f, self.result); # resolve group_fd to event names self.resolve_groups(self.expect); self.resolve_groups(self.result); # do the expectation - results matching - both ways self.compare(self.expect, self.result) self.compare(self.result, self.expect) finally: # cleanup shutil.rmtree(tempdir) def run_tests(options): for f in glob.glob(options.test_dir + '/' + options.test): try: Test(f, options).run() except Unsup, obj: log.warning("unsupp %s" % obj.getMsg()) def setup_log(verbose): global log level = logging.CRITICAL if verbose == 1: level = logging.WARNING if verbose == 2: level = logging.INFO if verbose >= 3: level = logging.DEBUG log = logging.getLogger('test') log.setLevel(level) ch = logging.StreamHandler() ch.setLevel(level) formatter = logging.Formatter('%(message)s') ch.setFormatter(formatter) log.addHandler(ch) USAGE = '''%s [OPTIONS] -d dir # tests dir -p path # perf binary -t test # single test -v # verbose level ''' % sys.argv[0] def main(): parser = optparse.OptionParser(usage=USAGE) parser.add_option("-t", "--test", action="store", type="string", dest="test") parser.add_option("-d", "--test-dir", action="store", type="string", dest="test_dir") parser.add_option("-p", "--perf", action="store", type="string", dest="perf") parser.add_option("-v", "--verbose", action="count", dest="verbose") options, args = parser.parse_args() if args: parser.error('FAILED wrong arguments %s' % ' '.join(args)) return -1 setup_log(options.verbose) if not options.test_dir: print 'FAILED no -d option specified' sys.exit(-1) if not options.test: options.test = 'test*' try: run_tests(options) except Fail, obj: print "FAILED %s" % obj.getMsg(); sys.exit(-1) sys.exit(0) if __name__ == '__main__': main()
Bachaco-ve/odoo
refs/heads/8.0
addons/website_mail/models/mail_message.py
264
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import SUPERUSER_ID from openerp.tools import html2plaintext from openerp.tools.translate import _ from openerp.osv import osv, fields, expression class MailMessage(osv.Model): _inherit = 'mail.message' def _get_description_short(self, cr, uid, ids, name, arg, context=None): res = dict.fromkeys(ids, False) for message in self.browse(cr, uid, ids, context=context): if message.subject: res[message.id] = message.subject else: plaintext_ct = '' if not message.body else html2plaintext(message.body) res[message.id] = plaintext_ct[:30] + '%s' % (' [...]' if len(plaintext_ct) >= 30 else '') return res _columns = { 'description': fields.function( _get_description_short, type='char', help='Message description: either the subject, or the beginning of the body' ), 'website_published': fields.boolean( 'Published', help="Visible on the website as a comment", copy=False, ), } def default_get(self, cr, uid, fields_list, context=None): defaults = super(MailMessage, self).default_get(cr, uid, fields_list, context=context) # Note: explicitly implemented in default_get() instead of _defaults, # to avoid setting to True for all existing messages during upgrades. # TODO: this default should probably be dynamic according to the model # on which the messages are attached, thus moved to create(). if 'website_published' in fields_list: defaults.setdefault('website_published', True) return defaults def _search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None): """ Override that adds specific access rights of mail.message, to restrict messages to published messages for public users. """ if uid != SUPERUSER_ID: group_ids = self.pool.get('res.users').browse(cr, uid, uid, context=context).groups_id group_user_id = self.pool.get("ir.model.data").get_object_reference(cr, uid, 'base', 'group_public')[1] if group_user_id in [group.id for group in group_ids]: args = expression.AND([[('website_published', '=', True)], list(args)]) return super(MailMessage, self)._search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count, access_rights_uid=access_rights_uid) def check_access_rule(self, cr, uid, ids, operation, context=None): """ Add Access rules of mail.message for non-employee user: - read: - raise if the type is comment and subtype NULL (internal note) """ if uid != SUPERUSER_ID: group_ids = self.pool.get('res.users').browse(cr, uid, uid, context=context).groups_id group_user_id = self.pool.get("ir.model.data").get_object_reference(cr, uid, 'base', 'group_public')[1] if group_user_id in [group.id for group in group_ids]: cr.execute('SELECT id FROM "%s" WHERE website_published IS FALSE AND id = ANY (%%s)' % (self._table), (ids,)) if cr.fetchall(): raise osv.except_osv( _('Access Denied'), _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % (self._description, operation)) return super(MailMessage, self).check_access_rule(cr, uid, ids=ids, operation=operation, context=context)
zakuro9715/lettuce
refs/heads/master
tests/integration/lib/Django-1.2.5/tests/regressiontests/forms/models.py
89
# -*- coding: utf-8 -*- import datetime import tempfile from django.db import models from django.core.files.storage import FileSystemStorage temp_storage_location = tempfile.mkdtemp() temp_storage = FileSystemStorage(location=temp_storage_location) class BoundaryModel(models.Model): positive_integer = models.PositiveIntegerField(null=True, blank=True) callable_default_value = 0 def callable_default(): global callable_default_value callable_default_value = callable_default_value + 1 return callable_default_value class Defaults(models.Model): name = models.CharField(max_length=255, default='class default value') def_date = models.DateField(default = datetime.date(1980, 1, 1)) value = models.IntegerField(default=42) callable_default = models.IntegerField(default=callable_default) class ChoiceModel(models.Model): """For ModelChoiceField and ModelMultipleChoiceField tests.""" name = models.CharField(max_length=10) class ChoiceOptionModel(models.Model): """Destination for ChoiceFieldModel's ForeignKey. Can't reuse ChoiceModel because error_message tests require that it have no instances.""" name = models.CharField(max_length=10) class Meta: ordering = ('name',) def __unicode__(self): return u'ChoiceOption %d' % self.pk class ChoiceFieldModel(models.Model): """Model with ForeignKey to another model, for testing ModelForm generation with ModelChoiceField.""" choice = models.ForeignKey(ChoiceOptionModel, blank=False, default=lambda: ChoiceOptionModel.objects.get(name='default')) choice_int = models.ForeignKey(ChoiceOptionModel, blank=False, related_name='choice_int', default=lambda: 1) multi_choice = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice', default=lambda: ChoiceOptionModel.objects.filter(name='default')) multi_choice_int = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice_int', default=lambda: [1]) class FileModel(models.Model): file = models.FileField(storage=temp_storage, upload_to='tests') class Group(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return u'%s' % self.name class Cheese(models.Model): name = models.CharField(max_length=100)
sonicrules1234/sonicbot
refs/heads/sonicbotv4
SonicMail/bbcode.py
1
# -*- coding: UTF-8 -*- """ Post Markup Author: Will McGugan (http://www.willmcgugan.com) """ __version__ = "1.1.0" import re from urllib import quote, unquote, quote_plus from urlparse import urlparse, urlunparse pygments_available = True try: from pygments import highlight from pygments.lexers import get_lexer_by_name, ClassNotFound from pygments.formatters import HtmlFormatter except ImportError: # Make Pygments optional pygments_available = False def annotate_link(domain): """This function is called by the url tag. Override to disable or change behaviour. domain -- Domain parsed from url """ return u" [%s]"%domain re_url = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.MULTILINE| re.UNICODE) re_html=re.compile('<.*?>|\&.*?\;') def textilize(s): """Remove markup from html""" return re_html.sub("", s) re_excerpt = re.compile(r'\[".*?\]+?.*?\[/".*?\]+?', re.DOTALL) re_remove_markup = re.compile(r'\[.*?\]', re.DOTALL) def remove_markup(post): """Removes html tags from a string.""" return re_remove_markup.sub("", post) def get_excerpt(post): """Returns an excerpt between ["] and [/"] post -- BBCode string""" match = re_excerpt.search(post) if match is None: return "" excerpt = match.group(0) excerpt = excerpt.replace(u'\n', u"<br/>") return remove_markup(excerpt) def strip_bbcode(bbcode): """ Strips bbcode tags from a string. bbcode -- A string to remove tags from """ return u"".join([t[1] for t in PostMarkup.tokenize(bbcode) if t[0] == PostMarkup.TOKEN_TEXT]) def create(include=None, exclude=None, use_pygments=True, **kwargs): """Create a postmarkup object that converts bbcode to XML snippets. include -- List or similar iterable containing the names of the tags to use If omitted, all tags will be used exclude -- List or similar iterable containing the names of the tags to exclude. If omitted, no tags will be excluded use_pygments -- If True, Pygments (http://pygments.org/) will be used for the code tag, otherwise it will use <pre>code</pre> """ postmarkup = PostMarkup() postmarkup_add_tag = postmarkup.tag_factory.add_tag def add_tag(tag_class, name, *args, **kwargs): if include is None or name in include: if exclude is not None and name in exclude: return postmarkup_add_tag(tag_class, name, *args, **kwargs) add_tag(SimpleTag, 'b', 'strong') add_tag(SimpleTag, 'i', 'em') add_tag(SimpleTag, 'u', 'u') add_tag(SimpleTag, 's', 'strike') add_tag(LinkTag, 'link', **kwargs) add_tag(LinkTag, 'url', **kwargs) add_tag(QuoteTag, 'quote') add_tag(SearchTag, u'wiki', u"http://en.wikipedia.org/wiki/Special:Search?search=%s", u'wikipedia.com', **kwargs) add_tag(SearchTag, u'google', u"http://www.google.com/search?hl=en&q=%s&btnG=Google+Search", u'google.com', **kwargs) add_tag(SearchTag, u'dictionary', u"http://dictionary.reference.com/browse/%s", u'dictionary.com', **kwargs) add_tag(SearchTag, u'dict', u"http://dictionary.reference.com/browse/%s", u'dictionary.com', **kwargs) add_tag(ImgTag, u'img') add_tag(ListTag, u'list') add_tag(ListItemTag, u'*') add_tag(SizeTag, u"size") add_tag(ColorTag, u"color") add_tag(CenterTag, u"center") if use_pygments: assert pygments_available, "Install Pygments (http://pygments.org/) or call create with use_pygments=False" add_tag(PygmentsCodeTag, u'code', **kwargs) else: add_tag(CodeTag, u'code', **kwargs) return postmarkup _postmarkup = None def render_bbcode(bbcode, encoding="ascii", exclude_tags=None, auto_urls=True): """Renders a bbcode string in to XHTML. This is a shortcut if you don't need to customize any tags. bbcode -- A string containing the bbcode encoding -- If bbcode is not unicode, then then it will be encoded with this encoding (defaults to 'ascii'). Ignore the encoding if you already have a unicode string """ global _postmarkup if _postmarkup is None: _postmarkup = create(use_pygments=pygments_available, pygments_line_numbers=True) return _postmarkup(bbcode, encoding, exclude_tags=exclude_tags, auto_urls=auto_urls) class TagBase(object): def __init__(self, name, enclosed=False, auto_close=False, inline=False, strip_first_newline=False, **kwargs): """Base class for all tags. name -- The name of the bbcode tag enclosed -- True if the contents of the tag should not be bbcode processed. auto_close -- True if the tag is standalone and does not require a close tag. inline -- True if the tag generates an inline html tag. """ self.name = name self.enclosed = enclosed self.auto_close = auto_close self.inline = inline self.strip_first_newline = strip_first_newline self.open_pos = None self.close_pos = None self.open_node_index = None self.close_node_index = None def open(self, parser, params, open_pos, node_index): """ Called when the open tag is initially encountered. """ self.params = params self.open_pos = open_pos self.open_node_index = node_index def close(self, parser, close_pos, node_index): """ Called when the close tag is initially encountered. """ self.close_pos = close_pos self.close_node_index = node_index def render_open(self, parser, node_index): """ Called to render the open tag. """ pass def render_close(self, parser, node_index): """ Called to render the close tag. """ pass def get_contents(self, parser): """Returns the string between the open and close tag.""" return parser.markup[self.open_pos:self.close_pos] def get_contents_text(self, parser): """Returns the string between the the open and close tag, minus bbcode tags.""" return u"".join( parser.get_text_nodes(self.open_node_index, self.close_node_index) ) def skip_contents(self, parser): """Skips the contents of a tag while rendering.""" parser.skip_to_node(self.close_node_index) def __str__(self): return '[%s]'%self.name class SimpleTag(TagBase): """A tag that can be rendered with a simple substitution. """ def __init__(self, name, html_name, **kwargs): """ html_name -- the html tag to substitute.""" TagBase.__init__(self, name, inline=True) self.html_name = html_name def render_open(self, parser, node_index): return u"<%s>"%self.html_name def render_close(self, parser, node_index): return u"</%s>"%self.html_name class DivStyleTag(TagBase): """A simple tag that is replaces with a div and a style.""" def __init__(self, name, style, value, **kwargs): TagBase.__init__(self, name) self.style = style self.value = value def render_open(self, parser, node_index): return u'<div style="%s:%s;">' % (self.style, self.value) def render_close(self, parser, node_index): return u'</div>' class LinkTag(TagBase): def __init__(self, name, annotate_links=True, **kwargs): TagBase.__init__(self, name, inline=True) self.annotate_links = annotate_links def render_open(self, parser, node_index): self.domain = u'' tag_data = parser.tag_data nest_level = tag_data['link_nest_level'] = tag_data.setdefault('link_nest_level', 0) + 1 if nest_level > 1: return u"" if self.params: url = self.params.strip() else: url = self.get_contents_text(parser).strip() self.domain = "" #Unquote the url self.url = unquote(url) #Disallow javascript links if u"javascript:" in self.url.lower(): return "" #Disallow non http: links url_parsed = urlparse(self.url) if url_parsed[0] and not url_parsed[0].lower().startswith(u'http'): return "" #Prepend http: if it is not present if not url_parsed[0]: self.url="http://"+self.url url_parsed = urlparse(self.url) #Get domain self.domain = url_parsed[1].lower() #Remove www for brevity if self.domain.startswith(u'www.'): self.domain = self.domain[4:] #Quote the url #self.url="http:"+urlunparse( map(quote, (u"",)+url_parsed[1:]) ) self.url= unicode( urlunparse([quote(component, safe='/=&?:+') for component in url_parsed]) ) if not self.url: return u"" if self.domain: return u'<a href="%s">'%self.url else: return u"" def render_close(self, parser, node_index): tag_data = parser.tag_data tag_data['link_nest_level'] -= 1 if tag_data['link_nest_level'] > 0: return u'' if self.domain: return u'</a>'+self.annotate_link(self.domain) else: return u'' def annotate_link(self, domain=None): if domain and self.annotate_links: return annotate_link(domain) else: return u"" class QuoteTag(TagBase): def __init__(self, name, **kwargs): TagBase.__init__(self, name, strip_first_newline=True) def open(self, parser, *args): TagBase.open(self, parser, *args) def close(self, parser, *args): TagBase.close(self, parser, *args) def render_open(self, parser, node_index): if self.params: return u'<blockquote><em>%s</em><br/>'%(PostMarkup.standard_replace(self.params)) else: return u'<blockquote>' def render_close(self, parser, node_index): return u"</blockquote>" class SearchTag(TagBase): def __init__(self, name, url, label="", annotate_links=True, **kwargs): TagBase.__init__(self, name, inline=True) self.url = url self.label = label self.annotate_links = annotate_links def render_open(self, parser, node_idex): if self.params: search=self.params else: search=self.get_contents(parser) link = u'<a href="%s">' % self.url if u'%' in link: return link%quote_plus(search.encode("UTF-8")) else: return link def render_close(self, parser, node_index): if self.label: ret = u'</a>' if self.annotate_links: ret += annotate_link(self.label) return ret else: return u'' class PygmentsCodeTag(TagBase): def __init__(self, name, pygments_line_numbers=False, **kwargs): TagBase.__init__(self, name, enclosed=True, strip_first_newline=True) self.line_numbers = pygments_line_numbers def render_open(self, parser, node_index): contents = self.get_contents(parser) self.skip_contents(parser) try: lexer = get_lexer_by_name(self.params, stripall=True) except ClassNotFound: contents = _escape(contents) return '<div class="code"><pre>%s</pre></div>' % contents formatter = HtmlFormatter(linenos=self.line_numbers, cssclass="code") return highlight(contents, lexer, formatter) class CodeTag(TagBase): def __init__(self, name, **kwargs): TagBase.__init__(self, name, enclosed=True, strip_first_newline=True) def render_open(self, parser, node_index): contents = _escape(self.get_contents(parser)) self.skip_contents(parser) return '<div class="code"><pre>%s</pre></div>' % contents class ImgTag(TagBase): def __init__(self, name, **kwargs): TagBase.__init__(self, name, inline=True) def render_open(self, parser, node_index): contents = self.get_contents(parser) self.skip_contents(parser) contents = strip_bbcode(contents).replace(u'"', "%22") return u'<img src="%s"></img>' % contents class ListTag(TagBase): def __init__(self, name, **kwargs): TagBase.__init__(self, name, strip_first_newline=True) def open(self, parser, params, open_pos, node_index): TagBase.open(self, parser, params, open_pos, node_index) def close(self, parser, close_pos, node_index): TagBase.close(self, parser, close_pos, node_index) def render_open(self, parser, node_index): self.close_tag = u"" tag_data = parser.tag_data tag_data.setdefault("ListTag.count", 0) if tag_data["ListTag.count"]: return u"" tag_data["ListTag.count"] += 1 tag_data["ListItemTag.initial_item"]=True if self.params == "1": self.close_tag = u"</li></ol>" return u"<ol><li>" elif self.params == "a": self.close_tag = u"</li></ol>" return u'<ol style="list-style-type: lower-alpha;"><li>' elif self.params == "A": self.close_tag = u"</li></ol>" return u'<ol style="list-style-type: upper-alpha;"><li>' else: self.close_tag = u"</li></ul>" return u"<ul><li>" def render_close(self, parser, node_index): tag_data = parser.tag_data tag_data["ListTag.count"] -= 1 return self.close_tag class ListItemTag(TagBase): def __init__(self, name, **kwargs): TagBase.__init__(self, name) self.closed = False def render_open(self, parser, node_index): tag_data = parser.tag_data if not tag_data.setdefault("ListTag.count", 0): return u"" if tag_data["ListItemTag.initial_item"]: tag_data["ListItemTag.initial_item"] = False return return u"</li><li>" class SizeTag(TagBase): valid_chars = frozenset("0123456789") def __init__(self, name, **kwargs): TagBase.__init__(self, name, inline=True) def render_open(self, parser, node_index): try: self.size = int( "".join([c for c in self.params if c in self.valid_chars]) ) except ValueError: self.size = None if self.size is None: return u"" self.size = self.validate_size(self.size) return u'<span style="font-size:%spx">' % self.size def render_close(self, parser, node_index): if self.size is None: return u"" return u'</span>' def validate_size(self, size): size = min(64, size) size = max(4, size) return size class ColorTag(TagBase): valid_chars = frozenset("#0123456789abcdefghijklmnopqrstuvwxyz") def __init__(self, name, **kwargs): TagBase.__init__(self, name, inline=True) def render_open(self, parser, node_index): valid_chars = self.valid_chars color = self.params.split()[0:1][0].lower() self.color = "".join([c for c in color if c in valid_chars]) if not self.color: return u"" return u'<span style="color:%s">' % self.color def render_close(self, parser, node_index): if not self.color: return u'' return u'</span>' class CenterTag(TagBase): def render_open(self, parser, node_index, **kwargs): return u'<div style="text-align:center">' def render_close(self, parser, node_index): return u'</div>' # http://effbot.org/zone/python-replace.htm class MultiReplace: def __init__(self, repl_dict): # string to string mapping; use a regular expression keys = repl_dict.keys() keys.sort() # lexical order keys.reverse() # use longest match first pattern = u"|".join([re.escape(key) for key in keys]) self.pattern = re.compile(pattern) self.dict = repl_dict def replace(self, s): # apply replacement dictionary to string def repl(match, get=self.dict.get): item = match.group(0) return get(item, item) return self.pattern.sub(repl, s) __call__ = replace def _escape(s): return PostMarkup.standard_replace(s.rstrip('\n')) class TagFactory(object): def __init__(self): self.tags = {} @classmethod def tag_factory_callable(cls, tag_class, name, *args, **kwargs): """ Returns a callable that returns a new tag instance. """ def make(): return tag_class(name, *args, **kwargs) return make def add_tag(self, cls, name, *args, **kwargs): self.tags[name] = self.tag_factory_callable(cls, name, *args, **kwargs) def __getitem__(self, name): return self.tags[name]() def __contains__(self, name): return name in self.tags def get(self, name, default=None): if name in self.tags: return self.tags[name]() return default class _Parser(object): """ This is an interfaced to the parser, used by Tag classes. """ def __init__(self, post_markup): self.pm = post_markup self.tag_data = {} self.render_node_index = 0 def skip_to_node(self, node_index): """ Skips to a node, ignoring intermediate nodes. """ assert node_index is not None, "Node index must be non-None" self.render_node_index = node_index def get_text_nodes(self, node1, node2): """ Retrieves the text nodes between two node indices. """ if node2 is None: node2 = node1+1 return [node for node in self.nodes[node1:node2] if not callable(node)] def begin_no_breaks(self): """Disables replacing of newlines with break tags at the start and end of text nodes. Can only be called from a tags 'open' method. """ assert self.phase==1, "Can not be called from render_open or render_close" self.no_breaks_count += 1 def end_no_breaks(self): """Re-enables auto-replacing of newlines with break tags (see begin_no_breaks).""" assert self.phase==1, "Can not be called from render_open or render_close" if self.no_breaks_count: self.no_breaks_count -= 1 class PostMarkup(object): standard_replace = MultiReplace({ u'<':u'&lt;', u'>':u'&gt;', u'&':u'&amp;', u'\n':u'<br/>'}) standard_replace_no_break = MultiReplace({ u'<':u'&lt;', u'>':u'&gt;', u'&':u'&amp;',}) TOKEN_TAG, TOKEN_PTAG, TOKEN_TEXT = range(3) # I tried to use RE's. Really I did. @classmethod def tokenize(cls, post): text = True pos = 0 def find_first(post, pos, c): f1 = post.find(c[0], pos) f2 = post.find(c[1], pos) if f1 == -1: return f2 if f2 == -1: return f1 return min(f1, f2) while True: brace_pos = post.find(u'[', pos) if brace_pos == -1: if pos<len(post): yield PostMarkup.TOKEN_TEXT, post[pos:], pos, len(post) return if brace_pos - pos > 0: yield PostMarkup.TOKEN_TEXT, post[pos:brace_pos], pos, brace_pos pos = brace_pos end_pos = pos+1 open_tag_pos = post.find(u'[', end_pos) end_pos = find_first(post, end_pos, u']=') if end_pos == -1: yield PostMarkup.TOKEN_TEXT, post[pos:], pos, len(post) return if open_tag_pos != -1 and open_tag_pos < end_pos: yield PostMarkup.TOKEN_TEXT, post[pos:open_tag_pos], pos, open_tag_pos end_pos = open_tag_pos pos = end_pos continue if post[end_pos] == ']': yield PostMarkup.TOKEN_TAG, post[pos:end_pos+1], pos, end_pos+1 pos = end_pos+1 continue if post[end_pos] == '=': try: end_pos += 1 while post[end_pos] == ' ': end_pos += 1 if post[end_pos] != '"': end_pos = post.find(u']', end_pos+1) if end_pos == -1: return yield PostMarkup.TOKEN_TAG, post[pos:end_pos+1], pos, end_pos+1 else: end_pos = find_first(post, end_pos, u'"]') if end_pos==-1: return if post[end_pos] == '"': end_pos = post.find(u'"', end_pos+1) if end_pos == -1: return end_pos = post.find(u']', end_pos+1) if end_pos == -1: return yield PostMarkup.TOKEN_PTAG, post[pos:end_pos+1], pos, end_pos+1 else: yield PostMarkup.TOKEN_TAG, post[pos:end_pos+1], pos, end_pos pos = end_pos+1 except IndexError: return def tagify_urls(self, postmarkup ): """ Surrounds urls with url bbcode tags. """ def repl(match): return u'[url]%s[/url]' % match.group(0) text_tokens = [] for tag_type, tag_token, start_pos, end_pos in self.tokenize(postmarkup): if tag_type == PostMarkup.TOKEN_TEXT: text_tokens.append(re_url.sub(repl, tag_token)) else: text_tokens.append(tag_token) return u"".join(text_tokens) def __init__(self, tag_factory=None): self.tag_factory = tag_factory or TagFactory() def default_tags(self): """ Add some basic tags. """ add_tag = self.tag_factory.add_tag add_tag(SimpleTag, u'b', u'strong') add_tag(SimpleTag, u'i', u'em') add_tag(SimpleTag, u'u', u'u') add_tag(SimpleTag, u's', u's') def get_supported_tags(self): """ Returns a list of the supported tags. """ return sorted(self.tag_factory.tags.keys()) def render_to_html(self, post_markup, encoding="ascii", exclude_tags=None, auto_urls=True): """Converts Post Markup to XHTML. post_markup -- String containing bbcode. encoding -- Encoding of string, defaults to "ascii". exclude_tags -- A collection of tag names to ignore. auto_urls -- If True, then urls will be wrapped with url bbcode tags. """ if not isinstance(post_markup, unicode): post_markup = unicode(post_markup, encoding, 'replace') if auto_urls: post_markup = self.tagify_urls(post_markup) parser = _Parser(self) parser.markup = post_markup if exclude_tags is None: exclude_tags = [] tag_factory = self.tag_factory nodes = [] parser.nodes = nodes parser.phase = 1 parser.no_breaks_count = 0 enclosed_count = 0 open_stack = [] tag_stack = [] break_stack = [] remove_next_newline = False def check_tag_stack(tag_name): for tag in reversed(tag_stack): if tag_name == tag.name: return True return False def redo_break_stack(): while break_stack: tag = break_stack.pop() open_tag(tag) tag_stack.append(tag) def break_inline_tags(): while tag_stack: if tag_stack[-1].inline: tag = tag_stack.pop() close_tag(tag) break_stack.append(tag) else: break def open_tag(tag): def call(node_index): return tag.render_open(parser, node_index) nodes.append(call) def close_tag(tag): def call(node_index): return tag.render_close(parser, node_index) nodes.append(call) # Pass 1 for tag_type, tag_token, start_pos, end_pos in self.tokenize(post_markup): raw_tag_token = tag_token if tag_type == PostMarkup.TOKEN_TEXT: if parser.no_breaks_count: tag_token = tag_token.strip() if not tag_token: continue if remove_next_newline: tag_token = tag_token.lstrip(' ') if tag_token.startswith('\n'): tag_token = tag_token.lstrip(' ')[1:] if not tag_token: continue remove_next_newline = False if tag_stack and tag_stack[-1].strip_first_newline: tag_token = tag_token.lstrip() tag_stack[-1].strip_first_newline = False if not tag_stack[-1]: tag_stack.pop() continue if not enclosed_count: redo_break_stack() nodes.append(self.standard_replace(tag_token)) continue elif tag_type == PostMarkup.TOKEN_TAG: tag_token = tag_token[1:-1].lstrip() if ' ' in tag_token: tag_name, tag_attribs = tag_token.split(u' ', 1) tag_attribs = tag_attribs.strip() else: if '=' in tag_token: tag_name, tag_attribs = tag_token.split(u'=', 1) tag_attribs = tag_attribs.strip() else: tag_name = tag_token tag_attribs = u"" else: tag_token = tag_token[1:-1].lstrip() tag_name, tag_attribs = tag_token.split(u'=', 1) tag_attribs = tag_attribs.strip()[1:-1] tag_name = tag_name.strip().lower() end_tag = False if tag_name.startswith(u'/'): end_tag = True tag_name = tag_name[1:] if enclosed_count and tag_stack[-1].name != tag_name: continue if tag_name in exclude_tags: continue if not end_tag: tag = tag_factory.get(tag_name, None) if tag is None: continue redo_break_stack() if not tag.inline: break_inline_tags() tag.open(parser, tag_attribs, end_pos, len(nodes)) if tag.enclosed: enclosed_count += 1 tag_stack.append(tag) open_tag(tag) if tag.auto_close: tag = tag_stack.pop() tag.close(self, start_pos, len(nodes)-1) close_tag(tag) else: if check_tag_stack(tag_name): while tag_stack[-1].name != tag_name: tag = tag_stack.pop() break_stack.append(tag) close_tag(tag) tag = tag_stack.pop() tag.close(parser, start_pos, len(nodes)) if tag.enclosed: enclosed_count -= 1 close_tag(tag) if not tag.inline: remove_next_newline = True if tag_stack: redo_break_stack() while tag_stack: tag = tag_stack.pop() tag.close(parser, len(post_markup), len(nodes)) if tag.enclosed: enclosed_count -= 1 close_tag(tag) parser.phase = 2 # Pass 2 parser.nodes = nodes text = [] parser.render_node_index = 0 while parser.render_node_index < len(parser.nodes): i = parser.render_node_index node_text = parser.nodes[i] if callable(node_text): node_text = node_text(i) if node_text is not None: text.append(node_text) parser.render_node_index += 1 return u"".join(text) __call__ = render_to_html def _tests(): import sys #sys.stdout=open('test.htm', 'w') post_markup = create(use_pygments=True) tests = [] print """<link rel="stylesheet" href="code.css" type="text/css" />\n""" tests.append(']') tests.append('[') tests.append(':-[ Hello, [b]World[/b]') tests.append("[link=http://www.willmcgugan.com]My homepage[/link]") tests.append('[link="http://www.willmcgugan.com"]My homepage[/link]') tests.append("[link http://www.willmcgugan.com]My homepage[/link]") tests.append("[link]http://www.willmcgugan.com[/link]") tests.append(u"[b]Hello André[/b]") tests.append(u"[google]André[/google]") tests.append("[s]Strike through[/s]") tests.append("[b]bold [i]bold and italic[/b] italic[/i]") tests.append("[google]Will McGugan[/google]") tests.append("[wiki Will McGugan]Look up my name in Wikipedia[/wiki]") tests.append("[quote Will said...]BBCode is very cool[/quote]") tests.append("""[code python] # A proxy object that calls a callback when converted to a string class TagStringify(object): def __init__(self, callback, raw): self.callback = callback self.raw = raw r[b]=3 def __str__(self): return self.callback() def __repr__(self): return self.__str__() [/code]""") tests.append(u"[img]http://upload.wikimedia.org/wikipedia/commons"\ "/6/61/Triops_longicaudatus.jpg[/img]") tests.append("[list][*]Apples[*]Oranges[*]Pears[/list]") tests.append("""[list=1] [*]Apples [*]Oranges are not the only fruit [*]Pears [/list]""") tests.append("[list=a][*]Apples[*]Oranges[*]Pears[/list]") tests.append("[list=A][*]Apples[*]Oranges[*]Pears[/list]") long_test="""[b]Long test[/b] New lines characters are converted to breaks."""\ """Tags my be [b]ove[i]rl[/b]apped[/i]. [i]Open tags will be closed. [b]Test[/b]""" tests.append(long_test) tests.append("[dict]Will[/dict]") tests.append("[code unknownlanguage]10 print 'In yr code'; 20 goto 10[/code]") tests.append("[url=http://www.google.com/coop/cse?cx=006850030468302103399%3Amqxv78bdfdo]CakePHP Google Groups[/url]") tests.append("[url=http://www.google.com/search?hl=en&safe=off&client=opera&rls=en&hs=pO1&q=python+bbcode&btnG=Search]Search for Python BBCode[/url]") #tests = [] # Attempt to inject html in to unicode tests.append("[url=http://www.test.com/sfsdfsdf/ter?t=\"></a><h1>HACK</h1><a>\"]Test Hack[/url]") tests.append('Nested urls, i.e. [url][url]www.becontrary.com[/url][/url], are condensed in to a single tag.') tests.append(u'[google]ɸβfvθðsz[/google]') tests.append(u'[size 30]Hello, World![/size]') tests.append(u'[color red]This should be red[/color]') tests.append(u'[color #0f0]This should be green[/color]') tests.append(u"[center]This should be in the center!") tests.append('Nested urls, i.e. [url][url]www.becontrary.com[/url][/url], are condensed in to a single tag.') #tests = [] tests.append('[b]Hello, [i]World[/b]! [/i]') tests.append('[b][center]This should be centered![/center][/b]') tests.append('[list][*]Hello[i][*]World![/i][/list]') tests.append("""[list=1] [*]Apples [*]Oranges are not the only fruit [*]Pears [/list]""") tests.append("[b]urls such as http://www.willmcgugan.com are authomaticaly converted to links[/b]") tests = [] tests.append(""" [b] [code python] parser.markup[self.open_pos:self.close_pos] [/code] asdasdasdasdqweqwe """) tests = ["""[list 1] [*]Hello [*]World [/list]"""] for test in tests: print u"<pre>%s</pre>"%str(test.encode("ascii", "xmlcharrefreplace")) print u"<p>%s</p>"%str(post_markup(test).encode("ascii", "xmlcharrefreplace")) print u"<hr/>" print #print render_bbcode("[b]For the lazy, use the http://www.willmcgugan.com render_bbcode function.[/b]") def _run_unittests(): # TODO: Expand tests for better coverage! import unittest class TestPostmarkup(unittest.TestCase): def testsimpletag(self): postmarkup = create() tests= [ ('[b]Hello[/b]', "<strong>Hello</strong>"), ('[i]Italic[/i]', "<em>Italic</em>"), ('[s]Strike[/s]', "<strike>Strike</strike>"), ('[u]underlined[/u]', "<u>underlined</u>"), ] for test, result in tests: self.assertEqual(postmarkup(test), result) def testoverlap(self): postmarkup = create() tests= [ ('[i][b]Hello[/i][/b]', "<em><strong>Hello</strong></em>"), ('[b]bold [u]both[/b] underline[/u]', '<strong>bold <u>both</u></strong><u> underline</u>') ] for test, result in tests: self.assertEqual(postmarkup(test), result) def testlinks(self): postmarkup = create(annotate_links=False) tests= [ ('[link=http://www.willmcgugan.com]blog1[/link]', '<a href="http://www.willmcgugan.com">blog1</a>'), ('[link="http://www.willmcgugan.com"]blog2[/link]', '<a href="http://www.willmcgugan.com">blog2</a>'), ('[link http://www.willmcgugan.com]blog3[/link]', '<a href="http://www.willmcgugan.com">blog3</a>'), ('[link]http://www.willmcgugan.com[/link]', '<a href="http://www.willmcgugan.com">http://www.willmcgugan.com</a>') ] for test, result in tests: self.assertEqual(postmarkup(test), result) suite = unittest.TestLoader().loadTestsFromTestCase(TestPostmarkup) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == "__main__": #_tests() _run_unittests()
andymg/androguard
refs/heads/master
demos/apk_format_2.py
63
#!/usr/bin/env python import sys PATH_INSTALL = "./" sys.path.append( PATH_INSTALL ) from androguard.core.bytecodes import dvm, apk TEST = "./apks/crash/mikecc/e0399fdd481992bc049b6e9d765da7f007f89875.apk" a = apk.APK( TEST, zipmodule=2 ) a.show() j = dvm.DalvikVMFormat( a.get_dex() ) # SHOW CLASS (verbose) #j.show()
fengbaicanhe/intellij-community
refs/heads/master
python/testData/codeInsight/smartEnter/withOnlyColonMissing.py
80
with open('file.txt') as f<caret>