repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
palerdot/calibre
src/chardet/mbcssm.py
215
18214
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from constants import eStart, eError, eItsMe # BIG5 BIG5_cls = ( \ 1,1,1,1,1,1,1,1, # 00 - 07 #allow 0x00 as legal value 1,1,1,1,1,1,0,0, # 08 - 0f 1,1,1,1,1,1,1,1, # 10 - 17 1,1,1,0,1,1,1,1, # 18 - 1f 1,1,1,1,1,1,1,1, # 20 - 27 1,1,1,1,1,1,1,1, # 28 - 2f 1,1,1,1,1,1,1,1, # 30 - 37 1,1,1,1,1,1,1,1, # 38 - 3f 2,2,2,2,2,2,2,2, # 40 - 47 2,2,2,2,2,2,2,2, # 48 - 4f 2,2,2,2,2,2,2,2, # 50 - 57 2,2,2,2,2,2,2,2, # 58 - 5f 2,2,2,2,2,2,2,2, # 60 - 67 2,2,2,2,2,2,2,2, # 68 - 6f 2,2,2,2,2,2,2,2, # 70 - 77 2,2,2,2,2,2,2,1, # 78 - 7f 4,4,4,4,4,4,4,4, # 80 - 87 4,4,4,4,4,4,4,4, # 88 - 8f 4,4,4,4,4,4,4,4, # 90 - 97 4,4,4,4,4,4,4,4, # 98 - 9f 4,3,3,3,3,3,3,3, # a0 - a7 3,3,3,3,3,3,3,3, # a8 - af 3,3,3,3,3,3,3,3, # b0 - b7 3,3,3,3,3,3,3,3, # b8 - bf 3,3,3,3,3,3,3,3, # c0 - c7 3,3,3,3,3,3,3,3, # c8 - cf 3,3,3,3,3,3,3,3, # d0 - d7 3,3,3,3,3,3,3,3, # d8 - df 3,3,3,3,3,3,3,3, # e0 - e7 3,3,3,3,3,3,3,3, # e8 - ef 3,3,3,3,3,3,3,3, # f0 - f7 3,3,3,3,3,3,3,0) # f8 - ff BIG5_st = ( \ eError,eStart,eStart, 3,eError,eError,eError,eError,#00-07 eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eError,#08-0f eError,eStart,eStart,eStart,eStart,eStart,eStart,eStart)#10-17 Big5CharLenTable = (0, 1, 1, 2, 0) Big5SMModel = {'classTable': BIG5_cls, 'classFactor': 5, 'stateTable': BIG5_st, 'charLenTable': Big5CharLenTable, 'name': 'Big5'} # EUC-JP EUCJP_cls = ( \ 4,4,4,4,4,4,4,4, # 00 - 07 4,4,4,4,4,4,5,5, # 08 - 0f 4,4,4,4,4,4,4,4, # 10 - 17 4,4,4,5,4,4,4,4, # 18 - 1f 4,4,4,4,4,4,4,4, # 20 - 27 4,4,4,4,4,4,4,4, # 28 - 2f 4,4,4,4,4,4,4,4, # 30 - 37 4,4,4,4,4,4,4,4, # 38 - 3f 4,4,4,4,4,4,4,4, # 40 - 47 4,4,4,4,4,4,4,4, # 48 - 4f 4,4,4,4,4,4,4,4, # 50 - 57 4,4,4,4,4,4,4,4, # 58 - 5f 4,4,4,4,4,4,4,4, # 60 - 67 4,4,4,4,4,4,4,4, # 68 - 6f 4,4,4,4,4,4,4,4, # 70 - 77 4,4,4,4,4,4,4,4, # 78 - 7f 5,5,5,5,5,5,5,5, # 80 - 87 5,5,5,5,5,5,1,3, # 88 - 8f 5,5,5,5,5,5,5,5, # 90 - 97 5,5,5,5,5,5,5,5, # 98 - 9f 5,2,2,2,2,2,2,2, # a0 - a7 2,2,2,2,2,2,2,2, # a8 - af 2,2,2,2,2,2,2,2, # b0 - b7 2,2,2,2,2,2,2,2, # b8 - bf 2,2,2,2,2,2,2,2, # c0 - c7 2,2,2,2,2,2,2,2, # c8 - cf 2,2,2,2,2,2,2,2, # d0 - d7 2,2,2,2,2,2,2,2, # d8 - df 0,0,0,0,0,0,0,0, # e0 - e7 0,0,0,0,0,0,0,0, # e8 - ef 0,0,0,0,0,0,0,0, # f0 - f7 0,0,0,0,0,0,0,5) # f8 - ff EUCJP_st = ( \ 3, 4, 3, 5,eStart,eError,eError,eError,#00-07 eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,#08-0f eItsMe,eItsMe,eStart,eError,eStart,eError,eError,eError,#10-17 eError,eError,eStart,eError,eError,eError, 3,eError,#18-1f 3,eError,eError,eError,eStart,eStart,eStart,eStart)#20-27 EUCJPCharLenTable = (2, 2, 2, 3, 1, 0) EUCJPSMModel = {'classTable': EUCJP_cls, 'classFactor': 6, 'stateTable': EUCJP_st, 'charLenTable': EUCJPCharLenTable, 'name': 'EUC-JP'} # EUC-KR EUCKR_cls = ( \ 1,1,1,1,1,1,1,1, # 00 - 07 1,1,1,1,1,1,0,0, # 08 - 0f 1,1,1,1,1,1,1,1, # 10 - 17 1,1,1,0,1,1,1,1, # 18 - 1f 1,1,1,1,1,1,1,1, # 20 - 27 1,1,1,1,1,1,1,1, # 28 - 2f 1,1,1,1,1,1,1,1, # 30 - 37 1,1,1,1,1,1,1,1, # 38 - 3f 1,1,1,1,1,1,1,1, # 40 - 47 1,1,1,1,1,1,1,1, # 48 - 4f 1,1,1,1,1,1,1,1, # 50 - 57 1,1,1,1,1,1,1,1, # 58 - 5f 1,1,1,1,1,1,1,1, # 60 - 67 1,1,1,1,1,1,1,1, # 68 - 6f 1,1,1,1,1,1,1,1, # 70 - 77 1,1,1,1,1,1,1,1, # 78 - 7f 0,0,0,0,0,0,0,0, # 80 - 87 0,0,0,0,0,0,0,0, # 88 - 8f 0,0,0,0,0,0,0,0, # 90 - 97 0,0,0,0,0,0,0,0, # 98 - 9f 0,2,2,2,2,2,2,2, # a0 - a7 2,2,2,2,2,3,3,3, # a8 - af 2,2,2,2,2,2,2,2, # b0 - b7 2,2,2,2,2,2,2,2, # b8 - bf 2,2,2,2,2,2,2,2, # c0 - c7 2,3,2,2,2,2,2,2, # c8 - cf 2,2,2,2,2,2,2,2, # d0 - d7 2,2,2,2,2,2,2,2, # d8 - df 2,2,2,2,2,2,2,2, # e0 - e7 2,2,2,2,2,2,2,2, # e8 - ef 2,2,2,2,2,2,2,2, # f0 - f7 2,2,2,2,2,2,2,0) # f8 - ff EUCKR_st = ( eError,eStart, 3,eError,eError,eError,eError,eError,#00-07 eItsMe,eItsMe,eItsMe,eItsMe,eError,eError,eStart,eStart)#08-0f EUCKRCharLenTable = (0, 1, 2, 0) EUCKRSMModel = {'classTable': EUCKR_cls, 'classFactor': 4, 'stateTable': EUCKR_st, 'charLenTable': EUCKRCharLenTable, 'name': 'EUC-KR'} # EUC-TW EUCTW_cls = ( \ 2,2,2,2,2,2,2,2, # 00 - 07 2,2,2,2,2,2,0,0, # 08 - 0f 2,2,2,2,2,2,2,2, # 10 - 17 2,2,2,0,2,2,2,2, # 18 - 1f 2,2,2,2,2,2,2,2, # 20 - 27 2,2,2,2,2,2,2,2, # 28 - 2f 2,2,2,2,2,2,2,2, # 30 - 37 2,2,2,2,2,2,2,2, # 38 - 3f 2,2,2,2,2,2,2,2, # 40 - 47 2,2,2,2,2,2,2,2, # 48 - 4f 2,2,2,2,2,2,2,2, # 50 - 57 2,2,2,2,2,2,2,2, # 58 - 5f 2,2,2,2,2,2,2,2, # 60 - 67 2,2,2,2,2,2,2,2, # 68 - 6f 2,2,2,2,2,2,2,2, # 70 - 77 2,2,2,2,2,2,2,2, # 78 - 7f 0,0,0,0,0,0,0,0, # 80 - 87 0,0,0,0,0,0,6,0, # 88 - 8f 0,0,0,0,0,0,0,0, # 90 - 97 0,0,0,0,0,0,0,0, # 98 - 9f 0,3,4,4,4,4,4,4, # a0 - a7 5,5,1,1,1,1,1,1, # a8 - af 1,1,1,1,1,1,1,1, # b0 - b7 1,1,1,1,1,1,1,1, # b8 - bf 1,1,3,1,3,3,3,3, # c0 - c7 3,3,3,3,3,3,3,3, # c8 - cf 3,3,3,3,3,3,3,3, # d0 - d7 3,3,3,3,3,3,3,3, # d8 - df 3,3,3,3,3,3,3,3, # e0 - e7 3,3,3,3,3,3,3,3, # e8 - ef 3,3,3,3,3,3,3,3, # f0 - f7 3,3,3,3,3,3,3,0) # f8 - ff EUCTW_st = ( \ eError,eError,eStart, 3, 3, 3, 4,eError,#00-07 eError,eError,eError,eError,eError,eError,eItsMe,eItsMe,#08-0f eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eError,eStart,eError,#10-17 eStart,eStart,eStart,eError,eError,eError,eError,eError,#18-1f 5,eError,eError,eError,eStart,eError,eStart,eStart,#20-27 eStart,eError,eStart,eStart,eStart,eStart,eStart,eStart)#28-2f EUCTWCharLenTable = (0, 0, 1, 2, 2, 2, 3) EUCTWSMModel = {'classTable': EUCTW_cls, 'classFactor': 7, 'stateTable': EUCTW_st, 'charLenTable': EUCTWCharLenTable, 'name': 'x-euc-tw'} # GB2312 GB2312_cls = ( \ 1,1,1,1,1,1,1,1, # 00 - 07 1,1,1,1,1,1,0,0, # 08 - 0f 1,1,1,1,1,1,1,1, # 10 - 17 1,1,1,0,1,1,1,1, # 18 - 1f 1,1,1,1,1,1,1,1, # 20 - 27 1,1,1,1,1,1,1,1, # 28 - 2f 3,3,3,3,3,3,3,3, # 30 - 37 3,3,1,1,1,1,1,1, # 38 - 3f 2,2,2,2,2,2,2,2, # 40 - 47 2,2,2,2,2,2,2,2, # 48 - 4f 2,2,2,2,2,2,2,2, # 50 - 57 2,2,2,2,2,2,2,2, # 58 - 5f 2,2,2,2,2,2,2,2, # 60 - 67 2,2,2,2,2,2,2,2, # 68 - 6f 2,2,2,2,2,2,2,2, # 70 - 77 2,2,2,2,2,2,2,4, # 78 - 7f 5,6,6,6,6,6,6,6, # 80 - 87 6,6,6,6,6,6,6,6, # 88 - 8f 6,6,6,6,6,6,6,6, # 90 - 97 6,6,6,6,6,6,6,6, # 98 - 9f 6,6,6,6,6,6,6,6, # a0 - a7 6,6,6,6,6,6,6,6, # a8 - af 6,6,6,6,6,6,6,6, # b0 - b7 6,6,6,6,6,6,6,6, # b8 - bf 6,6,6,6,6,6,6,6, # c0 - c7 6,6,6,6,6,6,6,6, # c8 - cf 6,6,6,6,6,6,6,6, # d0 - d7 6,6,6,6,6,6,6,6, # d8 - df 6,6,6,6,6,6,6,6, # e0 - e7 6,6,6,6,6,6,6,6, # e8 - ef 6,6,6,6,6,6,6,6, # f0 - f7 6,6,6,6,6,6,6,0) # f8 - ff GB2312_st = ( \ eError,eStart,eStart,eStart,eStart,eStart, 3,eError,#00-07 eError,eError,eError,eError,eError,eError,eItsMe,eItsMe,#08-0f eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eError,eError,eStart,#10-17 4,eError,eStart,eStart,eError,eError,eError,eError,#18-1f eError,eError, 5,eError,eError,eError,eItsMe,eError,#20-27 eError,eError,eStart,eStart,eStart,eStart,eStart,eStart)#28-2f # To be accurate, the length of class 6 can be either 2 or 4. # But it is not necessary to discriminate between the two since # it is used for frequency analysis only, and we are validing # each code range there as well. So it is safe to set it to be # 2 here. GB2312CharLenTable = (0, 1, 1, 1, 1, 1, 2) GB2312SMModel = {'classTable': GB2312_cls, 'classFactor': 7, 'stateTable': GB2312_st, 'charLenTable': GB2312CharLenTable, 'name': 'GB2312'} # Shift_JIS SJIS_cls = ( \ 1,1,1,1,1,1,1,1, # 00 - 07 1,1,1,1,1,1,0,0, # 08 - 0f 1,1,1,1,1,1,1,1, # 10 - 17 1,1,1,0,1,1,1,1, # 18 - 1f 1,1,1,1,1,1,1,1, # 20 - 27 1,1,1,1,1,1,1,1, # 28 - 2f 1,1,1,1,1,1,1,1, # 30 - 37 1,1,1,1,1,1,1,1, # 38 - 3f 2,2,2,2,2,2,2,2, # 40 - 47 2,2,2,2,2,2,2,2, # 48 - 4f 2,2,2,2,2,2,2,2, # 50 - 57 2,2,2,2,2,2,2,2, # 58 - 5f 2,2,2,2,2,2,2,2, # 60 - 67 2,2,2,2,2,2,2,2, # 68 - 6f 2,2,2,2,2,2,2,2, # 70 - 77 2,2,2,2,2,2,2,1, # 78 - 7f 3,3,3,3,3,3,3,3, # 80 - 87 3,3,3,3,3,3,3,3, # 88 - 8f 3,3,3,3,3,3,3,3, # 90 - 97 3,3,3,3,3,3,3,3, # 98 - 9f #0xa0 is illegal in sjis encoding, but some pages does #contain such byte. We need to be more error forgiven. 2,2,2,2,2,2,2,2, # a0 - a7 2,2,2,2,2,2,2,2, # a8 - af 2,2,2,2,2,2,2,2, # b0 - b7 2,2,2,2,2,2,2,2, # b8 - bf 2,2,2,2,2,2,2,2, # c0 - c7 2,2,2,2,2,2,2,2, # c8 - cf 2,2,2,2,2,2,2,2, # d0 - d7 2,2,2,2,2,2,2,2, # d8 - df 3,3,3,3,3,3,3,3, # e0 - e7 3,3,3,3,3,4,4,4, # e8 - ef 4,4,4,4,4,4,4,4, # f0 - f7 4,4,4,4,4,0,0,0) # f8 - ff SJIS_st = ( \ eError,eStart,eStart, 3,eError,eError,eError,eError,#00-07 eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,#08-0f eItsMe,eItsMe,eError,eError,eStart,eStart,eStart,eStart)#10-17 SJISCharLenTable = (0, 1, 1, 2, 0, 0) SJISSMModel = {'classTable': SJIS_cls, 'classFactor': 6, 'stateTable': SJIS_st, 'charLenTable': SJISCharLenTable, 'name': 'Shift_JIS'} # UCS2-BE UCS2BE_cls = ( \ 0,0,0,0,0,0,0,0, # 00 - 07 0,0,1,0,0,2,0,0, # 08 - 0f 0,0,0,0,0,0,0,0, # 10 - 17 0,0,0,3,0,0,0,0, # 18 - 1f 0,0,0,0,0,0,0,0, # 20 - 27 0,3,3,3,3,3,0,0, # 28 - 2f 0,0,0,0,0,0,0,0, # 30 - 37 0,0,0,0,0,0,0,0, # 38 - 3f 0,0,0,0,0,0,0,0, # 40 - 47 0,0,0,0,0,0,0,0, # 48 - 4f 0,0,0,0,0,0,0,0, # 50 - 57 0,0,0,0,0,0,0,0, # 58 - 5f 0,0,0,0,0,0,0,0, # 60 - 67 0,0,0,0,0,0,0,0, # 68 - 6f 0,0,0,0,0,0,0,0, # 70 - 77 0,0,0,0,0,0,0,0, # 78 - 7f 0,0,0,0,0,0,0,0, # 80 - 87 0,0,0,0,0,0,0,0, # 88 - 8f 0,0,0,0,0,0,0,0, # 90 - 97 0,0,0,0,0,0,0,0, # 98 - 9f 0,0,0,0,0,0,0,0, # a0 - a7 0,0,0,0,0,0,0,0, # a8 - af 0,0,0,0,0,0,0,0, # b0 - b7 0,0,0,0,0,0,0,0, # b8 - bf 0,0,0,0,0,0,0,0, # c0 - c7 0,0,0,0,0,0,0,0, # c8 - cf 0,0,0,0,0,0,0,0, # d0 - d7 0,0,0,0,0,0,0,0, # d8 - df 0,0,0,0,0,0,0,0, # e0 - e7 0,0,0,0,0,0,0,0, # e8 - ef 0,0,0,0,0,0,0,0, # f0 - f7 0,0,0,0,0,0,4,5) # f8 - ff UCS2BE_st = ( \ 5, 7, 7,eError, 4, 3,eError,eError,#00-07 eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,#08-0f eItsMe,eItsMe, 6, 6, 6, 6,eError,eError,#10-17 6, 6, 6, 6, 6,eItsMe, 6, 6,#18-1f 6, 6, 6, 6, 5, 7, 7,eError,#20-27 5, 8, 6, 6,eError, 6, 6, 6,#28-2f 6, 6, 6, 6,eError,eError,eStart,eStart)#30-37 UCS2BECharLenTable = (2, 2, 2, 0, 2, 2) UCS2BESMModel = {'classTable': UCS2BE_cls, 'classFactor': 6, 'stateTable': UCS2BE_st, 'charLenTable': UCS2BECharLenTable, 'name': 'UTF-16BE'} # UCS2-LE UCS2LE_cls = ( \ 0,0,0,0,0,0,0,0, # 00 - 07 0,0,1,0,0,2,0,0, # 08 - 0f 0,0,0,0,0,0,0,0, # 10 - 17 0,0,0,3,0,0,0,0, # 18 - 1f 0,0,0,0,0,0,0,0, # 20 - 27 0,3,3,3,3,3,0,0, # 28 - 2f 0,0,0,0,0,0,0,0, # 30 - 37 0,0,0,0,0,0,0,0, # 38 - 3f 0,0,0,0,0,0,0,0, # 40 - 47 0,0,0,0,0,0,0,0, # 48 - 4f 0,0,0,0,0,0,0,0, # 50 - 57 0,0,0,0,0,0,0,0, # 58 - 5f 0,0,0,0,0,0,0,0, # 60 - 67 0,0,0,0,0,0,0,0, # 68 - 6f 0,0,0,0,0,0,0,0, # 70 - 77 0,0,0,0,0,0,0,0, # 78 - 7f 0,0,0,0,0,0,0,0, # 80 - 87 0,0,0,0,0,0,0,0, # 88 - 8f 0,0,0,0,0,0,0,0, # 90 - 97 0,0,0,0,0,0,0,0, # 98 - 9f 0,0,0,0,0,0,0,0, # a0 - a7 0,0,0,0,0,0,0,0, # a8 - af 0,0,0,0,0,0,0,0, # b0 - b7 0,0,0,0,0,0,0,0, # b8 - bf 0,0,0,0,0,0,0,0, # c0 - c7 0,0,0,0,0,0,0,0, # c8 - cf 0,0,0,0,0,0,0,0, # d0 - d7 0,0,0,0,0,0,0,0, # d8 - df 0,0,0,0,0,0,0,0, # e0 - e7 0,0,0,0,0,0,0,0, # e8 - ef 0,0,0,0,0,0,0,0, # f0 - f7 0,0,0,0,0,0,4,5) # f8 - ff UCS2LE_st = ( \ 6, 6, 7, 6, 4, 3,eError,eError,#00-07 eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,#08-0f eItsMe,eItsMe, 5, 5, 5,eError,eItsMe,eError,#10-17 5, 5, 5,eError, 5,eError, 6, 6,#18-1f 7, 6, 8, 8, 5, 5, 5,eError,#20-27 5, 5, 5,eError,eError,eError, 5, 5,#28-2f 5, 5, 5,eError, 5,eError,eStart,eStart)#30-37 UCS2LECharLenTable = (2, 2, 2, 2, 2, 2) UCS2LESMModel = {'classTable': UCS2LE_cls, 'classFactor': 6, 'stateTable': UCS2LE_st, 'charLenTable': UCS2LECharLenTable, 'name': 'UTF-16LE'} # UTF-8 UTF8_cls = ( \ 1,1,1,1,1,1,1,1, # 00 - 07 #allow 0x00 as a legal value 1,1,1,1,1,1,0,0, # 08 - 0f 1,1,1,1,1,1,1,1, # 10 - 17 1,1,1,0,1,1,1,1, # 18 - 1f 1,1,1,1,1,1,1,1, # 20 - 27 1,1,1,1,1,1,1,1, # 28 - 2f 1,1,1,1,1,1,1,1, # 30 - 37 1,1,1,1,1,1,1,1, # 38 - 3f 1,1,1,1,1,1,1,1, # 40 - 47 1,1,1,1,1,1,1,1, # 48 - 4f 1,1,1,1,1,1,1,1, # 50 - 57 1,1,1,1,1,1,1,1, # 58 - 5f 1,1,1,1,1,1,1,1, # 60 - 67 1,1,1,1,1,1,1,1, # 68 - 6f 1,1,1,1,1,1,1,1, # 70 - 77 1,1,1,1,1,1,1,1, # 78 - 7f 2,2,2,2,3,3,3,3, # 80 - 87 4,4,4,4,4,4,4,4, # 88 - 8f 4,4,4,4,4,4,4,4, # 90 - 97 4,4,4,4,4,4,4,4, # 98 - 9f 5,5,5,5,5,5,5,5, # a0 - a7 5,5,5,5,5,5,5,5, # a8 - af 5,5,5,5,5,5,5,5, # b0 - b7 5,5,5,5,5,5,5,5, # b8 - bf 0,0,6,6,6,6,6,6, # c0 - c7 6,6,6,6,6,6,6,6, # c8 - cf 6,6,6,6,6,6,6,6, # d0 - d7 6,6,6,6,6,6,6,6, # d8 - df 7,8,8,8,8,8,8,8, # e0 - e7 8,8,8,8,8,9,8,8, # e8 - ef 10,11,11,11,11,11,11,11, # f0 - f7 12,13,13,13,14,15,0,0) # f8 - ff UTF8_st = ( \ eError,eStart,eError,eError,eError,eError, 12, 10,#00-07 9, 11, 8, 7, 6, 5, 4, 3,#08-0f eError,eError,eError,eError,eError,eError,eError,eError,#10-17 eError,eError,eError,eError,eError,eError,eError,eError,#18-1f eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,#20-27 eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,#28-2f eError,eError, 5, 5, 5, 5,eError,eError,#30-37 eError,eError,eError,eError,eError,eError,eError,eError,#38-3f eError,eError,eError, 5, 5, 5,eError,eError,#40-47 eError,eError,eError,eError,eError,eError,eError,eError,#48-4f eError,eError, 7, 7, 7, 7,eError,eError,#50-57 eError,eError,eError,eError,eError,eError,eError,eError,#58-5f eError,eError,eError,eError, 7, 7,eError,eError,#60-67 eError,eError,eError,eError,eError,eError,eError,eError,#68-6f eError,eError, 9, 9, 9, 9,eError,eError,#70-77 eError,eError,eError,eError,eError,eError,eError,eError,#78-7f eError,eError,eError,eError,eError, 9,eError,eError,#80-87 eError,eError,eError,eError,eError,eError,eError,eError,#88-8f eError,eError, 12, 12, 12, 12,eError,eError,#90-97 eError,eError,eError,eError,eError,eError,eError,eError,#98-9f eError,eError,eError,eError,eError, 12,eError,eError,#a0-a7 eError,eError,eError,eError,eError,eError,eError,eError,#a8-af eError,eError, 12, 12, 12,eError,eError,eError,#b0-b7 eError,eError,eError,eError,eError,eError,eError,eError,#b8-bf eError,eError,eStart,eStart,eStart,eStart,eError,eError,#c0-c7 eError,eError,eError,eError,eError,eError,eError,eError)#c8-cf UTF8CharLenTable = (0, 1, 0, 0, 0, 0, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6) UTF8SMModel = {'classTable': UTF8_cls, 'classFactor': 16, 'stateTable': UTF8_st, 'charLenTable': UTF8CharLenTable, 'name': 'UTF-8'}
gpl-3.0
Gussy/bigcouch
couchjs/scons/scons-local-2.0.1/SCons/Tool/packaging/src_targz.py
61
1746
"""SCons.Tool.Packaging.targz The targz SRC packager. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/packaging/src_targz.py 5134 2010/08/16 23:02:40 bdeegan" from SCons.Tool.packaging import putintopackageroot def package(env, target, source, PACKAGEROOT, **kw): bld = env['BUILDERS']['Tar'] bld.set_suffix('.tar.gz') target, source = putintopackageroot(target, source, env, PACKAGEROOT, honor_install_location=0) return bld(env, target, source, TARFLAGS='-zc') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
apache-2.0
alex/warehouse
tests/unit/test_recaptcha.py
1
8023
# 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 socket import urllib.parse import pytest import pretend import requests import responses from warehouse import recaptcha _SETTINGS = { "recaptcha.site_key": "site_key_value", "recaptcha.secret_key": "secret_key_value", } _REQUEST = pretend.stub( # returning a real requests.Session object because responses is responsible # for mocking that out http=requests.Session(), registry=pretend.stub( settings=_SETTINGS, ), ) class TestVerifyResponse: @responses.activate def test_verify_service_disabled(self): responses.add( responses.POST, recaptcha.VERIFY_URL, body="", ) serv = recaptcha.Service( pretend.stub(registry=pretend.stub(settings={})) ) assert serv.verify_response('') is None assert not responses.calls @responses.activate def test_verify_service_disabled_with_none(self): responses.add( responses.POST, recaptcha.VERIFY_URL, body="", ) serv = recaptcha.Service( pretend.stub( registry=pretend.stub( settings={ "recaptcha.site_key": None, "recaptcha.secret_key": None, }, ), ), ) assert serv.verify_response('') is None assert not responses.calls @responses.activate def test_remote_ip_payload(self): responses.add( responses.POST, recaptcha.VERIFY_URL, json={"success": True}, ) serv = recaptcha.Service(_REQUEST) serv.verify_response("meaningless", remote_ip="ip") payload = dict(urllib.parse.parse_qsl(responses.calls[0].request.body)) assert payload["remoteip"] == "ip" @responses.activate def test_unexpected_data_error(self): responses.add( responses.POST, recaptcha.VERIFY_URL, body="something awful", ) serv = recaptcha.Service(_REQUEST) with pytest.raises(recaptcha.UnexpectedError) as err: serv.verify_response("meaningless") expected = "Unexpected data in response body: something awful" assert str(err.value) == expected @responses.activate def test_missing_success_key_error(self): responses.add( responses.POST, recaptcha.VERIFY_URL, json={"foo": "bar"}, ) serv = recaptcha.Service(_REQUEST) with pytest.raises(recaptcha.UnexpectedError) as err: serv.verify_response("meaningless") expected = "Missing 'success' key in response: {'foo': 'bar'}" assert str(err.value) == expected @responses.activate def test_missing_error_codes_key_error(self): responses.add( responses.POST, recaptcha.VERIFY_URL, json={"success": False}, ) serv = recaptcha.Service(_REQUEST) with pytest.raises(recaptcha.UnexpectedError) as err: serv.verify_response("meaningless") expected = "Response missing 'error-codes' key: {'success': False}" assert str(err.value) == expected @responses.activate def test_error_map_error(self): for key, exc_tp in recaptcha.ERROR_CODE_MAP.items(): responses.add( responses.POST, recaptcha.VERIFY_URL, json={ "success": False, "challenge_ts": 0, "hostname": "hotname_value", "error_codes": [key] } ) serv = recaptcha.Service(_REQUEST) with pytest.raises(exc_tp): serv.verify_response("meaningless") responses.reset() @responses.activate def test_error_map_unknown_error(self): responses.add( responses.POST, recaptcha.VERIFY_URL, json={ "success": False, "challenge_ts": 0, "hostname": "hostname_value", "error_codes": ["slartibartfast"], }, ) serv = recaptcha.Service(_REQUEST) with pytest.raises(recaptcha.UnexpectedError) as err: serv.verify_response("meaningless") assert str(err) == "Unexpected error code: slartibartfast" @responses.activate def test_challenge_response_missing_timestamp_success(self): responses.add( responses.POST, recaptcha.VERIFY_URL, json={ "success": True, "hostname": "hostname_value", }, ) serv = recaptcha.Service(_REQUEST) res = serv.verify_response("meaningless") assert isinstance(res, recaptcha.ChallengeResponse) assert res.challenge_ts is None assert res.hostname == "hostname_value" @responses.activate def test_challenge_response_missing_hostname_success(self): responses.add( responses.POST, recaptcha.VERIFY_URL, json={ "success": True, "challenge_ts": 0, }, ) serv = recaptcha.Service(_REQUEST) res = serv.verify_response("meaningless") assert isinstance(res, recaptcha.ChallengeResponse) assert res.hostname is None assert res.challenge_ts == 0 @responses.activate def test_challenge_response_success(self): responses.add( responses.POST, recaptcha.VERIFY_URL, json={ "success": True, "hostname": "hostname_value", "challenge_ts": 0, }, ) serv = recaptcha.Service(_REQUEST) res = serv.verify_response("meaningless") assert isinstance(res, recaptcha.ChallengeResponse) assert res.hostname == "hostname_value" assert res.challenge_ts == 0 @responses.activate def test_unexpected_error(self): serv = recaptcha.Service(_REQUEST) serv.request.http.post = pretend.raiser(socket.error) with pytest.raises(recaptcha.UnexpectedError): serv.verify_response("meaningless") class TestCSPPolicy: def test_csp_policy(self): scheme = 'https' request = pretend.stub( scheme=scheme, registry=pretend.stub(settings={ "recaptcha.site_key": "foo", "recaptcha.secret_key": "bar", }) ) serv = recaptcha.Service(request) assert serv.csp_policy == { "script-src": [ "{request.scheme}://www.google.com/recaptcha/", "{request.scheme}://www.gstatic.com/recaptcha/", ], "frame-src": ["{request.scheme}://www.google.com/recaptcha/"], "style-src": ["'unsafe-inline'"], } def test_service_factory(): serv = recaptcha.service_factory(None, _REQUEST) assert serv.request is _REQUEST def test_includeme(): config = pretend.stub( register_service_factory=pretend.call_recorder( lambda fact, name: None ), ) recaptcha.includeme(config) assert config.register_service_factory.calls == [ pretend.call(recaptcha.service_factory, name="recaptcha"), ]
apache-2.0
ramcn/demo3
venv/lib/python3.4/site-packages/braces/views/_other.py
11
4712
from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import resolve from django.shortcuts import redirect from django.utils.encoding import force_text class SetHeadlineMixin(object): """ Mixin allows you to set a static headline through a static property on the class or programmatically by overloading the get_headline method. """ headline = None # Default the headline to none def get_context_data(self, **kwargs): kwargs = super(SetHeadlineMixin, self).get_context_data(**kwargs) # Update the existing context dict with the provided headline. kwargs.update({"headline": self.get_headline()}) return kwargs def get_headline(self): if self.headline is None: # If no headline was provided as a view # attribute and this method wasn't # overridden raise a configuration error. raise ImproperlyConfigured( '{0} is missing a headline. ' 'Define {0}.headline, or override ' '{0}.get_headline().'.format(self.__class__.__name__)) return force_text(self.headline) class StaticContextMixin(object): """ Mixin allows you to set static context through a static property on the class. """ static_context = None def get_context_data(self, **kwargs): kwargs = super(StaticContextMixin, self).get_context_data(**kwargs) try: kwargs.update(self.get_static_context()) except (TypeError, ValueError): raise ImproperlyConfigured( '{0}.static_context must be a dictionary or container ' 'of two-tuples.'.format(self.__class__.__name__)) else: return kwargs def get_static_context(self): if self.static_context is None: raise ImproperlyConfigured( '{0} is missing the static_context property. Define ' '{0}.static_context, or override ' '{0}.get_static_context()'.format(self.__class__.__name__) ) return self.static_context class CanonicalSlugDetailMixin(object): """ A mixin that enforces a canonical slug in the url. If a urlpattern takes a object's pk and slug as arguments and the slug url argument does not equal the object's canonical slug, this mixin will redirect to the url containing the canonical slug. """ def dispatch(self, request, *args, **kwargs): # Set up since we need to super() later instead of earlier. self.request = request self.args = args self.kwargs = kwargs # Get the current object, url slug, and # urlpattern name (namespace aware). obj = self.get_object() slug = self.kwargs.get(self.slug_url_kwarg, None) match = resolve(request.path_info) url_parts = match.namespaces url_parts.append(match.url_name) current_urlpattern = ":".join(url_parts) # Figure out what the slug is supposed to be. if hasattr(obj, "get_canonical_slug"): canonical_slug = obj.get_canonical_slug() else: canonical_slug = self.get_canonical_slug() # If there's a discrepancy between the slug in the url and the # canonical slug, redirect to the canonical slug. if canonical_slug != slug: params = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: canonical_slug, 'permanent': True} return redirect(current_urlpattern, **params) return super(CanonicalSlugDetailMixin, self).dispatch( request, *args, **kwargs) def get_canonical_slug(self): """ Override this method to customize what slug should be considered canonical. Alternatively, define the get_canonical_slug method on this view's object class. In that case, this method will never be called. """ return self.get_object().slug class AllVerbsMixin(object): """Call a single method for all HTTP verbs. The name of the method should be specified using the class attribute ``all_handler``. The default value of this attribute is 'all'. """ all_handler = 'all' def dispatch(self, request, *args, **kwargs): if not self.all_handler: raise ImproperlyConfigured( '{0} requires the all_handler attribute to be set.'.format( self.__class__.__name__)) handler = getattr(self, self.all_handler, self.http_method_not_allowed) return handler(request, *args, **kwargs)
mit
nanolearning/edx-platform
common/djangoapps/student/migrations/0018_auto.py
188
10521
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding index on 'CourseEnrollment', fields ['created'] db.create_index('student_courseenrollment', ['created']) def backwards(self, orm): # Removing index on 'CourseEnrollment', fields ['created'] db.delete_index('student_courseenrollment', ['created']) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'about': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'avatar_type': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '1'}), 'bronze': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'consecutive_days_visit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'country': ('django_countries.fields.CountryField', [], {'max_length': '2', 'blank': 'True'}), 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'display_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'email_isvalid': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'email_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}), 'email_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'gold': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'gravatar': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ignored_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'interesting_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'new_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'questions_per_page': ('django.db.models.fields.SmallIntegerField', [], {'default': '10'}), 'real_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'reputation': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'seen_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'show_country': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'silver': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'w'", 'max_length': '2'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'student.courseenrollment': { 'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'CourseEnrollment'}, 'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.pendingemailchange': { 'Meta': {'object_name': 'PendingEmailChange'}, 'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_email': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'student.pendingnamechange': { 'Meta': {'object_name': 'PendingNameChange'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'rationale': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'student.registration': { 'Meta': {'object_name': 'Registration', 'db_table': "'auth_registration'"}, 'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'student.userprofile': { 'Meta': {'object_name': 'UserProfile', 'db_table': "'auth_userprofile'"}, 'country': ('django_countries.fields.CountryField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'courseware': ('django.db.models.fields.CharField', [], {'default': "'course.xml'", 'max_length': '255', 'blank': 'True'}), 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'gender': ('django.db.models.fields.CharField', [], {'max_length': '6', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'mailing_address': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'meta': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'occupation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'telephone_number': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"}) }, 'student.usertestgroup': { 'Meta': {'object_name': 'UserTestGroup'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'db_index': 'True', 'symmetrical': 'False'}) } } complete_apps = ['student']
agpl-3.0
liulion/mayavi
tvtk/tests/test_class_tree.py
2
5360
# Author: Prabhu Ramachandran # License: BSD style # Copyright (c) 2004, Enthought, Inc. """Tests class_tree.py. Uses the vtk module to test the code. Also tests if the tree generation works for the __builtin__ module. """ import unittest from tvtk import class_tree import vtk import __builtin__ # This computation can be expensive, so we cache it. _cache = class_tree.ClassTree(vtk) _cache.create() vtk_major_version = vtk.vtkVersion.GetVTKMajorVersion() def get_level(klass): """Gets the inheritance level of a given class.""" if not klass.__bases__: return 0 else: return max([get_level(b) for b in klass.__bases__]) + 1 class TestClassTree(unittest.TestCase): def setUp(self): self.t = _cache def test_basic_vtk(self): """Basic tests for the VTK module.""" t = self.t self.assertEqual(t.get_node('vtkObject').name, 'vtkObject') self.assertEqual(t.get_node('vtkObject').parents[0].name, 'vtkObjectBase') if (hasattr(vtk, 'vtkTuple')): names = [x.name for x in t.tree[0]] names.sort() if vtk_major_version < 6: self.assertEqual(len(t.tree[0]), 12) expect = ['object', 'vtkColor3', 'vtkColor4', 'vtkDenseArray', 'vtkObjectBase', 'vtkRect', 'vtkSparseArray', 'vtkTuple', 'vtkTypedArray', 'vtkVector', 'vtkVector2', 'vtkVector3'] else: self.assertEqual(len(t.tree[0]), 13) expect = ['object', 'vtkColor3', 'vtkColor4', 'vtkDenseArray', 'vtkObjectBase', 'vtkQuaternion', 'vtkRect', 'vtkSparseArray', 'vtkTuple', 'vtkTypedArray', 'vtkVector', 'vtkVector2', 'vtkVector3'] self.assertEqual(names, expect) elif (hasattr(vtk, 'vtkVector')): self.assertEqual(len(t.tree[0]), 11) names = [x.name for x in t.tree[0]] names.sort() expect = ['object', 'vtkColor3', 'vtkColor4', 'vtkDenseArray', 'vtkObjectBase', 'vtkRect', 'vtkSparseArray', 'vtkTypedArray', 'vtkVector', 'vtkVector2', 'vtkVector3'] self.assertEqual(names, expect) elif (hasattr(vtk, 'vtkArrayCoordinates') and issubclass(vtk.vtkArrayCoordinates, object)): self.assertEqual(len(t.tree[0]), 2) names = [x.name for x in t.tree[0]] names.sort() self.assertEqual(names, ['object', 'vtkObjectBase']) else: self.assertEqual(len(t.tree[0]), 1) self.assertEqual(t.tree[0][0].name, 'vtkObjectBase') def test_ancestors(self): """Check if get_ancestors is OK.""" # The parent child information is already tested so this test # needs to ensure that the method works for a few known # examples. # Simple VTK test. t = self.t n = t.get_node('vtkDataArray') x = vtk.vtkDataArray ancestors = [] while x.__name__ != 'vtkObjectBase': x = x.__bases__[0] ancestors.append(x.__name__) self.assertEqual([x.name for x in n.get_ancestors()], ancestors) # Simple __builtin__ test. t = class_tree.ClassTree(__builtin__) t.create() n = t.get_node('TabError') bases = ['IndentationError', 'SyntaxError', 'StandardError', 'Exception'] if len(Exception.__bases__) > 0: bases.extend(['BaseException', 'object']) self.assertEqual([x.name for x in n.get_ancestors()], bases) def test_parent_child(self): """Check if the node's parent and children are correct.""" t = self.t for node in t: n_class = t.get_class(node.name) base_names = [x.__name__ for x in n_class.__bases__] base_names.sort() parent_names = [x.name for x in node.parents] parent_names.sort() self.assertEqual(base_names, parent_names) for c in node.children: c_class = t.get_class(c.name) base_names = [x.__name__ for x in c_class.__bases__] self.assertEqual(node.name in base_names, True) def test_level(self): """Check the node levels.""" t = self.t for node in t: self.assertEqual(get_level(t.get_class(node.name)), node.level) def test_tree(self): """Check the tree structure.""" t = self.t n = sum([len(x) for x in t.tree]) self.assertEqual(n, len(t.nodes)) for level, nodes in enumerate(t.tree): for n in nodes: self.assertEqual(n.level, level) def test_builtin(self): """Check if tree structure for __builtin__ works.""" # This tests to see if the tree structure generation works for # the __builtin__ module. t = class_tree.ClassTree(__builtin__) t.create() self.t = t self.test_parent_child() self.test_level() self.test_tree() if __name__ == "__main__": unittest.main()
bsd-3-clause
rjonaitis/opengreenhouse
server.py
2
6191
#!/usr/bin/env python3 import os import http.server import bottle import json import urllib.parse import numpy import pandas from serial import Serial from serial.serialutil import SerialException import time from threading import Thread from queue import Queue, Empty import sys SERIAL_DEVICE = "/dev/arduino" SERIAL_RATE = 115200 HTTP_HOST = '127.0.0.1' HTTP_PORT = 8000 WINDOW_OPEN_POSITION = 5000 WINDOW_CLOSED_POSITION = 0 DOOR_OPEN_POSITION = -9500 DOOR_CLOSED_POSITION = 0 WIND_THRESHOLD = 200 WIND_MEAN_TIME = 10 ROOT = os.path.dirname(os.path.realpath(__file__)) WEBROOT = os.path.join(ROOT, "webroot") class Arduino: def __init__(self, mock): self.mock = mock self.pipe = None self.thread = Thread(target=self.interact) self.sendq = Queue() self.recvq = Queue() self.state = {} self.wind_fir = [] self.window_close = False self.window_prev = 0 self.door_prev = 0 def log_filename(self, key): return os.path.join(ROOT, 'log', key) def log_value(self, key, value): with open(self.log_filename(key), "a") as f: f.write("{} {}\n".format(time.time(), value)) def handle(self): wind = self.state.get('wind', 0) if not self.window_close and wind > WIND_THRESHOLD: self.window_close = True self.window_prev = self.state.get('window', 0) self.door_prev = self.state.get('door', 0) self.put('window', 0) self.put('door', 0) elif self.window_close and wind < WIND_THRESHOLD / 4: self.window_close = False self.put('window', self.window_prev) self.put('door', self.door_prev) def interact(self): serial = None while True: try: if serial is None and not self.mock: try: serial = Serial(SERIAL_DEVICE, SERIAL_RATE) print("Connecting to Arduino") except SerialException: print("Error opening serial. To use without arduino: ./server.py --mock") os._exit(1) try: while True: cmd = self.sendq.get(block=False) if self.mock: print("SERIAL WRITE:", cmd) else: serial.write(cmd.encode('ascii')) serial.write(b'\n') except Empty: pass if self.mock: time.sleep(1) line = b'temp 18\n' else: line = serial.readline() try: key, value = line.decode('ascii').strip().split(' ') value = self.from_arduino(key, int(value)) self.log_value(key, value) self.state[key] = value self.handle() self.recvq.put((key, value)) except ValueError: print("Malformed input from arduino:", line) continue except UnicodeDecodeError: print("Malformed input from arduino:", line) continue except SerialException: if serial is not None: serial.close() serial = None print("Disconnecting from Arduino") def start(self): self.thread.start() def from_arduino(self, key, value): if key == 'window': return int(100 * (value - WINDOW_CLOSED_POSITION) / (WINDOW_OPEN_POSITION - WINDOW_CLOSED_POSITION)) if key == 'door': return int(100 * (value - DOOR_CLOSED_POSITION) / (DOOR_OPEN_POSITION - DOOR_CLOSED_POSITION)) if key == 'wind': if value < 0: value = 0 self.wind_fir.append(int(value)) self.wind_fir = self.wind_fir[-WIND_MEAN_TIME:] return int(numpy.mean(self.wind_fir)) return int(value) def to_arduino(self, key, value): if key == 'window': return int((WINDOW_OPEN_POSITION - WINDOW_CLOSED_POSITION) * value / 100) + WINDOW_CLOSED_POSITION if key == 'door': return int((DOOR_OPEN_POSITION - DOOR_CLOSED_POSITION) * value / 100) + DOOR_CLOSED_POSITION return int(value) def get(self, key): return self.state.get(key, None) def put(self, key, value): self.sendq.put("{} {}".format(key, self.to_arduino(key, value))) return value def timeseries(self, name, start, end=None, resolution=None): if end is None: end = time.time() start = float(start) end = float(end) log = pandas.read_csv(self.log_filename(name), sep=' ', names=('time', 'value')) log = log.dropna() log.time = log.time.astype(float) log.value = log.value.astype(int) log = log[(start <= log.time) & (log.time <= end)] value = log.value value.index = pandas.to_datetime(log.time, unit='s') if len(value) and resolution is not None and resolution != 1: value = value.resample('{}s'.format(resolution)).dropna() return { 'time': [int(t.timestamp()) for t in value.index], 'value': [int(x) for x in value], } ARDUINO = Arduino(mock='--mock' in sys.argv) def ok(value): return {"ok": True, "value": value} @bottle.get('/rpc/series/<key>/') def series(key): q = bottle.request.query return ok(ARDUINO.timeseries(key, q.start, q.end, q.resolution)) @bottle.get('/rpc/<key>/') def get(key): return ok(ARDUINO.get(key)) @bottle.put('/rpc/<key>/') def put(key): q = bottle.request.query value = int(q.value) return ok(ARDUINO.put(key, value)) def main(): print("Starting up...") os.chdir(WEBROOT) ARDUINO.start() sys.argv = [sys.argv[0]] bottle.run(host=HTTP_HOST, port=HTTP_PORT, server='cherrypy') if __name__ == "__main__": main()
gpl-3.0
goddino/libjingle
trunk/tools/gyp/pylib/gyp/MSVSProject.py
2736
6387
# 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. """Visual Studio project reader/writer.""" import gyp.common import gyp.easy_xml as easy_xml #------------------------------------------------------------------------------ class Tool(object): """Visual Studio tool.""" def __init__(self, name, attrs=None): """Initializes the tool. Args: name: Tool name. attrs: Dict of tool attributes; may be None. """ self._attrs = attrs or {} self._attrs['Name'] = name def _GetSpecification(self): """Creates an element for the tool. Returns: A new xml.dom.Element for the tool. """ return ['Tool', self._attrs] class Filter(object): """Visual Studio filter - that is, a virtual folder.""" def __init__(self, name, contents=None): """Initializes the folder. Args: name: Filter (folder) name. contents: List of filenames and/or Filter objects contained. """ self.name = name self.contents = list(contents or []) #------------------------------------------------------------------------------ class Writer(object): """Visual Studio XML project writer.""" def __init__(self, project_path, version, name, guid=None, platforms=None): """Initializes the project. Args: project_path: Path to the project file. version: Format version to emit. name: Name of the project. guid: GUID to use for project, if not None. platforms: Array of string, the supported platforms. If null, ['Win32'] """ self.project_path = project_path self.version = version self.name = name self.guid = guid # Default to Win32 for platforms. if not platforms: platforms = ['Win32'] # Initialize the specifications of the various sections. self.platform_section = ['Platforms'] for platform in platforms: self.platform_section.append(['Platform', {'Name': platform}]) self.tool_files_section = ['ToolFiles'] self.configurations_section = ['Configurations'] self.files_section = ['Files'] # Keep a dict keyed on filename to speed up access. self.files_dict = dict() def AddToolFile(self, path): """Adds a tool file to the project. Args: path: Relative path from project to tool file. """ self.tool_files_section.append(['ToolFile', {'RelativePath': path}]) def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools): """Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Returns: """ # Handle defaults if not attrs: attrs = {} if not tools: tools = [] # Add configuration node and its attributes node_attrs = attrs.copy() node_attrs['Name'] = config_name specification = [config_type, node_attrs] # Add tool nodes and their attributes if tools: for t in tools: if isinstance(t, Tool): specification.append(t._GetSpecification()) else: specification.append(Tool(t)._GetSpecification()) return specification def AddConfig(self, name, attrs=None, tools=None): """Adds a configuration to the project. Args: name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. """ spec = self._GetSpecForConfiguration('Configuration', name, attrs, tools) self.configurations_section.append(spec) def _AddFilesToNode(self, parent, files): """Adds files and/or filters to the parent node. Args: parent: Destination node files: A list of Filter objects and/or relative paths to files. Will call itself recursively, if the files list contains Filter objects. """ for f in files: if isinstance(f, Filter): node = ['Filter', {'Name': f.name}] self._AddFilesToNode(node, f.contents) else: node = ['File', {'RelativePath': f}] self.files_dict[f] = node parent.append(node) def AddFiles(self, files): """Adds files to the project. Args: files: A list of Filter objects and/or relative paths to files. This makes a copy of the file/filter tree at the time of this call. If you later add files to a Filter object which was passed into a previous call to AddFiles(), it will not be reflected in this project. """ self._AddFilesToNode(self.files_section, files) # TODO(rspangler) This also doesn't handle adding files to an existing # filter. That is, it doesn't merge the trees. def AddFileConfig(self, path, config, attrs=None, tools=None): """Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles(). """ # Find the file node with the right relative path parent = self.files_dict.get(path) if not parent: raise ValueError('AddFileConfig: file "%s" not in project.' % path) # Add the config to the file node spec = self._GetSpecForConfiguration('FileConfiguration', config, attrs, tools) parent.append(spec) def WriteIfChanged(self): """Writes the project file.""" # First create XML content definition content = [ 'VisualStudioProject', {'ProjectType': 'Visual C++', 'Version': self.version.ProjectVersion(), 'Name': self.name, 'ProjectGUID': self.guid, 'RootNamespace': self.name, 'Keyword': 'Win32Proj' }, self.platform_section, self.tool_files_section, self.configurations_section, ['References'], # empty section self.files_section, ['Globals'] # empty section ] easy_xml.WriteXmlIfChanged(content, self.project_path, encoding="Windows-1252")
bsd-3-clause
trilliumtransit/oba_rvtd_deployer
oba_rvtd_deployer/aws.py
1
14048
try: input = raw_input except NameError: pass import os import sys import time import boto.ec2 from fabric.api import env, run, sudo, cd, put from fabric.context_managers import settings from fabric.contrib.files import exists from fabric.exceptions import NetworkError from oba_rvtd_deployer import REPORTS_DIR, CONFIG_TEMPLATE_DIR from oba_rvtd_deployer.config import get_aws_config, get_oba_config from oba_rvtd_deployer.fab_crontab import crontab_update from oba_rvtd_deployer.util import FabLogger, write_template, unix_path_join def get_aws_connection(): '''Connect to AWS. Returns: boto.ec2.connection.EC2Connection: Connection to region. ''' print('Connecting to AWS') aws_conf = get_aws_config() return boto.ec2.connect_to_region(aws_conf.get('DEFAULT', 'region'), aws_access_key_id=aws_conf.get('DEFAULT', 'aws_access_key_id'), aws_secret_access_key=aws_conf.get('DEFAULT', 'aws_secret_access_key')) def launch_new(): '''Launch a new EC2 instance installing an OBA instance ''' # connect to AWS and launch new instance aws_conf = get_aws_config() conn = get_aws_connection() print('Preparing volume') dev_xvda = boto.ec2.blockdevicemapping.EBSBlockDeviceType() dev_xvda.size = aws_conf.get('DEFAULT', 'volume_size') dev_xvda.delete_on_termination = True block_device_map = boto.ec2.blockdevicemapping.BlockDeviceMapping() block_device_map['/dev/xvda'] = dev_xvda print('Launching new instance') reservation = conn.run_instances(aws_conf.get('DEFAULT', 'ami_id'), instance_type=aws_conf.get('DEFAULT', 'instance_type'), key_name=aws_conf.get('DEFAULT', 'key_name'), security_groups=aws_conf.get('DEFAULT', 'security_groups').split(','), block_device_map=block_device_map) # Get the instance instance = reservation.instances[0] # Check if it's up and running a specified maximum number of times max_retries = 10 num_retries = 0 # Check up on its status every so often status = instance.update() while status == 'pending': if num_retries > max_retries: tear_down(instance.id, conn) raise Exception('Maximum Number of Instance Retries Hit. Did EC2 instance spawn correctly?') num_retries += 1 print('Instance pending, waiting 10 seconds...') time.sleep(10) status = instance.update() if status == 'running': instance.add_tag("Name", aws_conf.get('DEFAULT', 'instance_name')) instance.add_tag("Client", aws_conf.get('DEFAULT', 'client_name')) else: print('Instance status: ' + status) return None # Now that the status is running, it's not yet launched. # The only way to tell if it's fully up is to try to SSH in. aws_system = AwsFab(instance.public_dns_name) # If we've reached this point, the instance is up and running. print('SSH working') aws_system.set_timezone() aws_system.turn_off_ipv6() aws_system.install_pg() aws_system.update_system() aws_system.install_all() return instance class AwsFab: aws_conf = get_aws_config() oba_conf = get_oba_config() user = aws_conf.get('DEFAULT', 'user') config_dir = unix_path_join('/home', user, 'conf') def __init__(self, host_name): '''Constructor for Class. Sets up fabric environment. Args: host_name (string): ec2 public dns name ''' env.host_string = '{0}@{1}'.format(self.user, host_name) env.key_filename = [self.aws_conf.get('DEFAULT', 'key_filename')] sys.stdout = FabLogger(os.path.join(REPORTS_DIR, 'aws_fab.log')) max_retries = 6 num_retries = 0 retry = True while retry: try: # SSH into the box here. self.test_cmd() retry = False except NetworkError as e: print(e) if num_retries > max_retries: raise Exception('Maximum Number of SSH Retries Hit. Did EC2 instance get configured with ssh correctly?') num_retries += 1 print('SSH failed (the system may still be starting up), waiting 10 seconds...') time.sleep(10) def test_cmd(self): '''A test command to see if everything is running ok. ''' run('uname') def update_system(self): '''Updates the instance with the latest patches and upgrades. ''' sudo('yum -y update') def turn_off_ipv6(self): '''Edits the networking settings to turn off ipv6. Credit to CDSU user on http://blog.acsystem.sk/linux/rhel-6-centos-6-disabling-ipv6-in-system ''' # unfortunately, this requires sudo access with settings(warn_only=True): sudo('echo "net.ipv6.conf.default.disable_ipv6=1" >> /etc/sysctl.conf') sudo('echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf') sudo('sysctl -p') def install_all(self, exclude_pg=True): '''Method to install all stuff on machine (except OneBusAway). Args: exclude_pg (bool, default=True): skips installation of pg. Typically this is done right after instance startup. ''' # self.install_helpers() if not exclude_pg: self.install_pg() self.set_timezone() self.install_custom_monitoring() self.install_git() self.install_jdk() self.install_maven() self.install_tomcat() self.install_xwiki() def set_timezone(self): '''Changes the machine's localtime to the desired timezone. ''' with cd('/etc'): sudo('rm -rf localtime') sudo('ln -s {0} localtime'.format(self.aws_conf.get('DEFAULT', 'timezone'))) def install_custom_monitoring(self): '''Installs a custom monitoring script to monitor memory and disk utilization. ''' # install helpers sudo('yum -y install perl-DateTime perl-Sys-Syslog perl-LWP-Protocol-https') # dl scripts run('wget http://aws-cloudwatch.s3.amazonaws.com/downloads/CloudWatchMonitoringScripts-1.2.1.zip') sudo('unzip CloudWatchMonitoringScripts-1.2.1.zip -d /usr/local') run('rm CloudWatchMonitoringScripts-1.2.1.zip') # prepare the monitoring crontab with open(os.path.join(CONFIG_TEMPLATE_DIR, 'monitoring_crontab')) as f: cron = f.read() cron_settings = dict(aws_access_key_id=self.aws_conf.get('DEFAULT', 'aws_access_key_id'), aws_secret_key=self.aws_conf.get('DEFAULT', 'aws_secret_access_key'), cron_email=self.aws_conf.get('DEFAULT', 'cron_email')) aws_logging_cron = cron.format(**cron_settings) # start crontab for aws monitoring crontab_update(aws_logging_cron, 'aws_monitoring') def install_helpers(self): '''Installs various utilities (typically not included with CentOS). ''' sudo('yum -y install wget') sudo('yum -y install unzip') def install_git(self): '''Installs git. ''' sudo('yum -y install git') def install_jdk(self): '''Installs jdk devel, so maven is happy. ''' sudo('yum -y install java-1.7.0-openjdk java-1.7.0-openjdk-devel') def install_maven(self): '''Downloads and installs maven. ''' # download and extract maven run('wget http://mirror.symnds.com/software/Apache/maven/maven-3/3.3.3/binaries/apache-maven-3.3.3-bin.tar.gz') sudo('tar xzf apache-maven-3.3.3-bin.tar.gz -C /usr/local') run('rm apache-maven-3.3.3-bin.tar.gz') with cd('/usr/local'): sudo('ln -s apache-maven-3.3.3 maven') # check that mvn command works run('/usr/local/maven/bin/mvn -version') def upload_pg_hba_conf(self, local_method): '''Overwrites pg_hba.conf with specified local method. ''' remote_data_folder = '/var/lib/pgsql9/data' remote_pg_hba_conf = '/var/lib/pgsql9/data/pg_hba.conf' sudo('rm -rf {0}'.format(remote_pg_hba_conf)) if not exists(self.config_dir): run('mkdir {0}'.format(self.config_dir)) put(write_template(dict(local_method=local_method), 'pg_hba.conf'), self.config_dir) sudo('mv {0} {1}'.format(unix_path_join(self.config_dir, 'pg_hba.conf'), remote_data_folder)) sudo('chmod 600 {0}'.format(remote_pg_hba_conf)) sudo('chgrp postgres {0}'.format(remote_pg_hba_conf)) sudo('chown postgres {0}'.format(remote_pg_hba_conf)) def install_pg(self): '''Configures PostgreSQL for immediate use by OneBusAway. ''' # install it sudo('yum -y install postgresql postgresql-server') # initialize db sudo('service postgresql initdb') # edit pg_hba for db initialization self.upload_pg_hba_conf('trust') # start postgersql server sudo('service postgresql start') # run init sql db_setup_dict = dict(pg_username=self.oba_conf.get('DEFAULT', 'pg_username'), pg_password=self.oba_conf.get('DEFAULT', 'pg_password'), pg_role=self.oba_conf.get('DEFAULT', 'pg_role')) if not exists(self.config_dir): run('mkdir {0}'.format(self.config_dir)) put(write_template(db_setup_dict, 'init.sql'), self.config_dir) init_sql_filename = unix_path_join(self.config_dir, 'init.sql') sudo('psql -U postgres -f {0}'.format(init_sql_filename)) sudo('rm -rf {0}'.format(init_sql_filename)) # switch to more secure pg_hba.conf self.upload_pg_hba_conf('md5') # start postgersql server sudo('service postgresql restart') # start postgresql on boot sudo('chkconfig postgresql on') def install_tomcat(self): '''Configures Tomcat on EC2 instance. Unlinke other items, this is placed in /home/{user} directory, so that it can be restarted with cron to refresh gtfs updates. ''' # get tomcat from direct download run('wget http://mirror.cc.columbia.edu/pub/software/apache/tomcat/tomcat-7/v7.0.65/bin/apache-tomcat-7.0.65.tar.gz') # move to a local area for better organization run('tar xzf apache-tomcat-7.0.65.tar.gz') run('rm -rf apache-tomcat-7.0.65.tar.gz') run('mv apache-tomcat-7.0.65 tomcat') # add logging rotation for catalina.out put(write_template(dict(user=self.user), 'tomcat_catalina_out'), '/etc/logrotate.d', True) # add init.d script put(write_template(dict(user=self.user), 'tomcat_init.d'), '/etc/init.d', True) with cd('/etc/init.d'): sudo('mv tomcat_init.d tomcat') sudo('chmod 755 tomcat') sudo('chown root tomcat') sudo('chgrp root tomcat') sudo('chkconfig --add tomcat') def install_xwiki(self): run('wget http://download.forge.ow2.org/xwiki/xwiki-enterprise-jetty-hsqldb-7.3.zip') # move to a local area for better organization sudo('unzip xwiki-enterprise-jetty-hsqldb-7.3.zip -d /usr/local') run('rm xwiki-enterprise-jetty-hsqldb-7.3.zip') with cd('/usr/local'): sudo('ln -s xwiki-enterprise-jetty-hsqldb-7.3 xwiki') # add init.d script put(os.path.join(CONFIG_TEMPLATE_DIR, 'xwiki_init.d'), '/etc/init.d', True) with cd('/etc/init.d'): sudo('mv xwiki_init.d xwiki') sudo('chmod 755 xwiki') sudo('chown root xwiki') sudo('chgrp root xwiki') sudo('chkconfig --add xwiki') def tear_down(instance_id=None, conn=None): '''Terminates a EC2 instance and deletes all associated volumes. Args: instance_id (string): The ec2 instance id to terminate. conn (boto.ec2.connection.EC2Connection): Connection to region. ''' if not instance_id: instance_id = input('Enter instance id: ') if not conn: conn = get_aws_connection() volumes = conn.get_all_volumes(filters={'attachment.instance-id': [instance_id]}) print('Terminating instance') conn.terminate_instances([instance_id]) aws_conf = get_aws_config() if aws_conf.get('DEFAULT', 'delete_volumes_on_tear_down') == 'true': max_wait_retries = 12 print('Deleting volume(s) associated with instance') for volume in volumes: volume_deleted = False num_retries = 0 while not volume_deleted: try: conn.delete_volume(volume.id) volume_deleted = True except Exception as e: if num_retries >= max_wait_retries: raise e print('Waiting for volume to become detached from instance. Waiting 10 seconds...') time.sleep(10)
apache-2.0
toastedcornflakes/scikit-learn
sklearn/manifold/tests/test_locally_linear.py
27
5247
from itertools import product from nose.tools import assert_true import numpy as np from numpy.testing import assert_almost_equal, assert_array_almost_equal from scipy import linalg from sklearn import neighbors, manifold from sklearn.manifold.locally_linear import barycenter_kneighbors_graph from sklearn.utils.testing import assert_less from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_raise_message eigen_solvers = ['dense', 'arpack'] #---------------------------------------------------------------------- # Test utility routines def test_barycenter_kneighbors_graph(): X = np.array([[0, 1], [1.01, 1.], [2, 0]]) A = barycenter_kneighbors_graph(X, 1) assert_array_almost_equal( A.toarray(), [[0., 1., 0.], [1., 0., 0.], [0., 1., 0.]]) A = barycenter_kneighbors_graph(X, 2) # check that columns sum to one assert_array_almost_equal(np.sum(A.toarray(), 1), np.ones(3)) pred = np.dot(A.toarray(), X) assert_less(linalg.norm(pred - X) / X.shape[0], 1) #---------------------------------------------------------------------- # Test LLE by computing the reconstruction error on some manifolds. def test_lle_simple_grid(): # note: ARPACK is numerically unstable, so this test will fail for # some random seeds. We choose 2 because the tests pass. rng = np.random.RandomState(2) # grid of equidistant points in 2D, n_components = n_dim X = np.array(list(product(range(5), repeat=2))) X = X + 1e-10 * rng.uniform(size=X.shape) n_components = 2 clf = manifold.LocallyLinearEmbedding(n_neighbors=5, n_components=n_components, random_state=rng) tol = 0.1 N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() reconstruction_error = linalg.norm(np.dot(N, X) - X, 'fro') assert_less(reconstruction_error, tol) for solver in eigen_solvers: clf.set_params(eigen_solver=solver) clf.fit(X) assert_true(clf.embedding_.shape[1] == n_components) reconstruction_error = linalg.norm( np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 assert_less(reconstruction_error, tol) assert_almost_equal(clf.reconstruction_error_, reconstruction_error, decimal=1) # re-embed a noisy version of X using the transform method noise = rng.randn(*X.shape) / 100 X_reembedded = clf.transform(X + noise) assert_less(linalg.norm(X_reembedded - clf.embedding_), tol) def test_lle_manifold(): rng = np.random.RandomState(0) # similar test on a slightly more complex manifold X = np.array(list(product(np.arange(18), repeat=2))) X = np.c_[X, X[:, 0] ** 2 / 18] X = X + 1e-10 * rng.uniform(size=X.shape) n_components = 2 for method in ["standard", "hessian", "modified", "ltsa"]: clf = manifold.LocallyLinearEmbedding(n_neighbors=6, n_components=n_components, method=method, random_state=0) tol = 1.5 if method == "standard" else 3 N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() reconstruction_error = linalg.norm(np.dot(N, X) - X) assert_less(reconstruction_error, tol) for solver in eigen_solvers: clf.set_params(eigen_solver=solver) clf.fit(X) assert_true(clf.embedding_.shape[1] == n_components) reconstruction_error = linalg.norm( np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 details = ("solver: %s, method: %s" % (solver, method)) assert_less(reconstruction_error, tol, msg=details) assert_less(np.abs(clf.reconstruction_error_ - reconstruction_error), tol * reconstruction_error, msg=details) # Test the error raised when parameter passed to lle is invalid def test_lle_init_parameters(): X = np.random.rand(5, 3) clf = manifold.LocallyLinearEmbedding(eigen_solver="error") msg = "unrecognized eigen_solver 'error'" assert_raise_message(ValueError, msg, clf.fit, X) clf = manifold.LocallyLinearEmbedding(method="error") msg = "unrecognized method 'error'" assert_raise_message(ValueError, msg, clf.fit, X) def test_pipeline(): # check that LocallyLinearEmbedding works fine as a Pipeline # only checks that no error is raised. # TODO check that it actually does something useful from sklearn import pipeline, datasets X, y = datasets.make_blobs(random_state=0) clf = pipeline.Pipeline( [('filter', manifold.LocallyLinearEmbedding(random_state=0)), ('clf', neighbors.KNeighborsClassifier())]) clf.fit(X, y) assert_less(.9, clf.score(X, y)) # Test the error raised when the weight matrix is singular def test_singular_matrix(): from nose.tools import assert_raises M = np.ones((10, 3)) f = ignore_warnings assert_raises(ValueError, f(manifold.locally_linear_embedding), M, 2, 1, method='standard', eigen_solver='arpack')
bsd-3-clause
SpaceMonkeyInc/twisted-utils
deferred.py
1
3697
#!/usr/bin/env python # # See LICENSE file for copying information # """ Space Monkey Twisted helpers http://www.spacemonkey.com/ This library provides some miscellaneous Twisted helper primitives """ __copyright__ = "Copyright 2012 Space Monkey, Inc." import os from twisted.internet import defer from twisted.python.util import mergeFunctionMetadata def _inlineCallbacksSuccess(result, current_state, generator, deferred): if current_state[0]: current_state[0] = False current_state[1] = result else: _inlineCallbacks(result, None, generator, deferred) def _inlineCallbacksFailure(myfailure, current_state, generator, deferred): if current_state[0]: current_state[0] = False current_state[2] = myfailure else: _inlineCallbacks(None, myfailure, generator, deferred) def _inlineCallbacks(result, myfailure, generator, deferred): current_state = [True, result, myfailure] while True: try: if current_state[2] is None: next_deferred = generator.send(current_state[1]) else: next_deferred = current_state[2].throwExceptionIntoGenerator( generator) current_state[2] = None except StopIteration: deferred.callback(None) return deferred except defer._DefGen_Return, e: # pylint: disable=W0212 deferred.callback(e.value) return deferred except: deferred.errback() return deferred args = (current_state, generator, deferred) try: next_deferred.addCallbacks( _inlineCallbacksSuccess, _inlineCallbacksFailure, callbackArgs=args, errbackArgs=args) except AttributeError: if hasattr(next_deferred, "addCallbacks"): raise # next_deferred was something without an addCallbacks. # just pass the value back in current_state[1] = next_deferred continue if current_state[0]: # the callbacks didn't run immediately current_state[0] = False return deferred # the callbacks ran immediately. reset waiting and loop current_state[0] = True def fastInline(f): """This decorator is mostly equivalent to defer.inlineCallbacks except that speed is the primary priority. while inlineCallbacks checks a few different things to make sure you're doing it properly, this method simply assumes you are. changes: * this decorator no longer checks that you're wrapping a generator * this decorator no longer checks that _DefGen_Return is thrown from the decoratored generator only * the generator loop no longer double checks that you're yielding deferreds and simply assumes it, catching the exception if you aren't * the generator stops calling isinstance for logic - profiling reveals that isinstance consumes a nontrivial amount of computing power during heavy use You can force this method to behave exactly like defer.inlineCallbacks by providing the FORCE_STANDARD_INLINE_CALLBACKS environment variable """ def unwind(*args, **kwargs): try: gen = f(*args, **kwargs) except defer._DefGen_Return: # pylint: disable=W0212 raise TypeError("defer.returnValue used from non-generator") return _inlineCallbacks(None, None, gen, defer.Deferred()) return mergeFunctionMetadata(f, unwind) if "FORCE_STANDARD_INLINE_CALLBACKS" in os.environ: fastInline = defer.inlineCallbacks
mit
xiandiancloud/edx-platform
common/djangoapps/config_models/__init__.py
220
2002
""" Model-Based Configuration ========================= This app allows other apps to easily define a configuration model that can be hooked into the admin site to allow configuration management with auditing. Installation ------------ Add ``config_models`` to your ``INSTALLED_APPS`` list. Usage ----- Create a subclass of ``ConfigurationModel``, with fields for each value that needs to be configured:: class MyConfiguration(ConfigurationModel): frobble_timeout = IntField(default=10) frazzle_target = TextField(defalut="debug") This is a normal django model, so it must be synced and migrated as usual. The default values for the fields in the ``ConfigurationModel`` will be used if no configuration has yet been created. Register that class with the Admin site, using the ``ConfigurationAdminModel``:: from django.contrib import admin from config_models.admin import ConfigurationModelAdmin admin.site.register(MyConfiguration, ConfigurationModelAdmin) Use the configuration in your code:: def my_view(self, request): config = MyConfiguration.current() fire_the_missiles(config.frazzle_target, timeout=config.frobble_timeout) Use the admin site to add new configuration entries. The most recently created entry is considered to be ``current``. Configuration ------------- The current ``ConfigurationModel`` will be cached in the ``configuration`` django cache, or in the ``default`` cache if ``configuration`` doesn't exist. You can specify the cache timeout in each ``ConfigurationModel`` by setting the ``cache_timeout`` property. You can change the name of the cache key used by the ``ConfigurationModel`` by overriding the ``cache_key_name`` function. Extension --------- ``ConfigurationModels`` are just django models, so they can be extended with new fields and migrated as usual. Newly added fields must have default values and should be nullable, so that rollbacks to old versions of configuration work correctly. """
agpl-3.0
hwstar/chargectrlr-python-buspirate
chargerctrl/SerialSelect.py
1
3015
__author__ = 'srodgers' """ This file is part of chargectrl-python-buspirate. chargectrl-python-buspirate 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. chargectrl-python-buspirate 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 chargectrl-python-buspirate. If not, see <http://www.gnu.org/licenses/>. """ import glob import serial from .Dialog import * class SerialSelect(Dialog): def __init__(self, parent, title="Select Serial Port", udevportname='', xoffset=50, yoffset=50): self.sindex=0 self.rbuttons = [] self.udevportname = udevportname self.ports= self._serial_ports(udevportname) Dialog.__init__(self, parent, title=title, xoffset=xoffset, yoffset=yoffset) def body(self, master): self.rbvar = IntVar() selected = 0 for index, port in enumerate(self.ports): self.rbuttons.append(Radiobutton(master, text=port, variable=self.rbvar, value=index, command=self._action, width=15).grid(row = index, column = 0)) if(port == '/dev/'+self.udevportname): selected = index self.rbvar.set(selected) def port(self): if(self.sindex != None): return self.ports[self.sindex] return None def _action(self): self.sindex = self.rbvar.get() def _serial_ports(self, udevportname=''): """Lists serial ports :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of available serial ports """ isLinux = False if sys.platform.startswith('win'): ports = ['COM' + str(i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): isLinux = True # this is to exclude your current terminal "/dev/tty" ports = glob.glob('/dev/ttyUSB*') if(len(udevportname)): ports += glob.glob('/dev/'+udevportname+'*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: if(isLinux == False): # Doing this in Linux disturbs the serial port s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result
gpl-3.0
BeegorMif/HTPC-Manager
sickbeard/notifiers/plex.py
1
4579
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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. # # SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>. import urllib import urllib2 import base64 import sickbeard from sickbeard import logger from sickbeard import common from sickbeard.exceptions import ex from sickbeard.encodingKludge import fixStupidEncodings from sickbeard.notifiers.xbmc import XBMCNotifier # TODO: switch over to using ElementTree from xml.dom import minidom class PLEXNotifier(XBMCNotifier): def _notify_pmc(self, message, title="SickRage", host=None, username=None, password=None, force=False): # fill in omitted parameters if not host: if sickbeard.PLEX_HOST: host = sickbeard.PLEX_HOST # Use the default Plex host else: logger.log(u"No Plex host specified, check your settings", logger.DEBUG) return False if not username: username = sickbeard.PLEX_USERNAME if not password: password = sickbeard.PLEX_PASSWORD # suppress notifications if the notifier is disabled but the notify options are checked if not sickbeard.USE_PLEX and not force: logger.log("Notification for Plex not enabled, skipping this notification", logger.DEBUG) return False return self._notify_xbmc(message=message, title=title, host=host, username=username, password=password, force=True) def notify_snatch(self, ep_name): if sickbeard.PLEX_NOTIFY_ONSNATCH: self._notify_pmc(ep_name, common.notifyStrings[common.NOTIFY_SNATCH]) def notify_download(self, ep_name): if sickbeard.PLEX_NOTIFY_ONDOWNLOAD: self._notify_pmc(ep_name, common.notifyStrings[common.NOTIFY_DOWNLOAD]) def notify_subtitle_download(self, ep_name, lang): if sickbeard.PLEX_NOTIFY_ONSUBTITLEDOWNLOAD: self._notify_pmc(ep_name + ": " + lang, common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD]) def test_notify(self, host, username, password): return self._notify_pmc("Testing Plex notifications from SickRage", "Test Notification", host, username, password, force=True) def update_library(self): """Handles updating the Plex Media Server host via HTTP API Plex Media Server currently only supports updating the whole video library and not a specific path. Returns: Returns True or False """ if sickbeard.USE_PLEX and sickbeard.PLEX_UPDATE_LIBRARY: if not sickbeard.PLEX_SERVER_HOST: logger.log(u"No Plex Media Server host specified, check your settings", logger.DEBUG) return False logger.log(u"Updating library for the Plex Media Server host: " + sickbeard.PLEX_SERVER_HOST, logger.MESSAGE) url = "http://%s/library/sections" % sickbeard.PLEX_SERVER_HOST try: xml_sections = minidom.parse(urllib.urlopen(url)) except IOError, e: logger.log(u"Error while trying to contact Plex Media Server: " + ex(e), logger.ERROR) return False sections = xml_sections.getElementsByTagName('Directory') if not sections: logger.log(u"Plex Media Server not running on: " + sickbeard.PLEX_SERVER_HOST, logger.MESSAGE) return False for s in sections: if s.getAttribute('type') == "show": url = "http://%s/library/sections/%s/refresh" % (sickbeard.PLEX_SERVER_HOST, s.getAttribute('key')) try: urllib.urlopen(url) except Exception, e: logger.log(u"Error updating library section for Plex Media Server: " + ex(e), logger.ERROR) return False return True notifier = PLEXNotifier
gpl-3.0
kerimlcr/ab2017-dpyo
ornek/imageio/imageio-2.1.2/debian/python-imageio/usr/lib/python2.7/dist-packages/imageio/plugins/fits.py
8
4926
# -*- coding: utf-8 -*- # Copyright (c) 2015, imageio contributors # imageio is distributed under the terms of the (new) BSD License. """ Plugin for reading FITS files. """ from __future__ import absolute_import, print_function, division from .. import formats from ..core import Format _fits = None # lazily loaded def load_lib(): global _fits try: from astropy.io import fits as _fits except ImportError: raise ImportError("The FITS format relies on the astropy package." "Please refer to http://www.astropy.org/ " "for further instructions.") return _fits class FitsFormat(Format): """ Flexible Image Transport System (FITS) is an open standard defining a digital file format useful for storage, transmission and processing of scientific and other images. FITS is the most commonly used digital file format in astronomy. This format requires the ``astropy`` package. Parameters for reading ---------------------- cache : bool If the file name is a URL, `~astropy.utils.data.download_file` is used to open the file. This specifies whether or not to save the file locally in Astropy's download cache (default: `True`). uint : bool Interpret signed integer data where ``BZERO`` is the central value and ``BSCALE == 1`` as unsigned integer data. For example, ``int16`` data with ``BZERO = 32768`` and ``BSCALE = 1`` would be treated as ``uint16`` data. Note, for backward compatibility, the kwarg **uint16** may be used instead. The kwarg was renamed when support was added for integers of any size. ignore_missing_end : bool Do not issue an exception when opening a file that is missing an ``END`` card in the last header. checksum : bool or str If `True`, verifies that both ``DATASUM`` and ``CHECKSUM`` card values (when present in the HDU header) match the header and data of all HDU's in the file. Updates to a file that already has a checksum will preserve and update the existing checksums unless this argument is given a value of 'remove', in which case the CHECKSUM and DATASUM values are not checked, and are removed when saving changes to the file. disable_image_compression : bool, optional If `True`, treats compressed image HDU's like normal binary table HDU's. do_not_scale_image_data : bool If `True`, image data is not scaled using BSCALE/BZERO values when read. ignore_blank : bool If `True`, the BLANK keyword is ignored if present. scale_back : bool If `True`, when saving changes to a file that contained scaled image data, restore the data to the original type and reapply the original BSCALE/BZERO values. This could lead to loss of accuracy if scaling back to integer values after performing floating point operations on the data. """ def _can_read(self, request): # We return True if ext matches, because this is the only plugin # that can. If astropy is not installed, a useful error follows. return request.filename.lower().endswith(self.extensions) def _can_write(self, request): # No write support return False # -- reader class Reader(Format.Reader): def _open(self, cache=False, **kwargs): if not _fits: load_lib() hdulist = _fits.open(self.request.get_file(), cache=cache, **kwargs) self._index = [] for n, hdu in zip(range(len(hdulist)), hdulist): if (isinstance(hdu, _fits.ImageHDU) or isinstance(hdu, _fits.PrimaryHDU)): # Ignore (primary) header units with no data (use '.size' # rather than '.data' to avoid actually loading the image): if hdu.size > 0: self._index.append(n) self._hdulist = hdulist def _close(self): self._hdulist.close() def _get_length(self): return len(self._index) def _get_data(self, index): # Get data if index < 0 or index >= len(self._index): raise IndexError('Index out of range while reading from fits') im = self._hdulist[self._index[index]].data # Return array and empty meta data return im, {} def _get_meta_data(self, index): # Get the meta data for the given index raise RuntimeError('The fits format does not support meta data.') # Register format = FitsFormat('fits', "Flexible Image Transport System (FITS) format", 'fits fit fts', 'iIvV') formats.add_format(format)
gpl-3.0
fafaman/django
tests/inspectdb/tests.py
100
13023
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import re from unittest import skipUnless from django.core.management import call_command from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.utils.six import PY3, StringIO from .models import ColumnTypes class InspectDBTestCase(TestCase): def test_stealth_table_name_filter_option(self): out = StringIO() # Lets limit the introspection to tables created for models of this # application call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_'), stdout=out) error_message = "inspectdb has examined a table that should have been filtered out." # contrib.contenttypes is one of the apps always installed when running # the Django test suite, check that one of its tables hasn't been # inspected self.assertNotIn("class DjangoContentType(models.Model):", out.getvalue(), msg=error_message) def make_field_type_asserter(self): """Call inspectdb and return a function to validate a field type in its output""" out = StringIO() call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_columntypes'), stdout=out) output = out.getvalue() def assertFieldType(name, definition): out_def = re.search(r'^\s*%s = (models.*)$' % name, output, re.MULTILINE).groups()[0] self.assertEqual(definition, out_def) return assertFieldType def test_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() # Inspecting Oracle DB doesn't produce correct results (#19884): # - it gets max_length wrong: it returns a number of bytes. # - it reports fields as blank=True when they aren't. if (connection.features.can_introspect_max_length and not connection.features.interprets_empty_strings_as_nulls): assertFieldType('char_field', "models.CharField(max_length=10)") assertFieldType('null_char_field', "models.CharField(max_length=10, blank=True, null=True)") assertFieldType('comma_separated_int_field', "models.CharField(max_length=99)") assertFieldType('date_field', "models.DateField()") assertFieldType('date_time_field', "models.DateTimeField()") if (connection.features.can_introspect_max_length and not connection.features.interprets_empty_strings_as_nulls): assertFieldType('email_field', "models.CharField(max_length=254)") assertFieldType('file_field', "models.CharField(max_length=100)") assertFieldType('file_path_field', "models.CharField(max_length=100)") if connection.features.can_introspect_ip_address_field: assertFieldType('gen_ip_adress_field', "models.GenericIPAddressField()") elif (connection.features.can_introspect_max_length and not connection.features.interprets_empty_strings_as_nulls): assertFieldType('gen_ip_adress_field', "models.CharField(max_length=39)") if (connection.features.can_introspect_max_length and not connection.features.interprets_empty_strings_as_nulls): assertFieldType('slug_field', "models.CharField(max_length=50)") if not connection.features.interprets_empty_strings_as_nulls: assertFieldType('text_field', "models.TextField()") if connection.features.can_introspect_time_field: assertFieldType('time_field', "models.TimeField()") if (connection.features.can_introspect_max_length and not connection.features.interprets_empty_strings_as_nulls): assertFieldType('url_field', "models.CharField(max_length=200)") def test_number_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() if not connection.features.can_introspect_autofield: assertFieldType('id', "models.IntegerField(primary_key=True) # AutoField?") if connection.features.can_introspect_big_integer_field: assertFieldType('big_int_field', "models.BigIntegerField()") else: assertFieldType('big_int_field', "models.IntegerField()") bool_field = ColumnTypes._meta.get_field('bool_field') bool_field_type = connection.features.introspected_boolean_field_type(bool_field) assertFieldType('bool_field', "models.{}()".format(bool_field_type)) null_bool_field = ColumnTypes._meta.get_field('null_bool_field') null_bool_field_type = connection.features.introspected_boolean_field_type(null_bool_field) if 'BooleanField' in null_bool_field_type: assertFieldType('null_bool_field', "models.{}()".format(null_bool_field_type)) else: if connection.features.can_introspect_null: assertFieldType('null_bool_field', "models.{}(blank=True, null=True)".format(null_bool_field_type)) else: assertFieldType('null_bool_field', "models.{}()".format(null_bool_field_type)) if connection.features.can_introspect_decimal_field: assertFieldType('decimal_field', "models.DecimalField(max_digits=6, decimal_places=1)") else: # Guessed arguments on SQLite, see #5014 assertFieldType('decimal_field', "models.DecimalField(max_digits=10, decimal_places=5) " "# max_digits and decimal_places have been guessed, " "as this database handles decimal fields as float") assertFieldType('float_field', "models.FloatField()") assertFieldType('int_field', "models.IntegerField()") if connection.features.can_introspect_positive_integer_field: assertFieldType('pos_int_field', "models.PositiveIntegerField()") else: assertFieldType('pos_int_field', "models.IntegerField()") if connection.features.can_introspect_positive_integer_field: if connection.features.can_introspect_small_integer_field: assertFieldType('pos_small_int_field', "models.PositiveSmallIntegerField()") else: assertFieldType('pos_small_int_field', "models.PositiveIntegerField()") else: if connection.features.can_introspect_small_integer_field: assertFieldType('pos_small_int_field', "models.SmallIntegerField()") else: assertFieldType('pos_small_int_field', "models.IntegerField()") if connection.features.can_introspect_small_integer_field: assertFieldType('small_int_field', "models.SmallIntegerField()") else: assertFieldType('small_int_field', "models.IntegerField()") @skipUnlessDBFeature('can_introspect_foreign_keys') def test_attribute_name_not_python_keyword(self): out = StringIO() # Lets limit the introspection to tables created for models of this # application call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_'), stdout=out) output = out.getvalue() error_message = "inspectdb generated an attribute name which is a python keyword" # Recursive foreign keys should be set to 'self' self.assertIn("parent = models.ForeignKey('self', models.DO_NOTHING)", output) self.assertNotIn( "from = models.ForeignKey(InspectdbPeople, models.DO_NOTHING)", output, msg=error_message, ) # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted self.assertIn( "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, db_column='from_id')", output, ) self.assertIn( "people_pk = models.ForeignKey(InspectdbPeople, models.DO_NOTHING, primary_key=True)", output, ) self.assertIn( "people_unique = models.ForeignKey(InspectdbPeople, models.DO_NOTHING, unique=True)", output, ) def test_digits_column_name_introspection(self): """Introspection of column names consist/start with digits (#16536/#17676)""" out = StringIO() # Lets limit the introspection to tables created for models of this # application call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_'), stdout=out) output = out.getvalue() error_message = "inspectdb generated a model field name which is a number" self.assertNotIn(" 123 = models.CharField", output, msg=error_message) self.assertIn("number_123 = models.CharField", output) error_message = "inspectdb generated a model field name which starts with a digit" self.assertNotIn(" 4extra = models.CharField", output, msg=error_message) self.assertIn("number_4extra = models.CharField", output) self.assertNotIn(" 45extra = models.CharField", output, msg=error_message) self.assertIn("number_45extra = models.CharField", output) def test_special_column_name_introspection(self): """ Introspection of column names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_'), stdout=out) output = out.getvalue() base_name = 'Field' if not connection.features.uppercases_column_names else 'field' self.assertIn("field = models.IntegerField()", output) self.assertIn("field_field = models.IntegerField(db_column='%s_')" % base_name, output) self.assertIn("field_field_0 = models.IntegerField(db_column='%s__')" % base_name, output) self.assertIn("field_field_1 = models.IntegerField(db_column='__field')", output) self.assertIn("prc_x = models.IntegerField(db_column='prc(%) x')", output) if PY3: # Python 3 allows non-ASCII identifiers self.assertIn("tamaño = models.IntegerField()", output) else: self.assertIn("tama_o = models.IntegerField(db_column='tama\\xf1o')", output) def test_table_name_introspection(self): """ Introspection of table names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_'), stdout=out) output = out.getvalue() self.assertIn("class InspectdbSpecialTableName(models.Model):", output) def test_managed_models(self): """Test that by default the command generates models with `Meta.managed = False` (#14305)""" out = StringIO() call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_columntypes'), stdout=out) output = out.getvalue() self.longMessage = False self.assertIn(" managed = False", output, msg='inspectdb should generate unmanaged models.') def test_unique_together_meta(self): out = StringIO() call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_uniquetogether'), stdout=out) output = out.getvalue() self.assertIn( " unique_together = (('field1', 'field2'),)", output, msg='inspectdb should generate unique_together.' ) @skipUnless(connection.vendor == 'sqlite', "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test") def test_custom_fields(self): """ Introspection of columns with a custom field (#21090) """ out = StringIO() orig_data_types_reverse = connection.introspection.data_types_reverse try: connection.introspection.data_types_reverse = { 'text': 'myfields.TextField', 'bigint': 'BigIntegerField', } call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_columntypes'), stdout=out) output = out.getvalue() self.assertIn("text_field = myfields.TextField()", output) self.assertIn("big_int_field = models.BigIntegerField()", output) finally: connection.introspection.data_types_reverse = orig_data_types_reverse
bsd-3-clause
pexip/os-pytest
testing/test_conftest.py
2
14608
from textwrap import dedent import _pytest._code import py import pytest from _pytest.config import PytestPluginManager from _pytest.main import EXIT_NOTESTSCOLLECTED, EXIT_USAGEERROR @pytest.fixture(scope="module", params=["global", "inpackage"]) def basedir(request, tmpdir_factory): from _pytest.tmpdir import tmpdir tmpdir = tmpdir(request, tmpdir_factory) tmpdir.ensure("adir/conftest.py").write("a=1 ; Directory = 3") tmpdir.ensure("adir/b/conftest.py").write("b=2 ; a = 1.5") if request.param == "inpackage": tmpdir.ensure("adir/__init__.py") tmpdir.ensure("adir/b/__init__.py") return tmpdir def ConftestWithSetinitial(path): conftest = PytestPluginManager() conftest_setinitial(conftest, [path]) return conftest def conftest_setinitial(conftest, args, confcutdir=None): class Namespace: def __init__(self): self.file_or_dir = args self.confcutdir = str(confcutdir) self.noconftest = False conftest._set_initial_conftests(Namespace()) class TestConftestValueAccessGlobal: def test_basic_init(self, basedir): conftest = PytestPluginManager() p = basedir.join("adir") assert conftest._rget_with_confmod("a", p)[1] == 1 def test_immediate_initialiation_and_incremental_are_the_same(self, basedir): conftest = PytestPluginManager() len(conftest._path2confmods) conftest._getconftestmodules(basedir) snap1 = len(conftest._path2confmods) #assert len(conftest._path2confmods) == snap1 + 1 conftest._getconftestmodules(basedir.join('adir')) assert len(conftest._path2confmods) == snap1 + 1 conftest._getconftestmodules(basedir.join('b')) assert len(conftest._path2confmods) == snap1 + 2 def test_value_access_not_existing(self, basedir): conftest = ConftestWithSetinitial(basedir) with pytest.raises(KeyError): conftest._rget_with_confmod('a', basedir) def test_value_access_by_path(self, basedir): conftest = ConftestWithSetinitial(basedir) adir = basedir.join("adir") assert conftest._rget_with_confmod("a", adir)[1] == 1 assert conftest._rget_with_confmod("a", adir.join("b"))[1] == 1.5 def test_value_access_with_confmod(self, basedir): startdir = basedir.join("adir", "b") startdir.ensure("xx", dir=True) conftest = ConftestWithSetinitial(startdir) mod, value = conftest._rget_with_confmod("a", startdir) assert value == 1.5 path = py.path.local(mod.__file__) assert path.dirpath() == basedir.join("adir", "b") assert path.purebasename.startswith("conftest") def test_conftest_in_nonpkg_with_init(tmpdir): tmpdir.ensure("adir-1.0/conftest.py").write("a=1 ; Directory = 3") tmpdir.ensure("adir-1.0/b/conftest.py").write("b=2 ; a = 1.5") tmpdir.ensure("adir-1.0/b/__init__.py") tmpdir.ensure("adir-1.0/__init__.py") ConftestWithSetinitial(tmpdir.join("adir-1.0", "b")) def test_doubledash_considered(testdir): conf = testdir.mkdir("--option") conf.join("conftest.py").ensure() conftest = PytestPluginManager() conftest_setinitial(conftest, [conf.basename, conf.basename]) l = conftest._getconftestmodules(conf) assert len(l) == 1 def test_issue151_load_all_conftests(testdir): names = "code proj src".split() for name in names: p = testdir.mkdir(name) p.ensure("conftest.py") conftest = PytestPluginManager() conftest_setinitial(conftest, names) d = list(conftest._conftestpath2mod.values()) assert len(d) == len(names) def test_conftest_global_import(testdir): testdir.makeconftest("x=3") p = testdir.makepyfile(""" import py, pytest from _pytest.config import PytestPluginManager conf = PytestPluginManager() mod = conf._importconftest(py.path.local("conftest.py")) assert mod.x == 3 import conftest assert conftest is mod, (conftest, mod) subconf = py.path.local().ensure("sub", "conftest.py") subconf.write("y=4") mod2 = conf._importconftest(subconf) assert mod != mod2 assert mod2.y == 4 import conftest assert conftest is mod2, (conftest, mod) """) res = testdir.runpython(p) assert res.ret == 0 def test_conftestcutdir(testdir): conf = testdir.makeconftest("") p = testdir.mkdir("x") conftest = PytestPluginManager() conftest_setinitial(conftest, [testdir.tmpdir], confcutdir=p) l = conftest._getconftestmodules(p) assert len(l) == 0 l = conftest._getconftestmodules(conf.dirpath()) assert len(l) == 0 assert conf not in conftest._conftestpath2mod # but we can still import a conftest directly conftest._importconftest(conf) l = conftest._getconftestmodules(conf.dirpath()) assert l[0].__file__.startswith(str(conf)) # and all sub paths get updated properly l = conftest._getconftestmodules(p) assert len(l) == 1 assert l[0].__file__.startswith(str(conf)) def test_conftestcutdir_inplace_considered(testdir): conf = testdir.makeconftest("") conftest = PytestPluginManager() conftest_setinitial(conftest, [conf.dirpath()], confcutdir=conf.dirpath()) l = conftest._getconftestmodules(conf.dirpath()) assert len(l) == 1 assert l[0].__file__.startswith(str(conf)) @pytest.mark.parametrize("name", 'test tests whatever .dotdir'.split()) def test_setinitial_conftest_subdirs(testdir, name): sub = testdir.mkdir(name) subconftest = sub.ensure("conftest.py") conftest = PytestPluginManager() conftest_setinitial(conftest, [sub.dirpath()], confcutdir=testdir.tmpdir) if name not in ('whatever', '.dotdir'): assert subconftest in conftest._conftestpath2mod assert len(conftest._conftestpath2mod) == 1 else: assert subconftest not in conftest._conftestpath2mod assert len(conftest._conftestpath2mod) == 0 def test_conftest_confcutdir(testdir): testdir.makeconftest("assert 0") x = testdir.mkdir("x") x.join("conftest.py").write(_pytest._code.Source(""" def pytest_addoption(parser): parser.addoption("--xyz", action="store_true") """)) result = testdir.runpytest("-h", "--confcutdir=%s" % x, x) result.stdout.fnmatch_lines(["*--xyz*"]) assert 'warning: could not load initial' not in result.stdout.str() def test_no_conftest(testdir): testdir.makeconftest("assert 0") result = testdir.runpytest("--noconftest") assert result.ret == EXIT_NOTESTSCOLLECTED result = testdir.runpytest() assert result.ret == EXIT_USAGEERROR def test_conftest_existing_resultlog(testdir): x = testdir.mkdir("tests") x.join("conftest.py").write(_pytest._code.Source(""" def pytest_addoption(parser): parser.addoption("--xyz", action="store_true") """)) testdir.makefile(ext=".log", result="") # Writes result.log result = testdir.runpytest("-h", "--resultlog", "result.log") result.stdout.fnmatch_lines(["*--xyz*"]) def test_conftest_existing_junitxml(testdir): x = testdir.mkdir("tests") x.join("conftest.py").write(_pytest._code.Source(""" def pytest_addoption(parser): parser.addoption("--xyz", action="store_true") """)) testdir.makefile(ext=".xml", junit="") # Writes junit.xml result = testdir.runpytest("-h", "--junitxml", "junit.xml") result.stdout.fnmatch_lines(["*--xyz*"]) def test_conftest_import_order(testdir, monkeypatch): ct1 = testdir.makeconftest("") sub = testdir.mkdir("sub") ct2 = sub.join("conftest.py") ct2.write("") def impct(p): return p conftest = PytestPluginManager() conftest._confcutdir = testdir.tmpdir monkeypatch.setattr(conftest, '_importconftest', impct) assert conftest._getconftestmodules(sub) == [ct1, ct2] def test_fixture_dependency(testdir, monkeypatch): ct1 = testdir.makeconftest("") ct1 = testdir.makepyfile("__init__.py") ct1.write("") sub = testdir.mkdir("sub") sub.join("__init__.py").write("") sub.join("conftest.py").write(py.std.textwrap.dedent(""" import pytest @pytest.fixture def not_needed(): assert False, "Should not be called!" @pytest.fixture def foo(): assert False, "Should not be called!" @pytest.fixture def bar(foo): return 'bar' """)) subsub = sub.mkdir("subsub") subsub.join("__init__.py").write("") subsub.join("test_bar.py").write(py.std.textwrap.dedent(""" import pytest @pytest.fixture def bar(): return 'sub bar' def test_event_fixture(bar): assert bar == 'sub bar' """)) result = testdir.runpytest("sub") result.stdout.fnmatch_lines(["*1 passed*"]) def test_conftest_found_with_double_dash(testdir): sub = testdir.mkdir("sub") sub.join("conftest.py").write(py.std.textwrap.dedent(""" def pytest_addoption(parser): parser.addoption("--hello-world", action="store_true") """)) p = sub.join("test_hello.py") p.write(py.std.textwrap.dedent(""" import pytest def test_hello(found): assert found == 1 """)) result = testdir.runpytest(str(p) + "::test_hello", "-h") result.stdout.fnmatch_lines(""" *--hello-world* """) class TestConftestVisibility: def _setup_tree(self, testdir): # for issue616 # example mostly taken from: # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html runner = testdir.mkdir("empty") package = testdir.mkdir("package") package.join("conftest.py").write(dedent("""\ import pytest @pytest.fixture def fxtr(): return "from-package" """)) package.join("test_pkgroot.py").write(dedent("""\ def test_pkgroot(fxtr): assert fxtr == "from-package" """)) swc = package.mkdir("swc") swc.join("__init__.py").ensure() swc.join("conftest.py").write(dedent("""\ import pytest @pytest.fixture def fxtr(): return "from-swc" """)) swc.join("test_with_conftest.py").write(dedent("""\ def test_with_conftest(fxtr): assert fxtr == "from-swc" """)) snc = package.mkdir("snc") snc.join("__init__.py").ensure() snc.join("test_no_conftest.py").write(dedent("""\ def test_no_conftest(fxtr): assert fxtr == "from-package" # No local conftest.py, so should # use value from parent dir's """)) print ("created directory structure:") for x in testdir.tmpdir.visit(): print (" " + x.relto(testdir.tmpdir)) return { "runner": runner, "package": package, "swc": swc, "snc": snc} # N.B.: "swc" stands for "subdir with conftest.py" # "snc" stands for "subdir no [i.e. without] conftest.py" @pytest.mark.parametrize("chdir,testarg,expect_ntests_passed", [ # Effective target: package/.. ("runner", "..", 3), ("package", "..", 3), ("swc", "../..", 3), ("snc", "../..", 3), # Effective target: package ("runner", "../package", 3), ("package", ".", 3), ("swc", "..", 3), ("snc", "..", 3), # Effective target: package/swc ("runner", "../package/swc", 1), ("package", "./swc", 1), ("swc", ".", 1), ("snc", "../swc", 1), # Effective target: package/snc ("runner", "../package/snc", 1), ("package", "./snc", 1), ("swc", "../snc", 1), ("snc", ".", 1), ]) @pytest.mark.issue616 def test_parsefactories_relative_node_ids( self, testdir, chdir,testarg, expect_ntests_passed): dirs = self._setup_tree(testdir) print("pytest run in cwd: %s" %( dirs[chdir].relto(testdir.tmpdir))) print("pytestarg : %s" %(testarg)) print("expected pass : %s" %(expect_ntests_passed)) with dirs[chdir].as_cwd(): reprec = testdir.inline_run(testarg, "-q", "--traceconfig") reprec.assertoutcome(passed=expect_ntests_passed) @pytest.mark.parametrize('confcutdir,passed,error', [ ('.', 2, 0), ('src', 1, 1), (None, 1, 1), ]) def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error): """Test that conftest files are detected only up to a ini file, unless an explicit --confcutdir option is given. """ root = testdir.tmpdir src = root.join('src').ensure(dir=1) src.join('pytest.ini').write('[pytest]') src.join('conftest.py').write(_pytest._code.Source(""" import pytest @pytest.fixture def fix1(): pass """)) src.join('test_foo.py').write(_pytest._code.Source(""" def test_1(fix1): pass def test_2(out_of_reach): pass """)) root.join('conftest.py').write(_pytest._code.Source(""" import pytest @pytest.fixture def out_of_reach(): pass """)) args = [str(src)] if confcutdir: args = ['--confcutdir=%s' % root.join(confcutdir)] result = testdir.runpytest(*args) match = '' if passed: match += '*%d passed*' % passed if error: match += '*%d error*' % error result.stdout.fnmatch_lines(match) def test_issue1073_conftest_special_objects(testdir): testdir.makeconftest(""" class DontTouchMe: def __getattr__(self, x): raise Exception('cant touch me') x = DontTouchMe() """) testdir.makepyfile(""" def test_some(): pass """) res = testdir.runpytest() assert res.ret == 0 def test_conftest_exception_handling(testdir): testdir.makeconftest(''' raise ValueError() ''') testdir.makepyfile(""" def test_some(): pass """) res = testdir.runpytest() assert res.ret == 4 assert 'raise ValueError()' in [line.strip() for line in res.errlines]
mit
vicnet/weboob
modules/gls/browser.py
2
1326
# -*- coding: utf-8 -*- # Copyright(C) 2015 Matthieu Weber # # This file is part of a weboob module. # # This weboob module 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 weboob module 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 weboob module. If not, see <http://www.gnu.org/licenses/>. from weboob.browser import PagesBrowser, URL from weboob.browser.exceptions import HTTPNotFound from weboob.capabilities.parcel import ParcelNotFound from .pages import SearchPage class GLSBrowser(PagesBrowser): BASEURL = 'https://gls-group.eu' search_page = URL('/app/service/open/rest/EU/en/rstt001\?match=(?P<id>.+)', SearchPage) def get_tracking_info(self, _id): try: return self.search_page.go(id=_id).get_info(_id) except HTTPNotFound: raise ParcelNotFound("No such ID: %s" % _id)
lgpl-3.0
cfossace/test
malstor/malstor_lib/helpers.py
1
3131
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # This file is in the public domain ### END LICENSE ### DO NOT EDIT THIS FILE ### """Helpers for an Ubuntu application.""" import logging import os from . malstorconfig import get_data_file from . Builder import Builder from locale import gettext as _ def get_builder(builder_file_name): """Return a fully-instantiated Gtk.Builder instance from specified ui file :param builder_file_name: The name of the builder file, without extension. Assumed to be in the 'ui' directory under the data path. """ # Look for the ui file that describes the user interface. ui_filename = get_data_file('ui', '%s.ui' % (builder_file_name,)) if not os.path.exists(ui_filename): ui_filename = None builder = Builder() builder.set_translation_domain('malstor') builder.add_from_file(ui_filename) return builder # Owais Lone : To get quick access to icons and stuff. def get_media_file(media_file_name): media_filename = get_data_file('media', '%s' % (media_file_name,)) if not os.path.exists(media_filename): media_filename = None return "file:///"+media_filename class NullHandler(logging.Handler): def emit(self, record): pass def set_up_logging(opts): # add a handler to prevent basicConfig root = logging.getLogger() null_handler = NullHandler() root.addHandler(null_handler) formatter = logging.Formatter("%(levelname)s:%(name)s: %(funcName)s() '%(message)s'") logger = logging.getLogger('malstor') logger_sh = logging.StreamHandler() logger_sh.setFormatter(formatter) logger.addHandler(logger_sh) lib_logger = logging.getLogger('malstor_lib') lib_logger_sh = logging.StreamHandler() lib_logger_sh.setFormatter(formatter) lib_logger.addHandler(lib_logger_sh) # Set the logging level to show debug messages. if opts.verbose: logger.setLevel(logging.DEBUG) logger.debug('logging enabled') if opts.verbose > 1: lib_logger.setLevel(logging.DEBUG) def get_help_uri(page=None): # help_uri from source tree - default language here = os.path.dirname(__file__) help_uri = os.path.abspath(os.path.join(here, '..', 'help', 'C')) if not os.path.exists(help_uri): # installed so use gnome help tree - user's language help_uri = 'malstor' # unspecified page is the index.page if page is not None: help_uri = '%s#%s' % (help_uri, page) return help_uri def show_uri(parent, link): from gi.repository import Gtk # pylint: disable=E0611 screen = parent.get_screen() Gtk.show_uri(screen, link, Gtk.get_current_event_time()) def alias(alternative_function_name): '''see http://www.drdobbs.com/web-development/184406073#l9''' def decorator(function): '''attach alternative_function_name(s) to function''' if not hasattr(function, 'aliases'): function.aliases = [] function.aliases.append(alternative_function_name) return function return decorator
mit
akubera/AliPhysics
PWGLF/SPECTRA/PiKaPr/TestAOD/createNames.py
41
1437
#!/usr/bin/python def main(): print "I need to be debugged, please fix me" return # print header output = list() output.append ("namespace AliSpectraNameSpace\n") output.append ("{\n") output.append (" const char * kHistName[] =\n") output.append (" {\n") # print histogram names ifile = open("Histograms.h", "rb") for line in ifile: lineNoWS = line.strip() if(not lineNoWS.startswith("k")): # skip everything which is not an entry in the enum continue if("=" in lineNoWS): # skip histogram type delimeters continue col=line.split(",") output.append(" \"h"+col[0].strip()[1:]+"\",\n"); output.append (" };\n") output.append ("}\n") # write file outfile = open("HistogramNames.h", "w") outfile.write("#ifndef HISTOGRAMNAMES_H\n"); outfile.write("#define HISTOGRAMNAMES_H\n\n"); outfile.write("//This file was generated automatically, please do not edit!!\n\n"); outfile.writelines(output) outfile.write("\n#endif\n"); outfile.close() ## def skipLines(lineNoWS): ## beginningsToSkip = ["//", "{", "namespace", "enum"] ## for entry in beginningsToSkip: ## if lineNoWS.startswith(entry): ## return 1 ## return 0 ####################################################################### if __name__ == "__main__": main()
bsd-3-clause
mapennell/ansible
cloud/webfaction/webfaction_site.py
6
6890
#! /usr/bin/python # # Create Webfaction website using Ansible and the Webfaction API # # ------------------------------------------ # # (c) Quentin Stafford-Fraser 2015 # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = ''' --- module: webfaction_site short_description: Add or remove a website on a Webfaction host description: - Add or remove a website on a Webfaction host. Further documentation at http://github.com/quentinsf/ansible-webfaction. author: Quentin Stafford-Fraser (@quentinsf) version_added: "2.0" notes: - Sadly, you I(do) need to know your webfaction hostname for the C(host) parameter. But at least, unlike the API, you don't need to know the IP address - you can use a DNS name. - If a site of the same name exists in the account but on a different host, the operation will exit. - "You can run playbooks that use this on a local machine, or on a Webfaction host, or elsewhere, since the scripts use the remote webfaction API - the location is not important. However, running them on multiple hosts I(simultaneously) is best avoided. If you don't specify I(localhost) as your host, you may want to add C(serial: 1) to the plays." - See `the webfaction API <http://docs.webfaction.com/xmlrpc-api/>`_ for more info. options: name: description: - The name of the website required: true state: description: - Whether the website should exist required: false choices: ['present', 'absent'] default: "present" host: description: - The webfaction host on which the site should be created. required: true https: description: - Whether or not to use HTTPS required: false choices: BOOLEANS default: 'false' site_apps: description: - A mapping of URLs to apps required: false subdomains: description: - A list of subdomains associated with this site. required: false default: null login_name: description: - The webfaction account to use required: true login_password: description: - The webfaction password to use required: true ''' EXAMPLES = ''' - name: create website webfaction_site: name: testsite1 state: present host: myhost.webfaction.com subdomains: - 'testsite1.my_domain.org' site_apps: - ['testapp1', '/'] https: no login_name: "{{webfaction_user}}" login_password: "{{webfaction_passwd}}" ''' import socket import xmlrpclib webfaction = xmlrpclib.ServerProxy('https://api.webfaction.com/') def main(): module = AnsibleModule( argument_spec = dict( name = dict(required=True), state = dict(required=False, choices=['present', 'absent'], default='present'), # You can specify an IP address or hostname. host = dict(required=True), https = dict(required=False, choices=BOOLEANS, default=False), subdomains = dict(required=False, default=[]), site_apps = dict(required=False, default=[]), login_name = dict(required=True), login_password = dict(required=True), ), supports_check_mode=True ) site_name = module.params['name'] site_state = module.params['state'] site_host = module.params['host'] site_ip = socket.gethostbyname(site_host) session_id, account = webfaction.login( module.params['login_name'], module.params['login_password'] ) site_list = webfaction.list_websites(session_id) site_map = dict([(i['name'], i) for i in site_list]) existing_site = site_map.get(site_name) result = {} # Here's where the real stuff happens if site_state == 'present': # Does a site with this name already exist? if existing_site: # If yes, but it's on a different IP address, then fail. # If we wanted to allow relocation, we could add a 'relocate=true' option # which would get the existing IP address, delete the site there, and create it # at the new address. A bit dangerous, perhaps, so for now we'll require manual # deletion if it's on another host. if existing_site['ip'] != site_ip: module.fail_json(msg="Website already exists with a different IP address. Please fix by hand.") # If it's on this host and the key parameters are the same, nothing needs to be done. if (existing_site['https'] == module.boolean(module.params['https'])) and \ (set(existing_site['subdomains']) == set(module.params['subdomains'])) and \ (dict(existing_site['website_apps']) == dict(module.params['site_apps'])): module.exit_json( changed = False ) positional_args = [ session_id, site_name, site_ip, module.boolean(module.params['https']), module.params['subdomains'], ] for a in module.params['site_apps']: positional_args.append( (a[0], a[1]) ) if not module.check_mode: # If this isn't a dry run, create or modify the site result.update( webfaction.create_website( *positional_args ) if not existing_site else webfaction.update_website ( *positional_args ) ) elif site_state == 'absent': # If the site's already not there, nothing changed. if not existing_site: module.exit_json( changed = False, ) if not module.check_mode: # If this isn't a dry run, delete the site result.update( webfaction.delete_website(session_id, site_name, site_ip) ) else: module.fail_json(msg="Unknown state specified: {}".format(site_state)) module.exit_json( changed = True, result = result ) from ansible.module_utils.basic import * main()
gpl-3.0
jicruz/heroku-bot
lib/youtube_dl/extractor/dfb.py
87
2255
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import unified_strdate class DFBIE(InfoExtractor): IE_NAME = 'tv.dfb.de' _VALID_URL = r'https?://tv\.dfb\.de/video/(?P<display_id>[^/]+)/(?P<id>\d+)' _TEST = { 'url': 'http://tv.dfb.de/video/u-19-em-stimmen-zum-spiel-gegen-russland/11633/', 'md5': 'ac0f98a52a330f700b4b3034ad240649', 'info_dict': { 'id': '11633', 'display_id': 'u-19-em-stimmen-zum-spiel-gegen-russland', 'ext': 'mp4', 'title': 'U 19-EM: Stimmen zum Spiel gegen Russland', 'upload_date': '20150714', }, } def _real_extract(self, url): display_id, video_id = re.match(self._VALID_URL, url).groups() player_info = self._download_xml( 'http://tv.dfb.de/server/hd_video.php?play=%s' % video_id, display_id) video_info = player_info.find('video') stream_access_url = self._proto_relative_url(video_info.find('url').text.strip()) formats = [] # see http://tv.dfb.de/player/js/ajax.js for the method to extract m3u8 formats for sa_url in (stream_access_url, stream_access_url + '&area=&format=iphone'): stream_access_info = self._download_xml(sa_url, display_id) token_el = stream_access_info.find('token') manifest_url = token_el.attrib['url'] + '?' + 'hdnea=' + token_el.attrib['auth'] if '.f4m' in manifest_url: formats.extend(self._extract_f4m_formats( manifest_url + '&hdcore=3.2.0', display_id, f4m_id='hds', fatal=False)) else: formats.extend(self._extract_m3u8_formats( manifest_url, display_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False)) self._sort_formats(formats) return { 'id': video_id, 'display_id': display_id, 'title': video_info.find('title').text, 'thumbnail': 'http://tv.dfb.de/images/%s_640x360.jpg' % video_id, 'upload_date': unified_strdate(video_info.find('time_date').text), 'formats': formats, }
gpl-3.0
ettm2012/MissionPlanner
Lib/unittest/suite.py
60
10112
"""TestSuite""" import sys from . import case from . import util __unittest = True def _call_if_exists(parent, attr): func = getattr(parent, attr, lambda: None) func() class BaseTestSuite(object): """A simple test suite that doesn't provide class or module shared fixtures. """ def __init__(self, tests=()): self._tests = [] self.addTests(tests) def __repr__(self): return "<%s tests=%s>" % (util.strclass(self.__class__), list(self)) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return list(self) == list(other) def __ne__(self, other): return not self == other # Can't guarantee hash invariant, so flag as unhashable __hash__ = None def __iter__(self): return iter(self._tests) def countTestCases(self): cases = 0 for test in self: cases += test.countTestCases() return cases def addTest(self, test): # sanity checks if not hasattr(test, '__call__'): raise TypeError("{} is not callable".format(repr(test))) if isinstance(test, type) and issubclass(test, (case.TestCase, TestSuite)): raise TypeError("TestCases and TestSuites must be instantiated " "before passing them to addTest()") self._tests.append(test) def addTests(self, tests): if isinstance(tests, basestring): raise TypeError("tests must be an iterable of tests, not a string") for test in tests: self.addTest(test) def run(self, result): for test in self: if result.shouldStop: break test(result) return result def __call__(self, *args, **kwds): return self.run(*args, **kwds) def debug(self): """Run the tests without collecting errors in a TestResult""" for test in self: test.debug() class TestSuite(BaseTestSuite): """A test suite is a composite test consisting of a number of TestCases. For use, create an instance of TestSuite, then add test case instances. When all tests have been added, the suite can be passed to a test runner, such as TextTestRunner. It will run the individual test cases in the order in which they were added, aggregating the results. When subclassing, do not forget to call the base class constructor. """ def run(self, result, debug=False): topLevel = False if getattr(result, '_testRunEntered', False) is False: result._testRunEntered = topLevel = True for test in self: if result.shouldStop: break if _isnotsuite(test): self._tearDownPreviousClass(test, result) self._handleModuleFixture(test, result) self._handleClassSetUp(test, result) result._previousTestClass = test.__class__ if (getattr(test.__class__, '_classSetupFailed', False) or getattr(result, '_moduleSetUpFailed', False)): continue if not debug: test(result) else: test.debug() if topLevel: self._tearDownPreviousClass(None, result) self._handleModuleTearDown(result) result._testRunEntered = False return result def debug(self): """Run the tests without collecting errors in a TestResult""" debug = _DebugResult() self.run(debug, True) ################################ def _handleClassSetUp(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if result._moduleSetUpFailed: return if getattr(currentClass, "__unittest_skip__", False): return try: currentClass._classSetupFailed = False except TypeError: # test may actually be a function # so its class will be a builtin-type pass setUpClass = getattr(currentClass, 'setUpClass', None) if setUpClass is not None: _call_if_exists(result, '_setupStdout') try: setUpClass() except Exception as e: if isinstance(result, _DebugResult): raise currentClass._classSetupFailed = True className = util.strclass(currentClass) errorName = 'setUpClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _get_previous_module(self, result): previousModule = None previousClass = getattr(result, '_previousTestClass', None) if previousClass is not None: previousModule = previousClass.__module__ return previousModule def _handleModuleFixture(self, test, result): previousModule = self._get_previous_module(result) currentModule = test.__class__.__module__ if currentModule == previousModule: return self._handleModuleTearDown(result) result._moduleSetUpFailed = False try: module = sys.modules[currentModule] except KeyError: return setUpModule = getattr(module, 'setUpModule', None) if setUpModule is not None: _call_if_exists(result, '_setupStdout') try: setUpModule() except Exception, e: if isinstance(result, _DebugResult): raise result._moduleSetUpFailed = True errorName = 'setUpModule (%s)' % currentModule self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _addClassOrModuleLevelException(self, result, exception, errorName): error = _ErrorHolder(errorName) addSkip = getattr(result, 'addSkip', None) if addSkip is not None and isinstance(exception, case.SkipTest): addSkip(error, str(exception)) else: result.addError(error, sys.exc_info()) def _handleModuleTearDown(self, result): previousModule = self._get_previous_module(result) if previousModule is None: return if result._moduleSetUpFailed: return try: module = sys.modules[previousModule] except KeyError: return tearDownModule = getattr(module, 'tearDownModule', None) if tearDownModule is not None: _call_if_exists(result, '_setupStdout') try: tearDownModule() except Exception as e: if isinstance(result, _DebugResult): raise errorName = 'tearDownModule (%s)' % previousModule self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _tearDownPreviousClass(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if getattr(previousClass, '_classSetupFailed', False): return if getattr(result, '_moduleSetUpFailed', False): return if getattr(previousClass, "__unittest_skip__", False): return tearDownClass = getattr(previousClass, 'tearDownClass', None) if tearDownClass is not None: _call_if_exists(result, '_setupStdout') try: tearDownClass() except Exception, e: if isinstance(result, _DebugResult): raise className = util.strclass(previousClass) errorName = 'tearDownClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') class _ErrorHolder(object): """ Placeholder for a TestCase inside a result. As far as a TestResult is concerned, this looks exactly like a unit test. Used to insert arbitrary errors into a test suite run. """ # Inspired by the ErrorHolder from Twisted: # http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py # attribute used by TestResult._exc_info_to_string failureException = None def __init__(self, description): self.description = description def id(self): return self.description def shortDescription(self): return None def __repr__(self): return "<ErrorHolder description=%r>" % (self.description,) def __str__(self): return self.id() def run(self, result): # could call result.addError(...) - but this test-like object # shouldn't be run anyway pass def __call__(self, result): return self.run(result) def countTestCases(self): return 0 def _isnotsuite(test): "A crude way to tell apart testcases and suites with duck-typing" try: iter(test) except TypeError: return True return False class _DebugResult(object): "Used by the TestSuite to hold previous class when running in debug." _previousTestClass = None _moduleSetUpFailed = False shouldStop = False
gpl-3.0
mozilla/stoneridge
python/src/Lib/test/test_macpath.py
100
2000
import macpath from test import test_support, test_genericpath import unittest class MacPathTestCase(unittest.TestCase): def test_abspath(self): self.assertEqual(macpath.abspath("xx:yy"), "xx:yy") def test_isabs(self): isabs = macpath.isabs self.assertTrue(isabs("xx:yy")) self.assertTrue(isabs("xx:yy:")) self.assertTrue(isabs("xx:")) self.assertFalse(isabs("foo")) self.assertFalse(isabs(":foo")) self.assertFalse(isabs(":foo:bar")) self.assertFalse(isabs(":foo:bar:")) def test_split(self): split = macpath.split self.assertEqual(split("foo:bar"), ('foo:', 'bar')) self.assertEqual(split("conky:mountpoint:foo:bar"), ('conky:mountpoint:foo', 'bar')) self.assertEqual(split(":"), ('', '')) self.assertEqual(split(":conky:mountpoint:"), (':conky:mountpoint', '')) def test_splitext(self): splitext = macpath.splitext self.assertEqual(splitext(":foo.ext"), (':foo', '.ext')) self.assertEqual(splitext("foo:foo.ext"), ('foo:foo', '.ext')) self.assertEqual(splitext(".ext"), ('.ext', '')) self.assertEqual(splitext("foo.ext:foo"), ('foo.ext:foo', '')) self.assertEqual(splitext(":foo.ext:"), (':foo.ext:', '')) self.assertEqual(splitext(""), ('', '')) self.assertEqual(splitext("foo.bar.ext"), ('foo.bar', '.ext')) def test_normpath(self): # Issue 5827: Make sure normpath preserves unicode for path in (u'', u'.', u'/', u'\\', u':', u'///foo/.//bar//'): self.assertIsInstance(macpath.normpath(path), unicode, 'normpath() returned str instead of unicode') class MacCommonTest(test_genericpath.CommonTest): pathmodule = macpath def test_main(): test_support.run_unittest(MacPathTestCase, MacCommonTest) if __name__ == "__main__": test_main()
mpl-2.0
nagyistoce/netzob
src/netzob_plugins/Exporters/WiresharkExporter/WiresharkExporter/WiresharkExporterPlugin.py
1
3712
# -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocols | #+---------------------------------------------------------------------------+ #| Copyright (C) 2012 AMOSSYS | #| 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/>. | #+---------------------------------------------------------------------------+ #| @url : http://www.netzob.org | #| @contact : contact@netzob.org | #| @sponsors : Amossys, http://www.amossys.fr | #| Supélec, http://www.rennes.supelec.fr/ren/rd/cidre/ | #+---------------------------------------------------------------------------+ #+---------------------------------------------------------------------------+ #| Standard library imports | #+---------------------------------------------------------------------------+ from gettext import gettext as _ #+---------------------------------------------------------------------------+ #| Local application imports | #+---------------------------------------------------------------------------+ from netzob.Common.Plugins.ExporterPlugin import ExporterPlugin from netzob.Common.Plugins.Extensions.ExportMenuExtension import ExportMenuExtension from WiresharkExporterController import WiresharkExporterController class WiresharkExporterPlugin(ExporterPlugin): """ Wireshark dissector generator """ __plugin_name__ = "WiresharkExporter" __plugin_version__ = "0.1" __plugin_description__ = _("Generate a LUA script used by Wireshark to dissect specific symbols.") __plugin_author__ = "Alexandre PIGNÉ <alex@freesenses.net>" __plugin_copyright__ = "AMOSSYS" __plugin_license__ = "GPLv3+" def __init__(self, netzobb): super(WiresharkExporterPlugin, self).__init__(netzobb) self.controller = WiresharkExporterController(netzobb, self) self.entry_points = [ExportMenuExtension(netzobb, self.controller, "wiresharkExporter", "Wireshark LUA script")] def getEntryPoints(self): """getEntryPoints: @rtype: netzob_plugins.Exporters.WiresharkExporter.EntryPoints.GlobalMenuEntryPoint.GlobalMenuEntryPoint @return: the plugin entry point, so it can be linked to the netzob project. """ return self.entry_points
gpl-3.0
ArcherCraftStore/ArcherVMPeridot
Python/Lib/site-packages/pip/_vendor/html5lib/tokenizer.py
1710
76929
from __future__ import absolute_import, division, unicode_literals try: chr = unichr # flake8: noqa except NameError: pass from collections import deque from .constants import spaceCharacters from .constants import entities from .constants import asciiLetters, asciiUpper2Lower from .constants import digits, hexDigits, EOF from .constants import tokenTypes, tagTokenTypes from .constants import replacementCharacters from .inputstream import HTMLInputStream from .trie import Trie entitiesTrie = Trie(entities) class HTMLTokenizer(object): """ This class takes care of tokenizing HTML. * self.currentToken Holds the token that is currently being processed. * self.state Holds a reference to the method to be invoked... XXX * self.stream Points to HTMLInputStream object. """ def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True, lowercaseElementName=True, lowercaseAttrName=True, parser=None): self.stream = HTMLInputStream(stream, encoding, parseMeta, useChardet) self.parser = parser # Perform case conversions? self.lowercaseElementName = lowercaseElementName self.lowercaseAttrName = lowercaseAttrName # Setup the initial tokenizer state self.escapeFlag = False self.lastFourChars = [] self.state = self.dataState self.escape = False # The current token being created self.currentToken = None super(HTMLTokenizer, self).__init__() def __iter__(self): """ This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested. """ self.tokenQueue = deque([]) # Start processing. When EOF is reached self.state will return False # instead of True and the loop will terminate. while self.state(): while self.stream.errors: yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)} while self.tokenQueue: yield self.tokenQueue.popleft() def consumeNumberEntity(self, isHex): """This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked. """ allowed = digits radix = 10 if isHex: allowed = hexDigits radix = 16 charStack = [] # Consume all the characters that are in range while making sure we # don't hit an EOF. c = self.stream.char() while c in allowed and c is not EOF: charStack.append(c) c = self.stream.char() # Convert the set of characters consumed to an int. charAsInt = int("".join(charStack), radix) # Certain characters get replaced with others if charAsInt in replacementCharacters: char = replacementCharacters[charAsInt] self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) elif ((0xD800 <= charAsInt <= 0xDFFF) or (charAsInt > 0x10FFFF)): char = "\uFFFD" self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) else: # Should speed up this check somehow (e.g. move the set to a constant) if ((0x0001 <= charAsInt <= 0x0008) or (0x000E <= charAsInt <= 0x001F) or (0x007F <= charAsInt <= 0x009F) or (0xFDD0 <= charAsInt <= 0xFDEF) or charAsInt in frozenset([0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, 0x10FFFF])): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) try: # Try/except needed as UCS-2 Python builds' unichar only works # within the BMP. char = chr(charAsInt) except ValueError: v = charAsInt - 0x10000 char = chr(0xD800 | (v >> 10)) + chr(0xDC00 | (v & 0x3FF)) # Discard the ; if present. Otherwise, put it back on the queue and # invoke parseError on parser. if c != ";": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "numeric-entity-without-semicolon"}) self.stream.unget(c) return char def consumeEntity(self, allowedChar=None, fromAttribute=False): # Initialise to the default output for when no entity is matched output = "&" charStack = [self.stream.char()] if (charStack[0] in spaceCharacters or charStack[0] in (EOF, "<", "&") or (allowedChar is not None and allowedChar == charStack[0])): self.stream.unget(charStack[0]) elif charStack[0] == "#": # Read the next character to see if it's hex or decimal hex = False charStack.append(self.stream.char()) if charStack[-1] in ("x", "X"): hex = True charStack.append(self.stream.char()) # charStack[-1] should be the first digit if (hex and charStack[-1] in hexDigits) \ or (not hex and charStack[-1] in digits): # At least one digit found, so consume the whole number self.stream.unget(charStack[-1]) output = self.consumeNumberEntity(hex) else: # No digits found self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-numeric-entity"}) self.stream.unget(charStack.pop()) output = "&" + "".join(charStack) else: # At this point in the process might have named entity. Entities # are stored in the global variable "entities". # # Consume characters and compare to these to a substring of the # entity names in the list until the substring no longer matches. while (charStack[-1] is not EOF): if not entitiesTrie.has_keys_with_prefix("".join(charStack)): break charStack.append(self.stream.char()) # At this point we have a string that starts with some characters # that may match an entity # Try to find the longest entity the string will match to take care # of &noti for instance. try: entityName = entitiesTrie.longest_prefix("".join(charStack[:-1])) entityLength = len(entityName) except KeyError: entityName = None if entityName is not None: if entityName[-1] != ";": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "named-entity-without-semicolon"}) if (entityName[-1] != ";" and fromAttribute and (charStack[entityLength] in asciiLetters or charStack[entityLength] in digits or charStack[entityLength] == "=")): self.stream.unget(charStack.pop()) output = "&" + "".join(charStack) else: output = entities[entityName] self.stream.unget(charStack.pop()) output += "".join(charStack[entityLength:]) else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-named-entity"}) self.stream.unget(charStack.pop()) output = "&" + "".join(charStack) if fromAttribute: self.currentToken["data"][-1][1] += output else: if output in spaceCharacters: tokenType = "SpaceCharacters" else: tokenType = "Characters" self.tokenQueue.append({"type": tokenTypes[tokenType], "data": output}) def processEntityInAttribute(self, allowedChar): """This method replaces the need for "entityInAttributeValueState". """ self.consumeEntity(allowedChar=allowedChar, fromAttribute=True) def emitCurrentToken(self): """This method is a generic handler for emitting the tags. It also sets the state to "data" because that's what's needed after a token has been emitted. """ token = self.currentToken # Add token to the queue to be yielded if (token["type"] in tagTokenTypes): if self.lowercaseElementName: token["name"] = token["name"].translate(asciiUpper2Lower) if token["type"] == tokenTypes["EndTag"]: if token["data"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "attributes-in-end-tag"}) if token["selfClosing"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "self-closing-flag-on-end-tag"}) self.tokenQueue.append(token) self.state = self.dataState # Below are the various tokenizer states worked out. def dataState(self): data = self.stream.char() if data == "&": self.state = self.entityDataState elif data == "<": self.state = self.tagOpenState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\u0000"}) elif data is EOF: # Tokenization ends. return False elif data in spaceCharacters: # Directly after emitting a token you switch back to the "data # state". At that point spaceCharacters are important so they are # emitted separately. self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data": data + self.stream.charsUntil(spaceCharacters, True)}) # No need to update lastFourChars here, since the first space will # have already been appended to lastFourChars and will have broken # any <!-- or --> sequences else: chars = self.stream.charsUntil(("&", "<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def entityDataState(self): self.consumeEntity() self.state = self.dataState return True def rcdataState(self): data = self.stream.char() if data == "&": self.state = self.characterReferenceInRcdata elif data == "<": self.state = self.rcdataLessThanSignState elif data == EOF: # Tokenization ends. return False elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data in spaceCharacters: # Directly after emitting a token you switch back to the "data # state". At that point spaceCharacters are important so they are # emitted separately. self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data": data + self.stream.charsUntil(spaceCharacters, True)}) # No need to update lastFourChars here, since the first space will # have already been appended to lastFourChars and will have broken # any <!-- or --> sequences else: chars = self.stream.charsUntil(("&", "<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def characterReferenceInRcdata(self): self.consumeEntity() self.state = self.rcdataState return True def rawtextState(self): data = self.stream.char() if data == "<": self.state = self.rawtextLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: # Tokenization ends. return False else: chars = self.stream.charsUntil(("<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def scriptDataState(self): data = self.stream.char() if data == "<": self.state = self.scriptDataLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: # Tokenization ends. return False else: chars = self.stream.charsUntil(("<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def plaintextState(self): data = self.stream.char() if data == EOF: # Tokenization ends. return False elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + self.stream.charsUntil("\u0000")}) return True def tagOpenState(self): data = self.stream.char() if data == "!": self.state = self.markupDeclarationOpenState elif data == "/": self.state = self.closeTagOpenState elif data in asciiLetters: self.currentToken = {"type": tokenTypes["StartTag"], "name": data, "data": [], "selfClosing": False, "selfClosingAcknowledged": False} self.state = self.tagNameState elif data == ">": # XXX In theory it could be something besides a tag name. But # do we really care? self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-tag-name-but-got-right-bracket"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<>"}) self.state = self.dataState elif data == "?": # XXX In theory it could be something besides a tag name. But # do we really care? self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-tag-name-but-got-question-mark"}) self.stream.unget(data) self.state = self.bogusCommentState else: # XXX self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-tag-name"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.dataState return True def closeTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.currentToken = {"type": tokenTypes["EndTag"], "name": data, "data": [], "selfClosing": False} self.state = self.tagNameState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-closing-tag-but-got-right-bracket"}) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-closing-tag-but-got-eof"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.state = self.dataState else: # XXX data can be _'_... self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-closing-tag-but-got-char", "datavars": {"data": data}}) self.stream.unget(data) self.state = self.bogusCommentState return True def tagNameState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeAttributeNameState elif data == ">": self.emitCurrentToken() elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-tag-name"}) self.state = self.dataState elif data == "/": self.state = self.selfClosingStartTagState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["name"] += "\uFFFD" else: self.currentToken["name"] += data # (Don't use charsUntil here, because tag names are # very short and it's faster to not do anything fancy) return True def rcdataLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.rcdataEndTagOpenState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.rcdataState return True def rcdataEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.rcdataEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.rcdataState return True def rcdataEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.rcdataState return True def rawtextLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.rawtextEndTagOpenState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.rawtextState return True def rawtextEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.rawtextEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.rawtextState return True def rawtextEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.rawtextState return True def scriptDataLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.scriptDataEndTagOpenState elif data == "!": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<!"}) self.state = self.scriptDataEscapeStartState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.scriptDataEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEscapeStartState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapeStartDashState else: self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEscapeStartDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapedDashDashState else: self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEscapedState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapedDashState elif data == "<": self.state = self.scriptDataEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: self.state = self.dataState else: chars = self.stream.charsUntil(("<", "-", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def scriptDataEscapedDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapedDashDashState elif data == "<": self.state = self.scriptDataEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataEscapedState elif data == EOF: self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataEscapedState return True def scriptDataEscapedDashDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) elif data == "<": self.state = self.scriptDataEscapedLessThanSignState elif data == ">": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"}) self.state = self.scriptDataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataEscapedState elif data == EOF: self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataEscapedState return True def scriptDataEscapedLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.scriptDataEscapedEndTagOpenState elif data in asciiLetters: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<" + data}) self.temporaryBuffer = data self.state = self.scriptDataDoubleEscapeStartState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataEscapedEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer = data self.state = self.scriptDataEscapedEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataEscapedEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataDoubleEscapeStartState(self): data = self.stream.char() if data in (spaceCharacters | frozenset(("/", ">"))): self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) if self.temporaryBuffer.lower() == "script": self.state = self.scriptDataDoubleEscapedState else: self.state = self.scriptDataEscapedState elif data in asciiLetters: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.temporaryBuffer += data else: self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataDoubleEscapedState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataDoubleEscapedDashState elif data == "<": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.state = self.scriptDataDoubleEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-script-in-script"}) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) return True def scriptDataDoubleEscapedDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataDoubleEscapedDashDashState elif data == "<": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.state = self.scriptDataDoubleEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataDoubleEscapedState elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-script-in-script"}) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataDoubleEscapedState return True def scriptDataDoubleEscapedDashDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) elif data == "<": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.state = self.scriptDataDoubleEscapedLessThanSignState elif data == ">": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"}) self.state = self.scriptDataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataDoubleEscapedState elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-script-in-script"}) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataDoubleEscapedState return True def scriptDataDoubleEscapedLessThanSignState(self): data = self.stream.char() if data == "/": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "/"}) self.temporaryBuffer = "" self.state = self.scriptDataDoubleEscapeEndState else: self.stream.unget(data) self.state = self.scriptDataDoubleEscapedState return True def scriptDataDoubleEscapeEndState(self): data = self.stream.char() if data in (spaceCharacters | frozenset(("/", ">"))): self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) if self.temporaryBuffer.lower() == "script": self.state = self.scriptDataEscapedState else: self.state = self.scriptDataDoubleEscapedState elif data in asciiLetters: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.temporaryBuffer += data else: self.stream.unget(data) self.state = self.scriptDataDoubleEscapedState return True def beforeAttributeNameState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data in asciiLetters: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data == ">": self.emitCurrentToken() elif data == "/": self.state = self.selfClosingStartTagState elif data in ("'", '"', "=", "<"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-character-in-attribute-name"}) self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"].append(["\uFFFD", ""]) self.state = self.attributeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-name-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState return True def attributeNameState(self): data = self.stream.char() leavingThisState = True emitToken = False if data == "=": self.state = self.beforeAttributeValueState elif data in asciiLetters: self.currentToken["data"][-1][0] += data +\ self.stream.charsUntil(asciiLetters, True) leavingThisState = False elif data == ">": # XXX If we emit here the attributes are converted to a dict # without being checked and when the code below runs we error # because data is a dict not a list emitToken = True elif data in spaceCharacters: self.state = self.afterAttributeNameState elif data == "/": self.state = self.selfClosingStartTagState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][0] += "\uFFFD" leavingThisState = False elif data in ("'", '"', "<"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-character-in-attribute-name"}) self.currentToken["data"][-1][0] += data leavingThisState = False elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-name"}) self.state = self.dataState else: self.currentToken["data"][-1][0] += data leavingThisState = False if leavingThisState: # Attributes are not dropped at this stage. That happens when the # start tag token is emitted so values can still be safely appended # to attributes, but we do want to report the parse error in time. if self.lowercaseAttrName: self.currentToken["data"][-1][0] = ( self.currentToken["data"][-1][0].translate(asciiUpper2Lower)) for name, value in self.currentToken["data"][:-1]: if self.currentToken["data"][-1][0] == name: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "duplicate-attribute"}) break # XXX Fix for above XXX if emitToken: self.emitCurrentToken() return True def afterAttributeNameState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data == "=": self.state = self.beforeAttributeValueState elif data == ">": self.emitCurrentToken() elif data in asciiLetters: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data == "/": self.state = self.selfClosingStartTagState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"].append(["\uFFFD", ""]) self.state = self.attributeNameState elif data in ("'", '"', "<"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-character-after-attribute-name"}) self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-end-of-tag-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState return True def beforeAttributeValueState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data == "\"": self.state = self.attributeValueDoubleQuotedState elif data == "&": self.state = self.attributeValueUnQuotedState self.stream.unget(data) elif data == "'": self.state = self.attributeValueSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-value-but-got-right-bracket"}) self.emitCurrentToken() elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" self.state = self.attributeValueUnQuotedState elif data in ("=", "<", "`"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "equals-in-unquoted-attribute-value"}) self.currentToken["data"][-1][1] += data self.state = self.attributeValueUnQuotedState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-value-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data self.state = self.attributeValueUnQuotedState return True def attributeValueDoubleQuotedState(self): data = self.stream.char() if data == "\"": self.state = self.afterAttributeValueState elif data == "&": self.processEntityInAttribute('"') elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-value-double-quote"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data +\ self.stream.charsUntil(("\"", "&", "\u0000")) return True def attributeValueSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterAttributeValueState elif data == "&": self.processEntityInAttribute("'") elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-value-single-quote"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data +\ self.stream.charsUntil(("'", "&", "\u0000")) return True def attributeValueUnQuotedState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeAttributeNameState elif data == "&": self.processEntityInAttribute(">") elif data == ">": self.emitCurrentToken() elif data in ('"', "'", "=", "<", "`"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-character-in-unquoted-attribute-value"}) self.currentToken["data"][-1][1] += data elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-value-no-quotes"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data + self.stream.charsUntil( frozenset(("&", ">", '"', "'", "=", "<", "`", "\u0000")) | spaceCharacters) return True def afterAttributeValueState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeAttributeNameState elif data == ">": self.emitCurrentToken() elif data == "/": self.state = self.selfClosingStartTagState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-EOF-after-attribute-value"}) self.stream.unget(data) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-character-after-attribute-value"}) self.stream.unget(data) self.state = self.beforeAttributeNameState return True def selfClosingStartTagState(self): data = self.stream.char() if data == ">": self.currentToken["selfClosing"] = True self.emitCurrentToken() elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-EOF-after-solidus-in-tag"}) self.stream.unget(data) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-character-after-solidus-in-tag"}) self.stream.unget(data) self.state = self.beforeAttributeNameState return True def bogusCommentState(self): # Make a new comment token and give it as value all the characters # until the first > or EOF (charsUntil checks for EOF automatically) # and emit it. data = self.stream.charsUntil(">") data = data.replace("\u0000", "\uFFFD") self.tokenQueue.append( {"type": tokenTypes["Comment"], "data": data}) # Eat the character directly after the bogus comment which is either a # ">" or an EOF. self.stream.char() self.state = self.dataState return True def markupDeclarationOpenState(self): charStack = [self.stream.char()] if charStack[-1] == "-": charStack.append(self.stream.char()) if charStack[-1] == "-": self.currentToken = {"type": tokenTypes["Comment"], "data": ""} self.state = self.commentStartState return True elif charStack[-1] in ('d', 'D'): matched = True for expected in (('o', 'O'), ('c', 'C'), ('t', 'T'), ('y', 'Y'), ('p', 'P'), ('e', 'E')): charStack.append(self.stream.char()) if charStack[-1] not in expected: matched = False break if matched: self.currentToken = {"type": tokenTypes["Doctype"], "name": "", "publicId": None, "systemId": None, "correct": True} self.state = self.doctypeState return True elif (charStack[-1] == "[" and self.parser is not None and self.parser.tree.openElements and self.parser.tree.openElements[-1].namespace != self.parser.tree.defaultNamespace): matched = True for expected in ["C", "D", "A", "T", "A", "["]: charStack.append(self.stream.char()) if charStack[-1] != expected: matched = False break if matched: self.state = self.cdataSectionState return True self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-dashes-or-doctype"}) while charStack: self.stream.unget(charStack.pop()) self.state = self.bogusCommentState return True def commentStartState(self): data = self.stream.char() if data == "-": self.state = self.commentStartDashState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "incorrect-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += data self.state = self.commentState return True def commentStartDashState(self): data = self.stream.char() if data == "-": self.state = self.commentEndState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "-\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "incorrect-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += "-" + data self.state = self.commentState return True def commentState(self): data = self.stream.char() if data == "-": self.state = self.commentEndDashState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += data + \ self.stream.charsUntil(("-", "\u0000")) return True def commentEndDashState(self): data = self.stream.char() if data == "-": self.state = self.commentEndState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "-\uFFFD" self.state = self.commentState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment-end-dash"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += "-" + data self.state = self.commentState return True def commentEndState(self): data = self.stream.char() if data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "--\uFFFD" self.state = self.commentState elif data == "!": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-bang-after-double-dash-in-comment"}) self.state = self.commentEndBangState elif data == "-": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-dash-after-double-dash-in-comment"}) self.currentToken["data"] += data elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment-double-dash"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: # XXX self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-comment"}) self.currentToken["data"] += "--" + data self.state = self.commentState return True def commentEndBangState(self): data = self.stream.char() if data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "-": self.currentToken["data"] += "--!" self.state = self.commentEndDashState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "--!\uFFFD" self.state = self.commentState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment-end-bang-state"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += "--!" + data self.state = self.commentState return True def doctypeState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeDoctypeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-doctype-name-but-got-eof"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "need-space-after-doctype"}) self.stream.unget(data) self.state = self.beforeDoctypeNameState return True def beforeDoctypeNameState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-doctype-name-but-got-right-bracket"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["name"] = "\uFFFD" self.state = self.doctypeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-doctype-name-but-got-eof"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["name"] = data self.state = self.doctypeNameState return True def doctypeNameState(self): data = self.stream.char() if data in spaceCharacters: self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) self.state = self.afterDoctypeNameState elif data == ">": self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["name"] += "\uFFFD" self.state = self.doctypeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype-name"}) self.currentToken["correct"] = False self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["name"] += data return True def afterDoctypeNameState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.currentToken["correct"] = False self.stream.unget(data) self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: if data in ("p", "P"): matched = True for expected in (("u", "U"), ("b", "B"), ("l", "L"), ("i", "I"), ("c", "C")): data = self.stream.char() if data not in expected: matched = False break if matched: self.state = self.afterDoctypePublicKeywordState return True elif data in ("s", "S"): matched = True for expected in (("y", "Y"), ("s", "S"), ("t", "T"), ("e", "E"), ("m", "M")): data = self.stream.char() if data not in expected: matched = False break if matched: self.state = self.afterDoctypeSystemKeywordState return True # All the characters read before the current 'data' will be # [a-zA-Z], so they're garbage in the bogus doctype and can be # discarded; only the latest character might be '>' or EOF # and needs to be ungetted self.stream.unget(data) self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-space-or-right-bracket-in-doctype", "datavars": {"data": data}}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def afterDoctypePublicKeywordState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeDoctypePublicIdentifierState elif data in ("'", '"'): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.stream.unget(data) self.state = self.beforeDoctypePublicIdentifierState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.stream.unget(data) self.state = self.beforeDoctypePublicIdentifierState return True def beforeDoctypePublicIdentifierState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == "\"": self.currentToken["publicId"] = "" self.state = self.doctypePublicIdentifierDoubleQuotedState elif data == "'": self.currentToken["publicId"] = "" self.state = self.doctypePublicIdentifierSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def doctypePublicIdentifierDoubleQuotedState(self): data = self.stream.char() if data == "\"": self.state = self.afterDoctypePublicIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["publicId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["publicId"] += data return True def doctypePublicIdentifierSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterDoctypePublicIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["publicId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["publicId"] += data return True def afterDoctypePublicIdentifierState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.betweenDoctypePublicAndSystemIdentifiersState elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == '"': self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierDoubleQuotedState elif data == "'": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierSingleQuotedState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def betweenDoctypePublicAndSystemIdentifiersState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == '"': self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierDoubleQuotedState elif data == "'": self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierSingleQuotedState elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def afterDoctypeSystemKeywordState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeDoctypeSystemIdentifierState elif data in ("'", '"'): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.stream.unget(data) self.state = self.beforeDoctypeSystemIdentifierState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.stream.unget(data) self.state = self.beforeDoctypeSystemIdentifierState return True def beforeDoctypeSystemIdentifierState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == "\"": self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierDoubleQuotedState elif data == "'": self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def doctypeSystemIdentifierDoubleQuotedState(self): data = self.stream.char() if data == "\"": self.state = self.afterDoctypeSystemIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["systemId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["systemId"] += data return True def doctypeSystemIdentifierSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterDoctypeSystemIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["systemId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["systemId"] += data return True def afterDoctypeSystemIdentifierState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.state = self.bogusDoctypeState return True def bogusDoctypeState(self): data = self.stream.char() if data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: # XXX EMIT self.stream.unget(data) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: pass return True def cdataSectionState(self): data = [] while True: data.append(self.stream.charsUntil("]")) data.append(self.stream.charsUntil(">")) char = self.stream.char() if char == EOF: break else: assert char == ">" if data[-1][-2:] == "]]": data[-1] = data[-1][:-2] break else: data.append(char) data = "".join(data) # Deal with null here rather than in the parser nullCount = data.count("\u0000") if nullCount > 0: for i in range(nullCount): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) data = data.replace("\u0000", "\uFFFD") if data: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.dataState return True
apache-2.0
franksort/css3tool
css3tool.py
1
3351
from parser import CSSParser import re from lxml.cssselect import CSSSelector from lxml.html import fromstring import argparse import os.path import logging logger = logging.getLogger() handler = logging.StreamHandler() logger.addHandler(handler) formatter = logging.Formatter('[%(levelname)s] %(message)s') handler.setFormatter(formatter) def get_unused_selectors(css, html): if logger.getEffectiveLevel() == logging.DEBUG: debug = True else: debug = False parser = CSSParser(debug) parser.parse(css) root = fromstring(html) unused = [] for s in parser.selectors: sel = CSSSelector(s) if len(sel(root)) == 0: unused.append(s) return unused if __name__ == '__main__': desc = " _ \n" \ " ' ) /) \n" \ " _ _ _ -( _/_ ______// \n" \ " (__/_)_/_)_(__ ) (__(_)(_)(/_ \n\n" \ " A tool for finding unused CSS3 selectors." \ example = 'example usage:\n' \ ' python css3tool.py index.html 1.css\n' \ ' python css3tool.py index.html 1.css 2.css\n' \ ' python css3tool.py index.html example/cssdir\n' \ ' python css3tool.py index.html 1.css example/cssdir' \ argparser = argparse.ArgumentParser(description=desc, epilog=example, formatter_class=argparse.RawDescriptionHelpFormatter) argparser.add_argument(dest='html', metavar='<HTML file>', type=argparse.FileType('r'), help='path to an HTML file') argparser.add_argument(dest='css', nargs='+', metavar='<CSS file or dir>', help='paths to a CSS files or directories') argparser.add_argument('--debug', dest='debug', action='store_true', help='turns on debugging') try: args = argparser.parse_args() except IOError as e: argparser.error('{0}'.format(e)) if(args.debug): logger.setLevel(logging.DEBUG) # HTML string html_str = args.html.read() # Convert CSS paths provided as arguments to real path if necessary. css_paths = [] for css_path in args.css: css_paths.append(os.path.realpath(css_path)) # Traverse CSS paths provided as arguments. If the path is a # directory, add the files it contains recursively then remove # the directory from the list. for css_path in css_paths: if os.path.isdir(css_path): for root, dirs, files in os.walk(css_path): for file in files: css_paths.append(os.path.join(root, file)) css_paths.remove(css_path) # Remove duplicate paths. css_paths = list(set(css_paths)) # Each list of unused selectors are stored in a dict # with the CSS file being as the key. # ie. {'/path/to/example.css': ['h1', 'h2'] result = {} for css_path in css_paths: fh = open(css_path) css_str = fh.read() fh.close() result[css_path] = get_unused_selectors(css=css_str, html=html_str) print 'Unused Selectors:' print result
mit
phiros/nepi
src/nepi/resources/ns3/classes/receive_list_error_model.py
1
1751
# # NEPI, a framework to manage network experiments # Copyright (C) 2014 INRIA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from nepi.execution.attribute import Attribute, Flags, Types from nepi.execution.trace import Trace, TraceAttr from nepi.execution.resource import ResourceManager, clsinit_copy, \ ResourceState from nepi.resources.ns3.ns3errormodel import NS3BaseErrorModel @clsinit_copy class NS3ReceiveListErrorModel(NS3BaseErrorModel): _rtype = "ns3::ReceiveListErrorModel" @classmethod def _register_attributes(cls): attr_isenabled = Attribute("IsEnabled", "Whether this ErrorModel is enabled or not.", type = Types.Bool, default = "True", allowed = None, range = None, flags = Flags.Reserved | Flags.Construct) cls._register_attribute(attr_isenabled) @classmethod def _register_traces(cls): pass def __init__(self, ec, guid): super(NS3ReceiveListErrorModel, self).__init__(ec, guid) self._home = "ns3-receive-list-error-model-%s" % self.guid
gpl-3.0
chromium/chromium
tools/perf/page_sets/loading_mobile.py
6
9572
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections from page_sets import page_cycler_story from telemetry.page import cache_temperature as cache_temperature_module from telemetry.page import shared_page_state from telemetry.page import traffic_setting as traffic_setting_module from telemetry import story Tag = collections.namedtuple('Tag', ['name', 'description']) # pylint: disable=line-too-long # Used https://cs.chromium.org/chromium/src/tools/perf/experimental/story_clustering/README.md # to find representative stories. ABRIDGED = Tag('abridged', 'Story should be included in abridged runs') ABRIDGED_STORY_NAMES = [ "Facebook", "GoogleIndia", "LocalMoxie", "Dramaq", "Hongkiat", "FranceTVInfo", ] class LoadingMobileStorySet(story.StorySet): """ A collection of tests to measure loading performance of mobile sites. Design doc: https://docs.google.com/document/d/1QKlZIoURAxZk-brrXsKYZl9O8ieqXht3ogeF9yLNFCI/edit """ def __init__(self, cache_temperatures=None, cache_temperatures_for_pwa=None, traffic_settings=None, include_tags=None): super(LoadingMobileStorySet, self).__init__( archive_data_file='data/loading_mobile.json', cloud_storage_bucket=story.PARTNER_BUCKET) if include_tags is None: include_tags = ['*'] if cache_temperatures is None: cache_temperatures = [cache_temperature_module.ANY] if cache_temperatures_for_pwa is None: cache_temperatures_for_pwa = [cache_temperature_module.ANY] if traffic_settings is None: traffic_settings = [traffic_setting_module.NONE] if '*' in include_tags or 'global' in include_tags: self.AddStories(['global'], [ ('https://www.google.com/search?q=flower#q=flower+delivery', 'GoogleRedirectToGoogleJapan'), ('https://www.youtube.com/watch?v=MU3YuvNRhVY', 'Youtube'), # pylint: disable=line-too-long ('https://www.google.co.in/search?q=%E0%A4%AB%E0%A5%82%E0%A4%B2&rct=j#q=%E0%A4%AB%E0%A5%82%E0%A4%B2+%E0%A4%B5%E0%A4%BF%E0%A4%A4%E0%A4%B0%E0%A4%A3', 'GoogleIndia'), ('https://www.google.com.br/search?q=flor#q=Entrega+de+flores&start=10', 'GoogleBrazil'), ('https://www.google.co.id/#q=pengiriman+bunga', 'GoogleIndonesia'), ('https://m.facebook.com/?soft=messages', 'Facebook'), # pylint: disable=line-too-long ('http://g1.globo.com/politica/noticia/2016/02/maioria-do-stf-autoriza-fisco-obter-dados-bancarios-sem-decisao-judicial.html', 'G1'), # pylint: disable=line-too-long ('https://m.baidu.com/s?word=%E9%B2%9C%E8%8A%B1%E9%80%9F%E9%80%92&oq=%E9%B2%9C%E8%8A%B1', 'Baidu'), # pylint: disable=line-too-long ('http://news.yahoo.com/were-top-10-most-visited-us-national-parks-105323727.html', 'YahooNews'), ('https://en.m.wikipedia.org/wiki/Solo_Foods', 'Wikipedia'), # pylint: disable=line-too-long ('http://noticias.bol.uol.com.br/ultimas-noticias/brasil/2016/08/03/tufao-nida-nao-deixa-vitimas-mas-prejuizos-de-us-43-milhoes.htm', 'BOLNoticias'), ('http://www.amazon.com/gp/aw/s/ref=is_s/189-8585431-1246432?k=shoes', 'Amazon'), # pylint: disable=line-too-long ('http://m.tribunnews.com/superskor/2016/08/03/ribuan-polisi-dikerahkan-mengawal-bonek', 'TribunNews'), ('http://xw.qq.com/news/20160803025029/NEW2016080302502901', 'QQNews'), # pylint: disable=line-too-long ('http://m.kaskus.co.id/thread/57a03a3214088d91068b4567/inilah-akibat-bersikap-overprotektif-terhadap-anak/?ref=homelanding&med=hot_thread', 'Kaskus'), ('http://www.dailymotion.com/video/x3d1kj5_fallout-4-review_videogames', 'Dailymotion'), ('https://mobile.twitter.com/scottjehl/status/760618697727803394', 'Twitter'), ('http://m.kapanlagi.com/lirik/artis/anji/kata_siapa/', 'KapanLagi'), # pylint: disable=line-too-long ('http://olx.co.id/iklan/iphone-6s-64-rose-gold-warna-favorite-IDiSdm5.html#5310a118c3;promoted', 'OLX'), # pylint: disable=line-too-long ('http://enquiry.indianrail.gov.in/mntes/MntesServlet?action=MainMenu&subAction=excep&excpType=EC', 'EnquiryIndianRail'), # TODO(rnephew): Rerecord this. crbug.com/728882 # pylint: disable=line-too-long # ('https://googleblog.blogspot.jp/2016/02/building-safer-web-for-everyone.html', # 'Blogspot'), # pylint: disable=line-too-long # ('http://m.detik.com/finance/read/2016/02/19/151843/3146351/1034/ekspor-tambang-mentah-mau-dibuka-lagi-kalau-sudah-bangun-smelter-bagaimana', # 'Detik'), ], cache_temperatures, traffic_settings) if '*' in include_tags or 'pwa' in include_tags: self.AddStories(['pwa'], [ # pylint: disable=line-too-long ('https://www.flipkart.com/big-wing-casuals/p/itmemeageyfn6m9z?lid=LSTSHOEMEAGURG2PHPW18FTBN&pid=SHOEMEAGURG2PHPW', 'FlipKart'), ('https://smp.suumo.jp/mansion/tokyo/sc_104/cond/?moreCond=1', 'Suumo'), ('https://voice-memos.appspot.com', 'VoiceMemos'), ('https://dev.opera.com/', 'DevOpera'), ('https://flipboard.com/topic/yoga', 'FlipBoard'), # TODO(rnephew): Record these. crbug.com/728882 # ('https://wiki-offline.jakearchibald.com/', # 'WikiOffline'), # ('https://busrouter.sg', 'BusRouter'), # ('https://airhorner.com', 'AirHorner'), ], cache_temperatures_for_pwa, traffic_settings) if '*' in include_tags or 'tough_ttfmp' in include_tags: self.AddStories(['tough_ttfmp'], [ ('http://www.localmoxie.com', 'LocalMoxie'), ('http://www.dawn.com', 'Dawn'), ('http://www.thairath.co.th', 'Thairath'), ], cache_temperatures, traffic_settings) if '*' in include_tags or 'easy_ttfmp' in include_tags: self.AddStories(['easy_ttfmp'], [ ('http://www.slideshare.net', 'SlideShare'), ('http://www.bradesco.com.br', 'Bradesco'), ('http://www.gsshop.com', 'GSShop'), ], cache_temperatures, traffic_settings) if '*' in include_tags or 'tough_tti' in include_tags: self.AddStories(['tough_tti'], [ ('http://www.thestar.com.my', 'TheStar'), ('http://www.58pic.com', '58Pic'), ('http://www.hongkiat.com', 'Hongkiat'), ], cache_temperatures, traffic_settings) if '*' in include_tags or 'easy_tti' in include_tags: self.AddStories(['easy_tti'], [ ('http://www.dramaq.com.tw', 'Dramaq'), ('http://www.locanto.in', 'Locanto'), ('http://www.francetvinfo.fr', 'FranceTVInfo'), ], cache_temperatures, traffic_settings) # The many_agents stories are not added unless explicitly specified to keep # loading.{mobile,desktop} benchmarks short. if 'many_agents' in include_tags: self.AddStories(['many_agents'], [ ('https://www.amazon.co.jp', 'AmazonJP'), ('https://www.netflix.com', 'Netflix'), ('https://sina.com.cn', 'Sina'), ('https://www.ebay.com', 'Ebay'), ('https://www.msn.com', 'MSN'), ('https://www.imdb.com', 'IMDB'), ('https://www.cnn.com', 'CNN'), ('https://www.bbc.com', 'BBC'), ('https://www.espn.com', 'ESPN'), ('https://www.nytimes.com', 'NyTimes'), ('https://www.nicovideo.jp', 'Nicovideo'), ('https://www.cricbuzz.com', 'Cricbuzz'), ('https://www.theguardian.com', 'TheGuardian'), ('https://www.cnet.com', 'CNet'), ('https://www.indiatimes.com', 'IndiaTimes'), ('https://www.sindonews.com', 'SindoNews'), ], cache_temperatures, traffic_settings) def GetAbridgedStorySetTagFilter(self): return ABRIDGED.name def AddStories(self, tags, urls, cache_temperatures, traffic_settings): for url, name in urls: for temp in cache_temperatures: for traffic in traffic_settings: page_name = name if temp == cache_temperature_module.COLD: page_name += '_cold' tags.append('cache_temperature_cold') elif temp == cache_temperature_module.WARM: page_name += '_warm' tags.append('cache_temperature_warm') elif temp == cache_temperature_module.HOT: page_name += '_hot' tags.append('cache_temperature_hot') elif temp == cache_temperature_module.ANY: pass else: raise NotImplementedError if traffic == traffic_setting_module.REGULAR_3G: page_name += '_3g' page_tags = tags[:] if page_name in ABRIDGED_STORY_NAMES: page_tags.append(ABRIDGED.name) self.AddStory( page_cycler_story.PageCyclerStory( url, self, name=page_name, shared_page_state_class=shared_page_state. SharedMobilePageState, cache_temperature=temp, traffic_setting=traffic, tags=page_tags, perform_final_navigation=True))
bsd-3-clause
ChinaMassClouds/copenstack-server
openstack/src/ceilometer-2014.2.2/ceilometer/tests/data_processing/test_notifications.py
6
3314
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import mock from oslo.config import cfg from oslotest import base from ceilometer.data_processing import notifications from ceilometer.openstack.common import log from ceilometer import sample NOW = datetime.datetime.isoformat(datetime.datetime.utcnow()) TENANT_ID = u'4c35985848bf4419b3f3d52c22e5792d' CLUSTER_NAME = u'AS1-ASGroup-53sqbo7sor7i' CLUSTER_ID = u'cb4a6fd1-1f5d-4002-ae91-9b91573cfb03' USER_NAME = u'demo' USER_ID = u'2e61f25ec63a4f6c954a6245421448a4' CLUSTER_STATUS = u'Active' PROJECT_ID = TENANT_ID RESOURCE_ID = CLUSTER_ID PUBLISHER_ID = u'data_processing.node-n5x66lxdy67d' CONF = cfg.CONF CONF.set_override('use_stderr', True) LOG = log.getLogger(__name__) def _dp_notification_for(operation): return { u'event_type': '%s.cluster.%s' % (notifications.SERVICE, operation), u'_context_roles': [ u'Member', ], u'_context_auth_uri': u'http://0.1.0.1:1010/v2.0', u'timestamp': NOW, u'_context_tenant_id': TENANT_ID, u'payload': { u'cluster_id': CLUSTER_ID, u'cluster_name': CLUSTER_NAME, u'cluster_status': CLUSTER_STATUS, u'project_id': TENANT_ID, u'user_id': USER_ID, }, u'_context_username': USER_NAME, u'_context_token': u'MIISAwYJKoZIhvcNAQcCoII...', u'_context_user_id': USER_ID, u'_context_tenant_name': USER_NAME, u'priority': u'INFO', u'_context_is_admin': False, u'publisher_id': PUBLISHER_ID, u'message_id': u'ef921faa-7f7b-4854-8b86-a424ab93c96e', } class TestNotification(base.BaseTestCase): def _verify_common_sample(self, actual, operation): self.assertIsNotNone(actual) self.assertEqual('cluster.%s' % operation, actual.name) self.assertEqual(NOW, actual.timestamp) self.assertEqual(sample.TYPE_DELTA, actual.type) self.assertEqual(PROJECT_ID, actual.project_id) self.assertEqual(RESOURCE_ID, actual.resource_id) self.assertEqual(USER_ID, actual.user_id) metadata = actual.resource_metadata self.assertEqual(PUBLISHER_ID, metadata.get('host')) def _test_operation(self, operation): notif = _dp_notification_for(operation) handler = notifications.DataProcessing(mock.Mock()) data = list(handler.process_notification(notif)) self.assertEqual(1, len(data)) self._verify_common_sample(data[0], operation) def test_create(self): self._test_operation('create') def test_update(self): self._test_operation('update') def test_delete(self): self._test_operation('delete')
gpl-2.0
nathanielvarona/airflow
tests/providers/google/cloud/operators/test_life_sciences.py
3
2349
# # 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. """Tests for Google Life Sciences Run Pipeline operator """ import unittest from unittest import mock from airflow.providers.google.cloud.operators.life_sciences import LifeSciencesRunPipelineOperator TEST_BODY = {"pipeline": {"actions": [{}], "resources": {}, "environment": {}, "timeout": '3.5s'}} TEST_OPERATION = { "name": 'operation-name', "metadata": {"@type": 'anytype'}, "done": True, "response": "response", } TEST_PROJECT_ID = "life-science-project-id" TEST_LOCATION = 'test-location' class TestLifeSciencesRunPipelineOperator(unittest.TestCase): @mock.patch("airflow.providers.google.cloud.operators.life_sciences.LifeSciencesHook") def test_executes(self, mock_hook): mock_instance = mock_hook.return_value mock_instance.run_pipeline.return_value = TEST_OPERATION operator = LifeSciencesRunPipelineOperator( task_id='task-id', body=TEST_BODY, location=TEST_LOCATION, project_id=TEST_PROJECT_ID ) result = operator.execute(None) assert result == TEST_OPERATION @mock.patch("airflow.providers.google.cloud.operators.life_sciences.LifeSciencesHook") def test_executes_without_project_id(self, mock_hook): mock_instance = mock_hook.return_value mock_instance.run_pipeline.return_value = TEST_OPERATION operator = LifeSciencesRunPipelineOperator( task_id='task-id', body=TEST_BODY, location=TEST_LOCATION, ) result = operator.execute(None) assert result == TEST_OPERATION
apache-2.0
elena/django
django/contrib/gis/gdal/driver.py
59
3264
from ctypes import c_void_p from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi from django.utils.encoding import force_bytes, force_str class Driver(GDALBase): """ Wrap a GDAL/OGR Data Source Driver. For more information, see the C API source code: https://www.gdal.org/gdal_8h.html - https://www.gdal.org/ogr__api_8h.html """ # Case-insensitive aliases for some GDAL/OGR Drivers. # For a complete list of original driver names see # https://www.gdal.org/ogr_formats.html (vector) # https://www.gdal.org/formats_list.html (raster) _alias = { # vector 'esri': 'ESRI Shapefile', 'shp': 'ESRI Shapefile', 'shape': 'ESRI Shapefile', 'tiger': 'TIGER', 'tiger/line': 'TIGER', # raster 'tiff': 'GTiff', 'tif': 'GTiff', 'jpeg': 'JPEG', 'jpg': 'JPEG', } def __init__(self, dr_input): """ Initialize an GDAL/OGR driver on either a string or integer input. """ if isinstance(dr_input, str): # If a string name of the driver was passed in self.ensure_registered() # Checking the alias dictionary (case-insensitive) to see if an # alias exists for the given driver. if dr_input.lower() in self._alias: name = self._alias[dr_input.lower()] else: name = dr_input # Attempting to get the GDAL/OGR driver by the string name. for iface in (vcapi, rcapi): driver = c_void_p(iface.get_driver_by_name(force_bytes(name))) if driver: break elif isinstance(dr_input, int): self.ensure_registered() for iface in (vcapi, rcapi): driver = iface.get_driver(dr_input) if driver: break elif isinstance(dr_input, c_void_p): driver = dr_input else: raise GDALException('Unrecognized input type for GDAL/OGR Driver: %s' % type(dr_input)) # Making sure we get a valid pointer to the OGR Driver if not driver: raise GDALException('Could not initialize GDAL/OGR Driver on input: %s' % dr_input) self.ptr = driver def __str__(self): return self.name @classmethod def ensure_registered(cls): """ Attempt to register all the data source drivers. """ # Only register all if the driver counts are 0 (or else all drivers # will be registered over and over again) if not vcapi.get_driver_count(): vcapi.register_all() if not rcapi.get_driver_count(): rcapi.register_all() @classmethod def driver_count(cls): """ Return the number of GDAL/OGR data source drivers registered. """ return vcapi.get_driver_count() + rcapi.get_driver_count() @property def name(self): """ Return description/name string for this driver. """ return force_str(rcapi.get_driver_description(self.ptr))
bsd-3-clause
JinnLynn/alfred-workflows
lib/html5lib/sanitizer.py
805
16428
from __future__ import absolute_import, division, unicode_literals import re from xml.sax.saxutils import escape, unescape from .tokenizer import HTMLTokenizer from .constants import tokenTypes class HTMLSanitizerMixin(object): """ sanitization of XHTML+MathML+SVG and of inline style attributes.""" acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset', 'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins', 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter', 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option', 'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select', 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video'] mathml_elements = ['maction', 'math', 'merror', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'none'] svg_elements = ['a', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'clipPath', 'circle', 'defs', 'desc', 'ellipse', 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern', 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', 'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use'] acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis', 'background', 'balance', 'bgcolor', 'bgproperties', 'border', 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding', 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff', 'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'compact', 'contenteditable', 'controls', 'coords', 'data', 'datafld', 'datapagesize', 'datasrc', 'datetime', 'default', 'delay', 'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end', 'face', 'for', 'form', 'frame', 'galleryimg', 'gutter', 'headers', 'height', 'hidefocus', 'hidden', 'high', 'href', 'hreflang', 'hspace', 'icon', 'id', 'inputmode', 'ismap', 'keytype', 'label', 'leftspacing', 'lang', 'list', 'longdesc', 'loop', 'loopcount', 'loopend', 'loopstart', 'low', 'lowsrc', 'max', 'maxlength', 'media', 'method', 'min', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'open', 'optimum', 'pattern', 'ping', 'point-size', 'poster', 'pqg', 'preload', 'prompt', 'radiogroup', 'readonly', 'rel', 'repeat-max', 'repeat-min', 'replace', 'required', 'rev', 'rightspacing', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'start', 'step', 'style', 'summary', 'suppress', 'tabindex', 'target', 'template', 'title', 'toppadding', 'type', 'unselectable', 'usemap', 'urn', 'valign', 'value', 'variable', 'volume', 'vspace', 'vrml', 'width', 'wrap', 'xml:lang'] mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'depth', 'display', 'displaystyle', 'equalcolumns', 'equalrows', 'fence', 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness', 'lspace', 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant', 'maxsize', 'minsize', 'other', 'rowalign', 'rowalign', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection', 'separator', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show', 'xlink:type', 'xmlns', 'xmlns:xlink'] svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic', 'arabic-form', 'ascent', 'attributeName', 'attributeType', 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height', 'class', 'clip-path', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx', 'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-opacity', 'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x', 'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', 'keySplines', 'keyTimes', 'lang', 'marker-end', 'marker-mid', 'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'mathematical', 'max', 'min', 'name', 'offset', 'opacity', 'orient', 'origin', 'overline-position', 'overline-thickness', 'panose-1', 'path', 'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'systemLanguage', 'target', 'text-anchor', 'to', 'transform', 'type', 'u1', 'u2', 'underline-position', 'underline-thickness', 'unicode', 'unicode-range', 'units-per-em', 'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x', 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', 'y1', 'y2', 'zoomAndPan'] attr_val_is_uri = ['href', 'src', 'cite', 'action', 'longdesc', 'poster', 'xlink:href', 'xml:base'] svg_attr_val_allows_ref = ['clip-path', 'color-profile', 'cursor', 'fill', 'filter', 'marker', 'marker-start', 'marker-mid', 'marker-end', 'mask', 'stroke'] svg_allow_local_href = ['altGlyph', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'cursor', 'feImage', 'filter', 'linearGradient', 'pattern', 'radialGradient', 'textpath', 'tref', 'set', 'use'] acceptable_css_properties = ['azimuth', 'background-color', 'border-bottom-color', 'border-collapse', 'border-color', 'border-left-color', 'border-right-color', 'border-top-color', 'clear', 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font', 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'overflow', 'pause', 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness', 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation', 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent', 'unicode-bidi', 'vertical-align', 'voice-family', 'volume', 'white-space', 'width'] acceptable_css_keywords = ['auto', 'aqua', 'black', 'block', 'blue', 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed', 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left', 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive', 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top', 'transparent', 'underline', 'white', 'yellow'] acceptable_svg_properties = ['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-opacity'] acceptable_protocols = ['ed2k', 'ftp', 'http', 'https', 'irc', 'mailto', 'news', 'gopher', 'nntp', 'telnet', 'webcal', 'xmpp', 'callto', 'feed', 'urn', 'aim', 'rsync', 'tag', 'ssh', 'sftp', 'rtsp', 'afs'] # subclasses may define their own versions of these constants allowed_elements = acceptable_elements + mathml_elements + svg_elements allowed_attributes = acceptable_attributes + mathml_attributes + svg_attributes allowed_css_properties = acceptable_css_properties allowed_css_keywords = acceptable_css_keywords allowed_svg_properties = acceptable_svg_properties allowed_protocols = acceptable_protocols # Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and # stripping out all # attributes not in ALLOWED_ATTRIBUTES. Style # attributes are parsed, and a restricted set, # specified by # ALLOWED_CSS_PROPERTIES and ALLOWED_CSS_KEYWORDS, are allowed through. # attributes in ATTR_VAL_IS_URI are scanned, and only URI schemes specified # in ALLOWED_PROTOCOLS are allowed. # # sanitize_html('<script> do_nasty_stuff() </script>') # => &lt;script> do_nasty_stuff() &lt;/script> # sanitize_html('<a href="javascript: sucker();">Click here for $100</a>') # => <a>Click here for $100</a> def sanitize_token(self, token): # accommodate filters which use token_type differently token_type = token["type"] if token_type in list(tokenTypes.keys()): token_type = tokenTypes[token_type] if token_type in (tokenTypes["StartTag"], tokenTypes["EndTag"], tokenTypes["EmptyTag"]): if token["name"] in self.allowed_elements: return self.allowed_token(token, token_type) else: return self.disallowed_token(token, token_type) elif token_type == tokenTypes["Comment"]: pass else: return token def allowed_token(self, token, token_type): if "data" in token: attrs = dict([(name, val) for name, val in token["data"][::-1] if name in self.allowed_attributes]) for attr in self.attr_val_is_uri: if attr not in attrs: continue val_unescaped = re.sub("[`\000-\040\177-\240\s]+", '', unescape(attrs[attr])).lower() # remove replacement characters from unescaped characters val_unescaped = val_unescaped.replace("\ufffd", "") if (re.match("^[a-z0-9][-+.a-z0-9]*:", val_unescaped) and (val_unescaped.split(':')[0] not in self.allowed_protocols)): del attrs[attr] for attr in self.svg_attr_val_allows_ref: if attr in attrs: attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', ' ', unescape(attrs[attr])) if (token["name"] in self.svg_allow_local_href and 'xlink:href' in attrs and re.search('^\s*[^#\s].*', attrs['xlink:href'])): del attrs['xlink:href'] if 'style' in attrs: attrs['style'] = self.sanitize_css(attrs['style']) token["data"] = [[name, val] for name, val in list(attrs.items())] return token def disallowed_token(self, token, token_type): if token_type == tokenTypes["EndTag"]: token["data"] = "</%s>" % token["name"] elif token["data"]: attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token["data"]]) token["data"] = "<%s%s>" % (token["name"], attrs) else: token["data"] = "<%s>" % token["name"] if token.get("selfClosing"): token["data"] = token["data"][:-1] + "/>" if token["type"] in list(tokenTypes.keys()): token["type"] = "Characters" else: token["type"] = tokenTypes["Characters"] del token["name"] return token def sanitize_css(self, style): # disallow urls style = re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) # gauntlet if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): return '' if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): return '' clean = [] for prop, value in re.findall("([-\w]+)\s*:\s*([^:;]*)", style): if not value: continue if prop.lower() in self.allowed_css_properties: clean.append(prop + ': ' + value + ';') elif prop.split('-')[0].lower() in ['background', 'border', 'margin', 'padding']: for keyword in value.split(): if not keyword in self.acceptable_css_keywords and \ not re.match("^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$", keyword): break else: clean.append(prop + ': ' + value + ';') elif prop.lower() in self.allowed_svg_properties: clean.append(prop + ': ' + value + ';') return ' '.join(clean) class HTMLSanitizer(HTMLTokenizer, HTMLSanitizerMixin): def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True, lowercaseElementName=False, lowercaseAttrName=False, parser=None): # Change case matching defaults as we only output lowercase html anyway # This solution doesn't seem ideal... HTMLTokenizer.__init__(self, stream, encoding, parseMeta, useChardet, lowercaseElementName, lowercaseAttrName, parser=parser) def __iter__(self): for token in HTMLTokenizer.__iter__(self): token = self.sanitize_token(token) if token: yield token
mit
jakwakwa/simple-slide-angularjs
node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
1284
100329
# Copyright (c) 2013 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. import collections import copy import hashlib import json import multiprocessing import os.path import re import signal import subprocess import sys import gyp import gyp.common from gyp.common import OrderedSet import gyp.msvs_emulation import gyp.MSVSUtil as MSVSUtil import gyp.xcode_emulation from cStringIO import StringIO from gyp.common import GetEnvironFallback import gyp.ninja_syntax as ninja_syntax generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'SHARED_LIB_PREFIX': 'lib', # Gyp expects the following variables to be expandable by the build # system to the appropriate locations. Ninja prefers paths to be # known at gyp time. To resolve this, introduce special # variables starting with $! and $| (which begin with a $ so gyp knows it # should be treated specially, but is otherwise an invalid # ninja/shell variable) that are passed to gyp here but expanded # before writing out into the target .ninja files; see # ExpandSpecial. # $! is used for variables that represent a path and that can only appear at # the start of a string, while $| is used for variables that can appear # anywhere in a string. 'INTERMEDIATE_DIR': '$!INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR': '$!PRODUCT_DIR/gen', 'PRODUCT_DIR': '$!PRODUCT_DIR', 'CONFIGURATION_NAME': '$|CONFIGURATION_NAME', # Special variables that may be used by gyp 'rule' targets. # We generate definitions for these variables on the fly when processing a # rule. 'RULE_INPUT_ROOT': '${root}', 'RULE_INPUT_DIRNAME': '${dirname}', 'RULE_INPUT_PATH': '${source}', 'RULE_INPUT_EXT': '${ext}', 'RULE_INPUT_NAME': '${name}', } # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() def StripPrefix(arg, prefix): if arg.startswith(prefix): return arg[len(prefix):] return arg def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # whitelist common OK ones and quote anything else. if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg): return arg # No quoting necessary. if flavor == 'win': return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'" def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == 'win': # cl.exe replaces literal # characters with = in preprocesor definitions for # some reason. Octal-encode to work around that. d = d.replace('#', '\\%03o' % ord('#')) return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor) def AddArch(output, arch): """Adds an arch string to an output path.""" output, extension = os.path.splitext(output) return '%s.%s%s' % (output, arch, extension) class Target(object): """Target represents the paths used within a single gyp target. Conceptually, building a single target A is a series of steps: 1) actions/rules/copies generates source/resources/etc. 2) compiles generates .o files 3) link generates a binary (library/executable) 4) bundle merges the above in a mac bundle (Any of these steps can be optional.) From a build ordering perspective, a dependent target B could just depend on the last output of this series of steps. But some dependent commands sometimes need to reach inside the box. For example, when linking B it needs to get the path to the static library generated by A. This object stores those paths. To keep things simple, member variables only store concrete paths to single files, while methods compute derived values like "the last output of the target". """ def __init__(self, type): # Gyp type ("static_library", etc.) of this target. self.type = type # File representing whether any input dependencies necessary for # dependent actions have completed. self.preaction_stamp = None # File representing whether any input dependencies necessary for # dependent compiles have completed. self.precompile_stamp = None # File representing the completion of actions/rules/copies, if any. self.actions_stamp = None # Path to the output of the link step, if any. self.binary = None # Path to the file representing the completion of building the bundle, # if any. self.bundle = None # On Windows, incremental linking requires linking against all the .objs # that compose a .lib (rather than the .lib itself). That list is stored # here. In this case, we also need to save the compile_deps for the target, # so that the the target that directly depends on the .objs can also depend # on those. self.component_objs = None self.compile_deps = None # Windows only. The import .lib is the output of a build step, but # because dependents only link against the lib (not both the lib and the # dll) we keep track of the import library here. self.import_lib = None def Linkable(self): """Return true if this is a target that can be linked against.""" return self.type in ('static_library', 'shared_library') def UsesToc(self, flavor): """Return true if the target should produce a restat rule based on a TOC file.""" # For bundles, the .TOC should be produced for the binary, not for # FinalOutput(). But the naive approach would put the TOC file into the # bundle, so don't do this for bundles for now. if flavor == 'win' or self.bundle: return False return self.type in ('shared_library', 'loadable_module') def PreActionInput(self, flavor): """Return the path, if any, that should be used as a dependency of any dependent action step.""" if self.UsesToc(flavor): return self.FinalOutput() + '.TOC' return self.FinalOutput() or self.preaction_stamp def PreCompileInput(self): """Return the path, if any, that should be used as a dependency of any dependent compile step.""" return self.actions_stamp or self.precompile_stamp def FinalOutput(self): """Return the last output of the target, which depends on all prior steps.""" return self.bundle or self.binary or self.actions_stamp # A small discourse on paths as used within the Ninja build: # All files we produce (both at gyp and at build time) appear in the # build directory (e.g. out/Debug). # # Paths within a given .gyp file are always relative to the directory # containing the .gyp file. Call these "gyp paths". This includes # sources as well as the starting directory a given gyp rule/action # expects to be run from. We call the path from the source root to # the gyp file the "base directory" within the per-.gyp-file # NinjaWriter code. # # All paths as written into the .ninja files are relative to the build # directory. Call these paths "ninja paths". # # We translate between these two notions of paths with two helper # functions: # # - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file) # into the equivalent ninja path. # # - GypPathToUniqueOutput translates a gyp path into a ninja path to write # an output file; the result can be namespaced such that it is unique # to the input file name as well as the output target name. class NinjaWriter(object): def __init__(self, hash_for_rules, target_outputs, base_dir, build_dir, output_file, toplevel_build, output_file_name, flavor, toplevel_dir=None): """ base_dir: path from source root to directory containing this gyp file, by gyp semantics, all input paths are relative to this build_dir: path from source root to build output toplevel_dir: path to the toplevel directory """ self.hash_for_rules = hash_for_rules self.target_outputs = target_outputs self.base_dir = base_dir self.build_dir = build_dir self.ninja = ninja_syntax.Writer(output_file) self.toplevel_build = toplevel_build self.output_file_name = output_file_name self.flavor = flavor self.abs_build_dir = None if toplevel_dir is not None: self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir)) self.obj_ext = '.obj' if flavor == 'win' else '.o' if flavor == 'win': # See docstring of msvs_emulation.GenerateEnvironmentFiles(). self.win_env = {} for arch in ('x86', 'x64'): self.win_env[arch] = 'environment.' + arch # Relative path from build output dir to base dir. build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir) self.build_to_base = os.path.join(build_to_top, base_dir) # Relative path from base dir to build dir. base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir) self.base_to_build = os.path.join(base_to_top, build_dir) def ExpandSpecial(self, path, product_dir=None): """Expand specials like $!PRODUCT_DIR in |path|. If |product_dir| is None, assumes the cwd is already the product dir. Otherwise, |product_dir| is the relative path to the product dir. """ PRODUCT_DIR = '$!PRODUCT_DIR' if PRODUCT_DIR in path: if product_dir: path = path.replace(PRODUCT_DIR, product_dir) else: path = path.replace(PRODUCT_DIR + '/', '') path = path.replace(PRODUCT_DIR + '\\', '') path = path.replace(PRODUCT_DIR, '.') INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR' if INTERMEDIATE_DIR in path: int_dir = self.GypPathToUniqueOutput('gen') # GypPathToUniqueOutput generates a path relative to the product dir, # so insert product_dir in front if it is provided. path = path.replace(INTERMEDIATE_DIR, os.path.join(product_dir or '', int_dir)) CONFIGURATION_NAME = '$|CONFIGURATION_NAME' path = path.replace(CONFIGURATION_NAME, self.config_name) return path def ExpandRuleVariables(self, path, root, dirname, source, ext, name): if self.flavor == 'win': path = self.msvs_settings.ConvertVSMacros( path, config=self.config_name) path = path.replace(generator_default_variables['RULE_INPUT_ROOT'], root) path = path.replace(generator_default_variables['RULE_INPUT_DIRNAME'], dirname) path = path.replace(generator_default_variables['RULE_INPUT_PATH'], source) path = path.replace(generator_default_variables['RULE_INPUT_EXT'], ext) path = path.replace(generator_default_variables['RULE_INPUT_NAME'], name) return path def GypPathToNinja(self, path, env=None): """Translate a gyp path to a ninja path, optionally expanding environment variable references in |path| with |env|. See the above discourse on path conversions.""" if env: if self.flavor == 'mac': path = gyp.xcode_emulation.ExpandEnvVars(path, env) elif self.flavor == 'win': path = gyp.msvs_emulation.ExpandMacros(path, env) if path.startswith('$!'): expanded = self.ExpandSpecial(path) if self.flavor == 'win': expanded = os.path.normpath(expanded) return expanded if '$|' in path: path = self.ExpandSpecial(path) assert '$' not in path, path return os.path.normpath(os.path.join(self.build_to_base, path)) def GypPathToUniqueOutput(self, path, qualified=True): """Translate a gyp path to a ninja path for writing output. If qualified is True, qualify the resulting filename with the name of the target. This is necessary when e.g. compiling the same path twice for two separate output targets. See the above discourse on path conversions.""" path = self.ExpandSpecial(path) assert not path.startswith('$'), path # Translate the path following this scheme: # Input: foo/bar.gyp, target targ, references baz/out.o # Output: obj/foo/baz/targ.out.o (if qualified) # obj/foo/baz/out.o (otherwise) # (and obj.host instead of obj for cross-compiles) # # Why this scheme and not some other one? # 1) for a given input, you can compute all derived outputs by matching # its path, even if the input is brought via a gyp file with '..'. # 2) simple files like libraries and stamps have a simple filename. obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset path_dir, path_basename = os.path.split(path) assert not os.path.isabs(path_dir), ( "'%s' can not be absolute path (see crbug.com/462153)." % path_dir) if qualified: path_basename = self.name + '.' + path_basename return os.path.normpath(os.path.join(obj, self.base_dir, path_dir, path_basename)) def WriteCollapsedDependencies(self, name, targets, order_only=None): """Given a list of targets, return a path for a single file representing the result of building all the targets or None. Uses a stamp file if necessary.""" assert targets == filter(None, targets), targets if len(targets) == 0: assert not order_only return None if len(targets) > 1 or order_only: stamp = self.GypPathToUniqueOutput(name + '.stamp') targets = self.ninja.build(stamp, 'stamp', targets, order_only=order_only) self.ninja.newline() return targets[0] def _SubninjaNameForArch(self, arch): output_file_base = os.path.splitext(self.output_file_name)[0] return '%s.%s.ninja' % (output_file_base, arch) def WriteSpec(self, spec, config_name, generator_flags): """The main entry point for NinjaWriter: write the build rules for a spec. Returns a Target object, which represents the output paths for this spec. Returns None if there are no outputs (e.g. a settings-only 'none' type target).""" self.config_name = config_name self.name = spec['target_name'] self.toolset = spec['toolset'] config = spec['configurations'][config_name] self.target = Target(spec['type']) self.is_standalone_static_library = bool( spec.get('standalone_static_library', 0)) # Track if this target contains any C++ files, to decide if gcc or g++ # should be used for linking. self.uses_cpp = False self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) self.xcode_settings = self.msvs_settings = None if self.flavor == 'mac': self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) if self.flavor == 'win': self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, generator_flags) arch = self.msvs_settings.GetArch(config_name) self.ninja.variable('arch', self.win_env[arch]) self.ninja.variable('cc', '$cl_' + arch) self.ninja.variable('cxx', '$cl_' + arch) self.ninja.variable('cc_host', '$cl_' + arch) self.ninja.variable('cxx_host', '$cl_' + arch) self.ninja.variable('asm', '$ml_' + arch) if self.flavor == 'mac': self.archs = self.xcode_settings.GetActiveArchs(config_name) if len(self.archs) > 1: self.arch_subninjas = dict( (arch, ninja_syntax.Writer( OpenOutput(os.path.join(self.toplevel_build, self._SubninjaNameForArch(arch)), 'w'))) for arch in self.archs) # Compute predepends for all rules. # actions_depends is the dependencies this target depends on before running # any of its action/rule/copy steps. # compile_depends is the dependencies this target depends on before running # any of its compile steps. actions_depends = [] compile_depends = [] # TODO(evan): it is rather confusing which things are lists and which # are strings. Fix these. if 'dependencies' in spec: for dep in spec['dependencies']: if dep in self.target_outputs: target = self.target_outputs[dep] actions_depends.append(target.PreActionInput(self.flavor)) compile_depends.append(target.PreCompileInput()) actions_depends = filter(None, actions_depends) compile_depends = filter(None, compile_depends) actions_depends = self.WriteCollapsedDependencies('actions_depends', actions_depends) compile_depends = self.WriteCollapsedDependencies('compile_depends', compile_depends) self.target.preaction_stamp = actions_depends self.target.precompile_stamp = compile_depends # Write out actions, rules, and copies. These must happen before we # compile any sources, so compute a list of predependencies for sources # while we do it. extra_sources = [] mac_bundle_depends = [] self.target.actions_stamp = self.WriteActionsRulesCopies( spec, extra_sources, actions_depends, mac_bundle_depends) # If we have actions/rules/copies, we depend directly on those, but # otherwise we depend on dependent target's actions/rules/copies etc. # We never need to explicitly depend on previous target's link steps, # because no compile ever depends on them. compile_depends_stamp = (self.target.actions_stamp or compile_depends) # Write out the compilation steps, if any. link_deps = [] sources = extra_sources + spec.get('sources', []) if sources: if self.flavor == 'mac' and len(self.archs) > 1: # Write subninja file containing compile and link commands scoped to # a single arch if a fat binary is being built. for arch in self.archs: self.ninja.subninja(self._SubninjaNameForArch(arch)) pch = None if self.flavor == 'win': gyp.msvs_emulation.VerifyMissingSources( sources, self.abs_build_dir, generator_flags, self.GypPathToNinja) pch = gyp.msvs_emulation.PrecompiledHeader( self.msvs_settings, config_name, self.GypPathToNinja, self.GypPathToUniqueOutput, self.obj_ext) else: pch = gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, self.GypPathToNinja, lambda path, lang: self.GypPathToUniqueOutput(path + '-' + lang)) link_deps = self.WriteSources( self.ninja, config_name, config, sources, compile_depends_stamp, pch, spec) # Some actions/rules output 'sources' that are already object files. obj_outputs = [f for f in sources if f.endswith(self.obj_ext)] if obj_outputs: if self.flavor != 'mac' or len(self.archs) == 1: link_deps += [self.GypPathToNinja(o) for o in obj_outputs] else: print "Warning: Actions/rules writing object files don't work with " \ "multiarch targets, dropping. (target %s)" % spec['target_name'] elif self.flavor == 'mac' and len(self.archs) > 1: link_deps = collections.defaultdict(list) compile_deps = self.target.actions_stamp or actions_depends if self.flavor == 'win' and self.target.type == 'static_library': self.target.component_objs = link_deps self.target.compile_deps = compile_deps # Write out a link step, if needed. output = None is_empty_bundle = not link_deps and not mac_bundle_depends if link_deps or self.target.actions_stamp or actions_depends: output = self.WriteTarget(spec, config_name, config, link_deps, compile_deps) if self.is_mac_bundle: mac_bundle_depends.append(output) # Bundle all of the above together, if needed. if self.is_mac_bundle: output = self.WriteMacBundle(spec, mac_bundle_depends, is_empty_bundle) if not output: return None assert self.target.FinalOutput(), output return self.target def _WinIdlRule(self, source, prebuild, outputs): """Handle the implicit VS .idl rule for one source file. Fills |outputs| with files that are generated.""" outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData( source, self.config_name) outdir = self.GypPathToNinja(outdir) def fix_path(path, rel=None): path = os.path.join(outdir, path) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) path = self.ExpandRuleVariables( path, root, dirname, source, ext, basename) if rel: path = os.path.relpath(path, rel) return path vars = [(name, fix_path(value, outdir)) for name, value in vars] output = [fix_path(p) for p in output] vars.append(('outdir', outdir)) vars.append(('idlflags', flags)) input = self.GypPathToNinja(source) self.ninja.build(output, 'idl', input, variables=vars, order_only=prebuild) outputs.extend(output) def WriteWinIdlFiles(self, spec, prebuild): """Writes rules to match MSVS's implicit idl handling.""" assert self.flavor == 'win' if self.msvs_settings.HasExplicitIdlRulesOrActions(spec): return [] outputs = [] for source in filter(lambda x: x.endswith('.idl'), spec['sources']): self._WinIdlRule(source, prebuild, outputs) return outputs def WriteActionsRulesCopies(self, spec, extra_sources, prebuild, mac_bundle_depends): """Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.""" outputs = [] if self.is_mac_bundle: mac_bundle_resources = spec.get('mac_bundle_resources', [])[:] else: mac_bundle_resources = [] extra_mac_bundle_resources = [] if 'actions' in spec: outputs += self.WriteActions(spec['actions'], extra_sources, prebuild, extra_mac_bundle_resources) if 'rules' in spec: outputs += self.WriteRules(spec['rules'], extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources) if 'copies' in spec: outputs += self.WriteCopies(spec['copies'], prebuild, mac_bundle_depends) if 'sources' in spec and self.flavor == 'win': outputs += self.WriteWinIdlFiles(spec, prebuild) stamp = self.WriteCollapsedDependencies('actions_rules_copies', outputs) if self.is_mac_bundle: xcassets = self.WriteMacBundleResources( extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends) partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends) self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends) return stamp def GenerateDescription(self, verb, message, fallback): """Generate and return a description of a build step. |verb| is the short summary, e.g. ACTION or RULE. |message| is a hand-written description, or None if not available. |fallback| is the gyp-level name of the step, usable as a fallback. """ if self.toolset != 'target': verb += '(%s)' % self.toolset if message: return '%s %s' % (verb, self.ExpandSpecial(message)) else: return '%s %s: %s' % (verb, self.name, fallback) def WriteActions(self, actions, extra_sources, prebuild, extra_mac_bundle_resources): # Actions cd into the base directory. env = self.GetToolchainEnv() all_outputs = [] for action in actions: # First write out a rule for the action. name = '%s_%s' % (action['action_name'], self.hash_for_rules) description = self.GenerateDescription('ACTION', action.get('message', None), name) is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(action) if self.flavor == 'win' else False) args = action['action'] depfile = action.get('depfile', None) if depfile: depfile = self.ExpandSpecial(depfile, self.base_to_build) pool = 'console' if int(action.get('ninja_use_console', 0)) else None rule_name, _ = self.WriteNewNinjaRule(name, args, description, is_cygwin, env, pool, depfile=depfile) inputs = [self.GypPathToNinja(i, env) for i in action['inputs']] if int(action.get('process_outputs_as_sources', False)): extra_sources += action['outputs'] if int(action.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += action['outputs'] outputs = [self.GypPathToNinja(o, env) for o in action['outputs']] # Then write out an edge using the rule. self.ninja.build(outputs, rule_name, inputs, order_only=prebuild) all_outputs += outputs self.ninja.newline() return all_outputs def WriteRules(self, rules, extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources): env = self.GetToolchainEnv() all_outputs = [] for rule in rules: # Skip a rule with no action and no inputs. if 'action' not in rule and not rule.get('rule_sources', []): continue # First write out a rule for the rule action. name = '%s_%s' % (rule['rule_name'], self.hash_for_rules) args = rule['action'] description = self.GenerateDescription( 'RULE', rule.get('message', None), ('%s ' + generator_default_variables['RULE_INPUT_PATH']) % name) is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(rule) if self.flavor == 'win' else False) pool = 'console' if int(rule.get('ninja_use_console', 0)) else None rule_name, args = self.WriteNewNinjaRule( name, args, description, is_cygwin, env, pool) # TODO: if the command references the outputs directly, we should # simplify it to just use $out. # Rules can potentially make use of some special variables which # must vary per source file. # Compute the list of variables we'll need to provide. special_locals = ('source', 'root', 'dirname', 'ext', 'name') needed_variables = set(['source']) for argument in args: for var in special_locals: if '${%s}' % var in argument: needed_variables.add(var) def cygwin_munge(path): # pylint: disable=cell-var-from-loop if is_cygwin: return path.replace('\\', '/') return path inputs = [self.GypPathToNinja(i, env) for i in rule.get('inputs', [])] # If there are n source files matching the rule, and m additional rule # inputs, then adding 'inputs' to each build edge written below will # write m * n inputs. Collapsing reduces this to m + n. sources = rule.get('rule_sources', []) num_inputs = len(inputs) if prebuild: num_inputs += 1 if num_inputs > 2 and len(sources) > 2: inputs = [self.WriteCollapsedDependencies( rule['rule_name'], inputs, order_only=prebuild)] prebuild = [] # For each source file, write an edge that generates all the outputs. for source in sources: source = os.path.normpath(source) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) # Gather the list of inputs and outputs, expanding $vars if possible. outputs = [self.ExpandRuleVariables(o, root, dirname, source, ext, basename) for o in rule['outputs']] if int(rule.get('process_outputs_as_sources', False)): extra_sources += outputs was_mac_bundle_resource = source in mac_bundle_resources if was_mac_bundle_resource or \ int(rule.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs # Note: This is n_resources * n_outputs_in_rule. Put to-be-removed # items in a set and remove them all in a single pass if this becomes # a performance issue. if was_mac_bundle_resource: mac_bundle_resources.remove(source) extra_bindings = [] for var in needed_variables: if var == 'root': extra_bindings.append(('root', cygwin_munge(root))) elif var == 'dirname': # '$dirname' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. dirname_expanded = self.ExpandSpecial(dirname, self.base_to_build) extra_bindings.append(('dirname', cygwin_munge(dirname_expanded))) elif var == 'source': # '$source' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. source_expanded = self.ExpandSpecial(source, self.base_to_build) extra_bindings.append(('source', cygwin_munge(source_expanded))) elif var == 'ext': extra_bindings.append(('ext', ext)) elif var == 'name': extra_bindings.append(('name', cygwin_munge(basename))) else: assert var == None, repr(var) outputs = [self.GypPathToNinja(o, env) for o in outputs] if self.flavor == 'win': # WriteNewNinjaRule uses unique_name for creating an rsp file on win. extra_bindings.append(('unique_name', hashlib.md5(outputs[0]).hexdigest())) self.ninja.build(outputs, rule_name, self.GypPathToNinja(source), implicit=inputs, order_only=prebuild, variables=extra_bindings) all_outputs.extend(outputs) return all_outputs def WriteCopies(self, copies, prebuild, mac_bundle_depends): outputs = [] env = self.GetToolchainEnv() for copy in copies: for path in copy['files']: # Normalize the path so trailing slashes don't confuse us. path = os.path.normpath(path) basename = os.path.split(path)[1] src = self.GypPathToNinja(path, env) dst = self.GypPathToNinja(os.path.join(copy['destination'], basename), env) outputs += self.ninja.build(dst, 'copy', src, order_only=prebuild) if self.is_mac_bundle: # gyp has mac_bundle_resources to copy things into a bundle's # Resources folder, but there's no built-in way to copy files to other # places in the bundle. Hence, some targets use copies for this. Check # if this file is copied into the current bundle, and if so add it to # the bundle depends so that dependent targets get rebuilt if the copy # input changes. if dst.startswith(self.xcode_settings.GetBundleContentsFolderPath()): mac_bundle_depends.append(dst) return outputs def WriteMacBundleResources(self, resources, bundle_depends): """Writes ninja edges for 'mac_bundle_resources'.""" xcassets = [] for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, map(self.GypPathToNinja, resources)): output = self.ExpandSpecial(output) if os.path.splitext(output)[-1] != '.xcassets': isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build(output, 'mac_tool', res, variables=[('mactool_cmd', 'copy-bundle-resource'), \ ('binary', isBinary)]) bundle_depends.append(output) else: xcassets.append(res) return xcassets def WriteMacXCassets(self, xcassets, bundle_depends): """Writes ninja edges for 'mac_bundle_resources' .xcassets files. This add an invocation of 'actool' via the 'mac_tool.py' helper script. It assumes that the assets catalogs define at least one imageset and thus an Assets.car file will be generated in the application resources directory. If this is not the case, then the build will probably be done at each invocation of ninja.""" if not xcassets: return extra_arguments = {} settings_to_arg = { 'XCASSETS_APP_ICON': 'app-icon', 'XCASSETS_LAUNCH_IMAGE': 'launch-image', } settings = self.xcode_settings.xcode_settings[self.config_name] for settings_key, arg_name in settings_to_arg.iteritems(): value = settings.get(settings_key) if value: extra_arguments[arg_name] = value partial_info_plist = None if extra_arguments: partial_info_plist = self.GypPathToUniqueOutput( 'assetcatalog_generated_info.plist') extra_arguments['output-partial-info-plist'] = partial_info_plist outputs = [] outputs.append( os.path.join( self.xcode_settings.GetBundleResourceFolder(), 'Assets.car')) if partial_info_plist: outputs.append(partial_info_plist) keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor) extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) bundle_depends.extend(self.ninja.build( outputs, 'compile_xcassets', xcassets, variables=[('env', env), ('keys', keys)])) return partial_info_plist def WriteMacInfoPlist(self, partial_info_plist, bundle_depends): """Write build rules for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, self.GypPathToNinja) if not info_plist: return out = self.ExpandSpecial(out) if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = self.GypPathToUniqueOutput( os.path.basename(info_plist)) defines = ' '.join([Define(d, self.flavor) for d in defines]) info_plist = self.ninja.build( intermediate_plist, 'preprocess_infoplist', info_plist, variables=[('defines',defines)]) env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) if partial_info_plist: intermediate_plist = self.GypPathToUniqueOutput('merged_info.plist') info_plist = self.ninja.build( intermediate_plist, 'merge_infoplist', [partial_info_plist, info_plist]) keys = self.xcode_settings.GetExtraPlistItems(self.config_name) keys = QuoteShellArgument(json.dumps(keys), self.flavor) isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build(out, 'copy_infoplist', info_plist, variables=[('env', env), ('keys', keys), ('binary', isBinary)]) bundle_depends.append(out) def WriteSources(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec): """Write build rules to compile all of |sources|.""" if self.toolset == 'host': self.ninja.variable('ar', '$ar_host') self.ninja.variable('cc', '$cc_host') self.ninja.variable('cxx', '$cxx_host') self.ninja.variable('ld', '$ld_host') self.ninja.variable('ldxx', '$ldxx_host') self.ninja.variable('nm', '$nm_host') self.ninja.variable('readelf', '$readelf_host') if self.flavor != 'mac' or len(self.archs) == 1: return self.WriteSourcesForArch( self.ninja, config_name, config, sources, predepends, precompiled_header, spec) else: return dict((arch, self.WriteSourcesForArch( self.arch_subninjas[arch], config_name, config, sources, predepends, precompiled_header, spec, arch=arch)) for arch in self.archs) def WriteSourcesForArch(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, arch=None): """Write build rules to compile all of |sources|.""" extra_defines = [] if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(config_name, arch=arch) cflags_c = self.xcode_settings.GetCflagsC(config_name) cflags_cc = self.xcode_settings.GetCflagsCC(config_name) cflags_objc = ['$cflags_c'] + \ self.xcode_settings.GetCflagsObjC(config_name) cflags_objcc = ['$cflags_cc'] + \ self.xcode_settings.GetCflagsObjCC(config_name) elif self.flavor == 'win': asmflags = self.msvs_settings.GetAsmflags(config_name) cflags = self.msvs_settings.GetCflags(config_name) cflags_c = self.msvs_settings.GetCflagsC(config_name) cflags_cc = self.msvs_settings.GetCflagsCC(config_name) extra_defines = self.msvs_settings.GetComputedDefines(config_name) # See comment at cc_command for why there's two .pdb files. pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName( config_name, self.ExpandSpecial) if not pdbpath_c: obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name)) pdbpath_c = pdbpath + '.c.pdb' pdbpath_cc = pdbpath + '.cc.pdb' self.WriteVariableList(ninja_file, 'pdbname_c', [pdbpath_c]) self.WriteVariableList(ninja_file, 'pdbname_cc', [pdbpath_cc]) self.WriteVariableList(ninja_file, 'pchprefix', [self.name]) else: cflags = config.get('cflags', []) cflags_c = config.get('cflags_c', []) cflags_cc = config.get('cflags_cc', []) # Respect environment variables related to build, but target-specific # flags can still override them. if self.toolset == 'target': cflags_c = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CFLAGS', '').split() + cflags_c) cflags_cc = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CXXFLAGS', '').split() + cflags_cc) elif self.toolset == 'host': cflags_c = (os.environ.get('CPPFLAGS_host', '').split() + os.environ.get('CFLAGS_host', '').split() + cflags_c) cflags_cc = (os.environ.get('CPPFLAGS_host', '').split() + os.environ.get('CXXFLAGS_host', '').split() + cflags_cc) defines = config.get('defines', []) + extra_defines self.WriteVariableList(ninja_file, 'defines', [Define(d, self.flavor) for d in defines]) if self.flavor == 'win': self.WriteVariableList(ninja_file, 'asmflags', map(self.ExpandSpecial, asmflags)) self.WriteVariableList(ninja_file, 'rcflags', [QuoteShellArgument(self.ExpandSpecial(f), self.flavor) for f in self.msvs_settings.GetRcflags(config_name, self.GypPathToNinja)]) include_dirs = config.get('include_dirs', []) env = self.GetToolchainEnv() if self.flavor == 'win': include_dirs = self.msvs_settings.AdjustIncludeDirs(include_dirs, config_name) self.WriteVariableList(ninja_file, 'includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in include_dirs]) if self.flavor == 'win': midl_include_dirs = config.get('midl_include_dirs', []) midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs( midl_include_dirs, config_name) self.WriteVariableList(ninja_file, 'midl_includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in midl_include_dirs]) pch_commands = precompiled_header.GetPchBuildCommands(arch) if self.flavor == 'mac': # Most targets use no precompiled headers, so only write these if needed. for ext, var in [('c', 'cflags_pch_c'), ('cc', 'cflags_pch_cc'), ('m', 'cflags_pch_objc'), ('mm', 'cflags_pch_objcc')]: include = precompiled_header.GetInclude(ext, arch) if include: ninja_file.variable(var, include) arflags = config.get('arflags', []) self.WriteVariableList(ninja_file, 'cflags', map(self.ExpandSpecial, cflags)) self.WriteVariableList(ninja_file, 'cflags_c', map(self.ExpandSpecial, cflags_c)) self.WriteVariableList(ninja_file, 'cflags_cc', map(self.ExpandSpecial, cflags_cc)) if self.flavor == 'mac': self.WriteVariableList(ninja_file, 'cflags_objc', map(self.ExpandSpecial, cflags_objc)) self.WriteVariableList(ninja_file, 'cflags_objcc', map(self.ExpandSpecial, cflags_objcc)) self.WriteVariableList(ninja_file, 'arflags', map(self.ExpandSpecial, arflags)) ninja_file.newline() outputs = [] has_rc_source = False for source in sources: filename, ext = os.path.splitext(source) ext = ext[1:] obj_ext = self.obj_ext if ext in ('cc', 'cpp', 'cxx'): command = 'cxx' self.uses_cpp = True elif ext == 'c' or (ext == 'S' and self.flavor != 'win'): command = 'cc' elif ext == 's' and self.flavor != 'win': # Doesn't generate .o.d files. command = 'cc_s' elif (self.flavor == 'win' and ext == 'asm' and not self.msvs_settings.HasExplicitAsmRules(spec)): command = 'asm' # Add the _asm suffix as msvs is capable of handling .cc and # .asm files of the same name without collision. obj_ext = '_asm.obj' elif self.flavor == 'mac' and ext == 'm': command = 'objc' elif self.flavor == 'mac' and ext == 'mm': command = 'objcxx' self.uses_cpp = True elif self.flavor == 'win' and ext == 'rc': command = 'rc' obj_ext = '.res' has_rc_source = True else: # Ignore unhandled extensions. continue input = self.GypPathToNinja(source) output = self.GypPathToUniqueOutput(filename + obj_ext) if arch is not None: output = AddArch(output, arch) implicit = precompiled_header.GetObjDependencies([input], [output], arch) variables = [] if self.flavor == 'win': variables, output, implicit = precompiled_header.GetFlagsModifications( input, output, implicit, command, cflags_c, cflags_cc, self.ExpandSpecial) ninja_file.build(output, command, input, implicit=[gch for _, _, gch in implicit], order_only=predepends, variables=variables) outputs.append(output) if has_rc_source: resource_include_dirs = config.get('resource_include_dirs', include_dirs) self.WriteVariableList(ninja_file, 'resource_includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in resource_include_dirs]) self.WritePchTargets(ninja_file, pch_commands) ninja_file.newline() return outputs def WritePchTargets(self, ninja_file, pch_commands): """Writes ninja rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: var_name = { 'c': 'cflags_pch_c', 'cc': 'cflags_pch_cc', 'm': 'cflags_pch_objc', 'mm': 'cflags_pch_objcc', }[lang] map = { 'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx', } cmd = map.get(lang) ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)]) def WriteLink(self, spec, config_name, config, link_deps): """Write out a link step. Fills out target.binary. """ if self.flavor != 'mac' or len(self.archs) == 1: return self.WriteLinkForArch( self.ninja, spec, config_name, config, link_deps) else: output = self.ComputeOutput(spec) inputs = [self.WriteLinkForArch(self.arch_subninjas[arch], spec, config_name, config, link_deps[arch], arch=arch) for arch in self.archs] extra_bindings = [] build_output = output if not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) # TODO(yyanagisawa): more work needed to fix: # https://code.google.com/p/gyp/issues/detail?id=411 if (spec['type'] in ('shared_library', 'loadable_module') and not self.is_mac_bundle): extra_bindings.append(('lib', output)) self.ninja.build([output, output + '.TOC'], 'solipo', inputs, variables=extra_bindings) else: self.ninja.build(build_output, 'lipo', inputs, variables=extra_bindings) return output def WriteLinkForArch(self, ninja_file, spec, config_name, config, link_deps, arch=None): """Write out a link step. Fills out target.binary. """ command = { 'executable': 'link', 'loadable_module': 'solink_module', 'shared_library': 'solink', }[spec['type']] command_suffix = '' implicit_deps = set() solibs = set() order_deps = set() if 'dependencies' in spec: # Two kinds of dependencies: # - Linkable dependencies (like a .a or a .so): add them to the link line. # - Non-linkable dependencies (like a rule that generates a file # and writes a stamp file): add them to implicit_deps extra_link_deps = set() for dep in spec['dependencies']: target = self.target_outputs.get(dep) if not target: continue linkable = target.Linkable() if linkable: new_deps = [] if (self.flavor == 'win' and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name)): new_deps = target.component_objs if target.compile_deps: order_deps.add(target.compile_deps) elif self.flavor == 'win' and target.import_lib: new_deps = [target.import_lib] elif target.UsesToc(self.flavor): solibs.add(target.binary) implicit_deps.add(target.binary + '.TOC') else: new_deps = [target.binary] for new_dep in new_deps: if new_dep not in extra_link_deps: extra_link_deps.add(new_dep) link_deps.append(new_dep) final_output = target.FinalOutput() if not linkable or final_output != target.binary: implicit_deps.add(final_output) extra_bindings = [] if self.uses_cpp and self.flavor != 'win': extra_bindings.append(('ld', '$ldxx')) output = self.ComputeOutput(spec, arch) if arch is None and not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) is_executable = spec['type'] == 'executable' # The ldflags config key is not used on mac or win. On those platforms # linker flags are set via xcode_settings and msvs_settings, respectively. env_ldflags = os.environ.get('LDFLAGS', '').split() if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(config_name, self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self.GypPathToNinja, arch) ldflags = env_ldflags + ldflags elif self.flavor == 'win': manifest_base_name = self.GypPathToUniqueOutput( self.ComputeOutputFileName(spec)) ldflags, intermediate_manifest, manifest_files = \ self.msvs_settings.GetLdflags(config_name, self.GypPathToNinja, self.ExpandSpecial, manifest_base_name, output, is_executable, self.toplevel_build) ldflags = env_ldflags + ldflags self.WriteVariableList(ninja_file, 'manifests', manifest_files) implicit_deps = implicit_deps.union(manifest_files) if intermediate_manifest: self.WriteVariableList( ninja_file, 'intermediatemanifest', [intermediate_manifest]) command_suffix = _GetWinLinkRuleNameSuffix( self.msvs_settings.IsEmbedManifest(config_name)) def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja) if def_file: implicit_deps.add(def_file) else: # Respect environment variables related to build, but target-specific # flags can still override them. ldflags = env_ldflags + config.get('ldflags', []) if is_executable and len(solibs): rpath = 'lib/' if self.toolset != 'target': rpath += self.toolset ldflags.append(r'-Wl,-rpath=\$$ORIGIN/%s' % rpath) ldflags.append('-Wl,-rpath-link=%s' % rpath) self.WriteVariableList(ninja_file, 'ldflags', map(self.ExpandSpecial, ldflags)) library_dirs = config.get('library_dirs', []) if self.flavor == 'win': library_dirs = [self.msvs_settings.ConvertVSMacros(l, config_name) for l in library_dirs] library_dirs = ['/LIBPATH:' + QuoteShellArgument(self.GypPathToNinja(l), self.flavor) for l in library_dirs] else: library_dirs = [QuoteShellArgument('-L' + self.GypPathToNinja(l), self.flavor) for l in library_dirs] libraries = gyp.common.uniquer(map(self.ExpandSpecial, spec.get('libraries', []))) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries, config_name) elif self.flavor == 'win': libraries = self.msvs_settings.AdjustLibraries(libraries) self.WriteVariableList(ninja_file, 'libs', library_dirs + libraries) linked_binary = output if command in ('solink', 'solink_module'): extra_bindings.append(('soname', os.path.split(output)[1])) extra_bindings.append(('lib', gyp.common.EncodePOSIXShellArgument(output))) if self.flavor != 'win': link_file_list = output if self.is_mac_bundle: # 'Dependency Framework.framework/Versions/A/Dependency Framework' -> # 'Dependency Framework.framework.rsp' link_file_list = self.xcode_settings.GetWrapperName() if arch: link_file_list += '.' + arch link_file_list += '.rsp' # If an rspfile contains spaces, ninja surrounds the filename with # quotes around it and then passes it to open(), creating a file with # quotes in its name (and when looking for the rsp file, the name # makes it through bash which strips the quotes) :-/ link_file_list = link_file_list.replace(' ', '_') extra_bindings.append( ('link_file_list', gyp.common.EncodePOSIXShellArgument(link_file_list))) if self.flavor == 'win': extra_bindings.append(('binary', output)) if ('/NOENTRY' not in ldflags and not self.msvs_settings.GetNoImportLibrary(config_name)): self.target.import_lib = output + '.lib' extra_bindings.append(('implibflag', '/IMPLIB:%s' % self.target.import_lib)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') output = [output, self.target.import_lib] if pdbname: output.append(pdbname) elif not self.is_mac_bundle: output = [output, output + '.TOC'] else: command = command + '_notoc' elif self.flavor == 'win': extra_bindings.append(('binary', output)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') if pdbname: output = [output, pdbname] if len(solibs): extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(solibs))) ninja_file.build(output, command + command_suffix, link_deps, implicit=list(implicit_deps), order_only=list(order_deps), variables=extra_bindings) return linked_binary def WriteTarget(self, spec, config_name, config, link_deps, compile_deps): extra_link_deps = any(self.target_outputs.get(dep).Linkable() for dep in spec.get('dependencies', []) if dep in self.target_outputs) if spec['type'] == 'none' or (not link_deps and not extra_link_deps): # TODO(evan): don't call this function for 'none' target types, as # it doesn't do anything, and we fake out a 'binary' with a stamp file. self.target.binary = compile_deps self.target.type = 'none' elif spec['type'] == 'static_library': self.target.binary = self.ComputeOutput(spec) if (self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not self.is_standalone_static_library): self.ninja.build(self.target.binary, 'alink_thin', link_deps, order_only=compile_deps) else: variables = [] if self.xcode_settings: libtool_flags = self.xcode_settings.GetLibtoolflags(config_name) if libtool_flags: variables.append(('libtool_flags', libtool_flags)) if self.msvs_settings: libflags = self.msvs_settings.GetLibFlags(config_name, self.GypPathToNinja) variables.append(('libflags', libflags)) if self.flavor != 'mac' or len(self.archs) == 1: self.AppendPostbuildVariable(variables, spec, self.target.binary, self.target.binary) self.ninja.build(self.target.binary, 'alink', link_deps, order_only=compile_deps, variables=variables) else: inputs = [] for arch in self.archs: output = self.ComputeOutput(spec, arch) self.arch_subninjas[arch].build(output, 'alink', link_deps[arch], order_only=compile_deps, variables=variables) inputs.append(output) # TODO: It's not clear if libtool_flags should be passed to the alink # call that combines single-arch .a files into a fat .a file. self.AppendPostbuildVariable(variables, spec, self.target.binary, self.target.binary) self.ninja.build(self.target.binary, 'alink', inputs, # FIXME: test proving order_only=compile_deps isn't # needed. variables=variables) else: self.target.binary = self.WriteLink(spec, config_name, config, link_deps) return self.target.binary def WriteMacBundle(self, spec, mac_bundle_depends, is_empty): assert self.is_mac_bundle package_framework = spec['type'] in ('shared_library', 'loadable_module') output = self.ComputeMacBundleOutput() if is_empty: output += '.stamp' variables = [] self.AppendPostbuildVariable(variables, spec, output, self.target.binary, is_command_start=not package_framework) if package_framework and not is_empty: variables.append(('version', self.xcode_settings.GetFrameworkVersion())) self.ninja.build(output, 'package_framework', mac_bundle_depends, variables=variables) else: self.ninja.build(output, 'stamp', mac_bundle_depends, variables=variables) self.target.bundle = output return output def GetToolchainEnv(self, additional_settings=None): """Returns the variables toolchain would set for build steps.""" env = self.GetSortedXcodeEnv(additional_settings=additional_settings) if self.flavor == 'win': env = self.GetMsvsToolchainEnv( additional_settings=additional_settings) return env def GetMsvsToolchainEnv(self, additional_settings=None): """Returns the variables Visual Studio would set for build steps.""" return self.msvs_settings.GetVSMacroEnv('$!PRODUCT_DIR', config=self.config_name) def GetSortedXcodeEnv(self, additional_settings=None): """Returns the variables Xcode would set for build steps.""" assert self.abs_build_dir abs_build_dir = self.abs_build_dir return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, abs_build_dir, os.path.join(abs_build_dir, self.build_to_base), self.config_name, additional_settings) def GetSortedXcodePostbuildEnv(self): """Returns the variables Xcode would set for postbuild steps.""" postbuild_settings = {} # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( 'CHROMIUM_STRIP_SAVE_FILE') if strip_save_file: postbuild_settings['CHROMIUM_STRIP_SAVE_FILE'] = strip_save_file return self.GetSortedXcodeEnv(additional_settings=postbuild_settings) def AppendPostbuildVariable(self, variables, spec, output, binary, is_command_start=False): """Adds a 'postbuild' variable if there is a postbuild for |output|.""" postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start) if postbuild: variables.append(('postbuilds', postbuild)) def GetPostbuildCommand(self, spec, output, output_binary, is_command_start): """Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.""" if not self.xcode_settings or spec['type'] == 'none' or not output: return '' output = QuoteShellArgument(output, self.flavor) postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True) if output_binary is not None: postbuilds = self.xcode_settings.AddImplicitPostbuilds( self.config_name, os.path.normpath(os.path.join(self.base_to_build, output)), QuoteShellArgument( os.path.normpath(os.path.join(self.base_to_build, output_binary)), self.flavor), postbuilds, quiet=True) if not postbuilds: return '' # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList( ['cd', self.build_to_base])) env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv()) # G will be non-null if any postbuild fails. Run all postbuilds in a # subshell. commands = env + ' (' + \ ' && '.join([ninja_syntax.escape(command) for command in postbuilds]) command_string = (commands + '); G=$$?; ' # Remove the final output if any postbuild failed. '((exit $$G) || rm -rf %s) ' % output + '&& exit $$G)') if is_command_start: return '(' + command_string + ' && ' else: return '$ && (' + command_string def ComputeExportEnvString(self, env): """Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.""" export_str = [] for k, v in env: export_str.append('export %s=%s;' % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v)))) return ' '.join(export_str) def ComputeMacBundleOutput(self): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables['PRODUCT_DIR'] return self.ExpandSpecial( os.path.join(path, self.xcode_settings.GetWrapperName())) def ComputeOutputFileName(self, spec, type=None): """Compute the filename of the final output for the current target.""" if not type: type = spec['type'] default_variables = copy.copy(generator_default_variables) CalculateVariables(default_variables, {'flavor': self.flavor}) # Compute filename prefix: the product prefix, or a default for # the product type. DEFAULT_PREFIX = { 'loadable_module': default_variables['SHARED_LIB_PREFIX'], 'shared_library': default_variables['SHARED_LIB_PREFIX'], 'static_library': default_variables['STATIC_LIB_PREFIX'], 'executable': default_variables['EXECUTABLE_PREFIX'], } prefix = spec.get('product_prefix', DEFAULT_PREFIX.get(type, '')) # Compute filename extension: the product extension, or a default # for the product type. DEFAULT_EXTENSION = { 'loadable_module': default_variables['SHARED_LIB_SUFFIX'], 'shared_library': default_variables['SHARED_LIB_SUFFIX'], 'static_library': default_variables['STATIC_LIB_SUFFIX'], 'executable': default_variables['EXECUTABLE_SUFFIX'], } extension = spec.get('product_extension') if extension: extension = '.' + extension else: extension = DEFAULT_EXTENSION.get(type, '') if 'product_name' in spec: # If we were given an explicit name, use that. target = spec['product_name'] else: # Otherwise, derive a name from the target name. target = spec['target_name'] if prefix == 'lib': # Snip out an extra 'lib' from libs if appropriate. target = StripPrefix(target, 'lib') if type in ('static_library', 'loadable_module', 'shared_library', 'executable'): return '%s%s%s' % (prefix, target, extension) elif type == 'none': return '%s.stamp' % target else: raise Exception('Unhandled output type %s' % type) def ComputeOutput(self, spec, arch=None): """Compute the path for the final output of the spec.""" type = spec['type'] if self.flavor == 'win': override = self.msvs_settings.GetOutputName(self.config_name, self.ExpandSpecial) if override: return override if arch is None and self.flavor == 'mac' and type in ( 'static_library', 'executable', 'shared_library', 'loadable_module'): filename = self.xcode_settings.GetExecutablePath() else: filename = self.ComputeOutputFileName(spec, type) if arch is None and 'product_dir' in spec: path = os.path.join(spec['product_dir'], filename) return self.ExpandSpecial(path) # Some products go into the output root, libraries go into shared library # dir, and everything else goes into the normal place. type_in_output_root = ['executable', 'loadable_module'] if self.flavor == 'mac' and self.toolset == 'target': type_in_output_root += ['shared_library', 'static_library'] elif self.flavor == 'win' and self.toolset == 'target': type_in_output_root += ['shared_library'] if arch is not None: # Make sure partial executables don't end up in a bundle or the regular # output directory. archdir = 'arch' if self.toolset != 'target': archdir = os.path.join('arch', '%s' % self.toolset) return os.path.join(archdir, AddArch(filename, arch)) elif type in type_in_output_root or self.is_standalone_static_library: return filename elif type == 'shared_library': libdir = 'lib' if self.toolset != 'target': libdir = os.path.join('lib', '%s' % self.toolset) return os.path.join(libdir, filename) else: return self.GypPathToUniqueOutput(filename, qualified=False) def WriteVariableList(self, ninja_file, var, values): assert not isinstance(values, str) if values is None: values = [] ninja_file.variable(var, ' '.join(values)) def WriteNewNinjaRule(self, name, args, description, is_cygwin, env, pool, depfile=None): """Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.""" if self.flavor == 'win': args = [self.msvs_settings.ConvertVSMacros( arg, self.base_to_build, config=self.config_name) for arg in args] description = self.msvs_settings.ConvertVSMacros( description, config=self.config_name) elif self.flavor == 'mac': # |env| is an empty list on non-mac. args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args] description = gyp.xcode_emulation.ExpandEnvVars(description, env) # TODO: we shouldn't need to qualify names; we do it because # currently the ninja rule namespace is global, but it really # should be scoped to the subninja. rule_name = self.name if self.toolset == 'target': rule_name += '.' + self.toolset rule_name += '.' + name rule_name = re.sub('[^a-zA-Z0-9_]', '_', rule_name) # Remove variable references, but not if they refer to the magic rule # variables. This is not quite right, as it also protects these for # actions, not just for rules where they are valid. Good enough. protect = [ '${root}', '${dirname}', '${source}', '${ext}', '${name}' ] protect = '(?!' + '|'.join(map(re.escape, protect)) + ')' description = re.sub(protect + r'\$', '_', description) # gyp dictates that commands are run from the base directory. # cd into the directory before running, and adjust paths in # the arguments to point to the proper locations. rspfile = None rspfile_content = None args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args] if self.flavor == 'win': rspfile = rule_name + '.$unique_name.rsp' # The cygwin case handles this inside the bash sub-shell. run_in = '' if is_cygwin else ' ' + self.build_to_base if is_cygwin: rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine( args, self.build_to_base) else: rspfile_content = gyp.msvs_emulation.EncodeRspFileList(args) command = ('%s gyp-win-tool action-wrapper $arch ' % sys.executable + rspfile + run_in) else: env = self.ComputeExportEnvString(env) command = gyp.common.EncodePOSIXShellList(args) command = 'cd %s; ' % self.build_to_base + env + command # GYP rules/actions express being no-ops by not touching their outputs. # Avoid executing downstream dependencies in this case by specifying # restat=1 to ninja. self.ninja.rule(rule_name, command, description, depfile=depfile, restat=True, pool=pool, rspfile=rspfile, rspfile_content=rspfile_content) self.ninja.newline() return rule_name, args def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" global generator_additional_non_configuration_keys global generator_additional_path_sections flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. import gyp.generator.xcode as xcode_generator generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) elif flavor == 'win': exts = gyp.MSVSUtil.TARGET_TYPE_EXT default_variables.setdefault('OS', 'win') default_variables['EXECUTABLE_SUFFIX'] = '.' + exts['executable'] default_variables['STATIC_LIB_PREFIX'] = '' default_variables['STATIC_LIB_SUFFIX'] = '.' + exts['static_library'] default_variables['SHARED_LIB_PREFIX'] = '' default_variables['SHARED_LIB_SUFFIX'] = '.' + exts['shared_library'] # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR', os.path.join('$!PRODUCT_DIR', 'lib')) default_variables.setdefault('LIB_DIR', os.path.join('$!PRODUCT_DIR', 'obj')) def ComputeOutputDir(params): """Returns the path from the toplevel_dir to the build output directory.""" # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to ninja easier, ninja doesn't put anything here. generator_dir = os.path.relpath(params['options'].generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = params.get('generator_flags', {}).get('output_dir', 'out') # Relative path from source root to our output files. e.g. "out" return os.path.normpath(os.path.join(generator_dir, output_dir)) def CalculateGeneratorInputInfo(params): """Called by __init__ to initialize generator values based on params.""" # E.g. "out/gypfiles" toplevel = params['options'].toplevel_dir qualified_out_dir = os.path.normpath(os.path.join( toplevel, ComputeOutputDir(params), 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': toplevel, 'qualified_out_dir': qualified_out_dir, } def OpenOutput(path, mode='w'): """Open |path| for writing, creating directories if necessary.""" gyp.common.EnsureDirExists(path) return open(path, mode) def CommandWithWrapper(cmd, wrappers, prog): wrapper = wrappers.get(cmd, '') if wrapper: return wrapper + ' ' + prog return prog def GetDefaultConcurrentLinks(): """Returns a best-guess for a number of concurrent links.""" pool_size = int(os.environ.get('GYP_LINK_CONCURRENCY', 0)) if pool_size: return pool_size if sys.platform in ('win32', 'cygwin'): import ctypes class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("sullAvailExtendedVirtual", ctypes.c_ulonglong), ] stat = MEMORYSTATUSEX() stat.dwLength = ctypes.sizeof(stat) ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) # VS 2015 uses 20% more working set than VS 2013 and can consume all RAM # on a 64 GB machine. mem_limit = max(1, stat.ullTotalPhys / (5 * (2 ** 30))) # total / 5GB hard_cap = max(1, int(os.environ.get('GYP_LINK_CONCURRENCY_MAX', 2**32))) return min(mem_limit, hard_cap) elif sys.platform.startswith('linux'): if os.path.exists("/proc/meminfo"): with open("/proc/meminfo") as meminfo: memtotal_re = re.compile(r'^MemTotal:\s*(\d*)\s*kB') for line in meminfo: match = memtotal_re.match(line) if not match: continue # Allow 8Gb per link on Linux because Gold is quite memory hungry return max(1, int(match.group(1)) / (8 * (2 ** 20))) return 1 elif sys.platform == 'darwin': try: avail_bytes = int(subprocess.check_output(['sysctl', '-n', 'hw.memsize'])) # A static library debug build of Chromium's unit_tests takes ~2.7GB, so # 4GB per ld process allows for some more bloat. return max(1, avail_bytes / (4 * (2 ** 30))) # total / 4GB except: return 1 else: # TODO(scottmg): Implement this for other platforms. return 1 def _GetWinLinkRuleNameSuffix(embed_manifest): """Returns the suffix used to select an appropriate linking rule depending on whether the manifest embedding is enabled.""" return '_embed' if embed_manifest else '' def _AddWinLinkRules(master_ninja, embed_manifest): """Adds link rules for Windows platform to |master_ninja|.""" def FullLinkCommand(ldcmd, out, binary_type): resource_name = { 'exe': '1', 'dll': '2', }[binary_type] return '%(python)s gyp-win-tool link-with-manifests $arch %(embed)s ' \ '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' \ '$manifests' % { 'python': sys.executable, 'out': out, 'ldcmd': ldcmd, 'resname': resource_name, 'embed': embed_manifest } rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest) use_separate_mspdbsrv = ( int(os.environ.get('GYP_USE_SEPARATE_MSPDBSRV', '0')) != 0) dlldesc = 'LINK%s(DLL) $binary' % rule_name_suffix.upper() dllcmd = ('%s gyp-win-tool link-wrapper $arch %s ' '$ld /nologo $implibflag /DLL /OUT:$binary ' '@$binary.rsp' % (sys.executable, use_separate_mspdbsrv)) dllcmd = FullLinkCommand(dllcmd, '$binary', 'dll') master_ninja.rule('solink' + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile='$binary.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True, pool='link_pool') master_ninja.rule('solink_module' + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile='$binary.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True, pool='link_pool') # Note that ldflags goes at the end so that it has the option of # overriding default settings earlier in the command line. exe_cmd = ('%s gyp-win-tool link-wrapper $arch %s ' '$ld /nologo /OUT:$binary @$binary.rsp' % (sys.executable, use_separate_mspdbsrv)) exe_cmd = FullLinkCommand(exe_cmd, '$binary', 'exe') master_ninja.rule('link' + rule_name_suffix, description='LINK%s $binary' % rule_name_suffix.upper(), command=exe_cmd, rspfile='$binary.rsp', rspfile_content='$in_newline $libs $ldflags', pool='link_pool') def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params['options'] flavor = gyp.common.GetFlavor(params) generator_flags = params.get('generator_flags', {}) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath( os.path.join(ComputeOutputDir(params), config_name)) toplevel_build = os.path.join(options.toplevel_dir, build_dir) master_ninja_file = OpenOutput(os.path.join(toplevel_build, 'build.ninja')) master_ninja = ninja_syntax.Writer(master_ninja_file, width=120) # Put build-time support tools in out/{config_name}. gyp.common.CopyTool(flavor, toplevel_build) # Grab make settings for CC/CXX. # The rules are # - The priority from low to high is gcc/g++, the 'make_global_settings' in # gyp, the environment variable. # - If there is no 'make_global_settings' for CC.host/CXX.host or # 'CC_host'/'CXX_host' enviroment variable, cc_host/cxx_host should be set # to cc/cxx. if flavor == 'win': ar = 'lib.exe' # cc and cxx must be set to the correct architecture by overriding with one # of cl_x86 or cl_x64 below. cc = 'UNSET' cxx = 'UNSET' ld = 'link.exe' ld_host = '$ld' else: ar = 'ar' cc = 'cc' cxx = 'c++' ld = '$cc' ldxx = '$cxx' ld_host = '$cc_host' ldxx_host = '$cxx_host' ar_host = 'ar' cc_host = None cxx_host = None cc_host_global_setting = None cxx_host_global_setting = None clang_cl = None nm = 'nm' nm_host = 'nm' readelf = 'readelf' readelf_host = 'readelf' build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings = data[build_file].get('make_global_settings', []) build_to_root = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) wrappers = {} for key, value in make_global_settings: if key == 'AR': ar = os.path.join(build_to_root, value) if key == 'AR.host': ar_host = os.path.join(build_to_root, value) if key == 'CC': cc = os.path.join(build_to_root, value) if cc.endswith('clang-cl'): clang_cl = cc if key == 'CXX': cxx = os.path.join(build_to_root, value) if key == 'CC.host': cc_host = os.path.join(build_to_root, value) cc_host_global_setting = value if key == 'CXX.host': cxx_host = os.path.join(build_to_root, value) cxx_host_global_setting = value if key == 'LD': ld = os.path.join(build_to_root, value) if key == 'LD.host': ld_host = os.path.join(build_to_root, value) if key == 'NM': nm = os.path.join(build_to_root, value) if key == 'NM.host': nm_host = os.path.join(build_to_root, value) if key == 'READELF': readelf = os.path.join(build_to_root, value) if key == 'READELF.host': readelf_host = os.path.join(build_to_root, value) if key.endswith('_wrapper'): wrappers[key[:-len('_wrapper')]] = os.path.join(build_to_root, value) # Support wrappers from environment variables too. for key, value in os.environ.iteritems(): if key.lower().endswith('_wrapper'): key_prefix = key[:-len('_wrapper')] key_prefix = re.sub(r'\.HOST$', '.host', key_prefix) wrappers[key_prefix] = os.path.join(build_to_root, value) if flavor == 'win': configs = [target_dicts[qualified_target]['configurations'][config_name] for qualified_target in target_list] shared_system_includes = None if not generator_flags.get('ninja_use_custom_environment_files', 0): shared_system_includes = \ gyp.msvs_emulation.ExtractSharedMSVSSystemIncludes( configs, generator_flags) cl_paths = gyp.msvs_emulation.GenerateEnvironmentFiles( toplevel_build, generator_flags, shared_system_includes, OpenOutput) for arch, path in cl_paths.iteritems(): if clang_cl: # If we have selected clang-cl, use that instead. path = clang_cl command = CommandWithWrapper('CC', wrappers, QuoteShellArgument(path, 'win')) if clang_cl: # Use clang-cl to cross-compile for x86 or x86_64. command += (' -m32' if arch == 'x86' else ' -m64') master_ninja.variable('cl_' + arch, command) cc = GetEnvironFallback(['CC_target', 'CC'], cc) master_ninja.variable('cc', CommandWithWrapper('CC', wrappers, cc)) cxx = GetEnvironFallback(['CXX_target', 'CXX'], cxx) master_ninja.variable('cxx', CommandWithWrapper('CXX', wrappers, cxx)) if flavor == 'win': master_ninja.variable('ld', ld) master_ninja.variable('idl', 'midl.exe') master_ninja.variable('ar', ar) master_ninja.variable('rc', 'rc.exe') master_ninja.variable('ml_x86', 'ml.exe') master_ninja.variable('ml_x64', 'ml64.exe') master_ninja.variable('mt', 'mt.exe') else: master_ninja.variable('ld', CommandWithWrapper('LINK', wrappers, ld)) master_ninja.variable('ldxx', CommandWithWrapper('LINK', wrappers, ldxx)) master_ninja.variable('ar', GetEnvironFallback(['AR_target', 'AR'], ar)) if flavor != 'mac': # Mac does not use readelf/nm for .TOC generation, so avoiding polluting # the master ninja with extra unused variables. master_ninja.variable( 'nm', GetEnvironFallback(['NM_target', 'NM'], nm)) master_ninja.variable( 'readelf', GetEnvironFallback(['READELF_target', 'READELF'], readelf)) if generator_supports_multiple_toolsets: if not cc_host: cc_host = cc if not cxx_host: cxx_host = cxx master_ninja.variable('ar_host', GetEnvironFallback(['AR_host'], ar_host)) master_ninja.variable('nm_host', GetEnvironFallback(['NM_host'], nm_host)) master_ninja.variable('readelf_host', GetEnvironFallback(['READELF_host'], readelf_host)) cc_host = GetEnvironFallback(['CC_host'], cc_host) cxx_host = GetEnvironFallback(['CXX_host'], cxx_host) # The environment variable could be used in 'make_global_settings', like # ['CC.host', '$(CC)'] or ['CXX.host', '$(CXX)'], transform them here. if '$(CC)' in cc_host and cc_host_global_setting: cc_host = cc_host_global_setting.replace('$(CC)', cc) if '$(CXX)' in cxx_host and cxx_host_global_setting: cxx_host = cxx_host_global_setting.replace('$(CXX)', cxx) master_ninja.variable('cc_host', CommandWithWrapper('CC.host', wrappers, cc_host)) master_ninja.variable('cxx_host', CommandWithWrapper('CXX.host', wrappers, cxx_host)) if flavor == 'win': master_ninja.variable('ld_host', ld_host) else: master_ninja.variable('ld_host', CommandWithWrapper( 'LINK', wrappers, ld_host)) master_ninja.variable('ldxx_host', CommandWithWrapper( 'LINK', wrappers, ldxx_host)) master_ninja.newline() master_ninja.pool('link_pool', depth=GetDefaultConcurrentLinks()) master_ninja.newline() deps = 'msvc' if flavor == 'win' else 'gcc' if flavor != 'win': master_ninja.rule( 'cc', description='CC $out', command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c ' '$cflags_pch_c -c $in -o $out'), depfile='$out.d', deps=deps) master_ninja.rule( 'cc_s', description='CC $out', command=('$cc $defines $includes $cflags $cflags_c ' '$cflags_pch_c -c $in -o $out')) master_ninja.rule( 'cxx', description='CXX $out', command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc ' '$cflags_pch_cc -c $in -o $out'), depfile='$out.d', deps=deps) else: # TODO(scottmg) Separate pdb names is a test to see if it works around # http://crbug.com/142362. It seems there's a race between the creation of # the .pdb by the precompiled header step for .cc and the compilation of # .c files. This should be handled by mspdbsrv, but rarely errors out with # c1xx : fatal error C1033: cannot open program database # By making the rules target separate pdb files this might be avoided. cc_command = ('ninja -t msvc -e $arch ' + '-- ' '$cc /nologo /showIncludes /FC ' '@$out.rsp /c $in /Fo$out /Fd$pdbname_c ') cxx_command = ('ninja -t msvc -e $arch ' + '-- ' '$cxx /nologo /showIncludes /FC ' '@$out.rsp /c $in /Fo$out /Fd$pdbname_cc ') master_ninja.rule( 'cc', description='CC $out', command=cc_command, rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_c', deps=deps) master_ninja.rule( 'cxx', description='CXX $out', command=cxx_command, rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_cc', deps=deps) master_ninja.rule( 'idl', description='IDL $in', command=('%s gyp-win-tool midl-wrapper $arch $outdir ' '$tlb $h $dlldata $iid $proxy $in ' '$midl_includes $idlflags' % sys.executable)) master_ninja.rule( 'rc', description='RC $in', # Note: $in must be last otherwise rc.exe complains. command=('%s gyp-win-tool rc-wrapper ' '$arch $rc $defines $resource_includes $rcflags /fo$out $in' % sys.executable)) master_ninja.rule( 'asm', description='ASM $out', command=('%s gyp-win-tool asm-wrapper ' '$arch $asm $defines $includes $asmflags /c /Fo $out $in' % sys.executable)) if flavor != 'mac' and flavor != 'win': master_ninja.rule( 'alink', description='AR $out', command='rm -f $out && $ar rcs $arflags $out $in') master_ninja.rule( 'alink_thin', description='AR $out', command='rm -f $out && $ar rcsT $arflags $out $in') # This allows targets that only need to depend on $lib's API to declare an # order-only dependency on $lib.TOC and avoid relinking such downstream # dependencies when $lib changes only in non-public ways. # The resulting string leaves an uninterpolated %{suffix} which # is used in the final substitution below. mtime_preserving_solink_base = ( 'if [ ! -e $lib -o ! -e $lib.TOC ]; then ' '%(solink)s && %(extract_toc)s > $lib.TOC; else ' '%(solink)s && %(extract_toc)s > $lib.tmp && ' 'if ! cmp -s $lib.tmp $lib.TOC; then mv $lib.tmp $lib.TOC ; ' 'fi; fi' % { 'solink': '$ld -shared $ldflags -o $lib -Wl,-soname=$soname %(suffix)s', 'extract_toc': ('{ $readelf -d $lib | grep SONAME ; ' '$nm -gD -f p $lib | cut -f1-2 -d\' \'; }')}) master_ninja.rule( 'solink', description='SOLINK $lib', restat=True, command=mtime_preserving_solink_base % {'suffix': '@$link_file_list'}, rspfile='$link_file_list', rspfile_content= '-Wl,--whole-archive $in $solibs -Wl,--no-whole-archive $libs', pool='link_pool') master_ninja.rule( 'solink_module', description='SOLINK(module) $lib', restat=True, command=mtime_preserving_solink_base % {'suffix': '@$link_file_list'}, rspfile='$link_file_list', rspfile_content='-Wl,--start-group $in -Wl,--end-group $solibs $libs', pool='link_pool') master_ninja.rule( 'link', description='LINK $out', command=('$ld $ldflags -o $out ' '-Wl,--start-group $in -Wl,--end-group $solibs $libs'), pool='link_pool') elif flavor == 'win': master_ninja.rule( 'alink', description='LIB $out', command=('%s gyp-win-tool link-wrapper $arch False ' '$ar /nologo /ignore:4221 /OUT:$out @$out.rsp' % sys.executable), rspfile='$out.rsp', rspfile_content='$in_newline $libflags') _AddWinLinkRules(master_ninja, embed_manifest=True) _AddWinLinkRules(master_ninja, embed_manifest=False) else: master_ninja.rule( 'objc', description='OBJC $out', command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_objc ' '$cflags_pch_objc -c $in -o $out'), depfile='$out.d', deps=deps) master_ninja.rule( 'objcxx', description='OBJCXX $out', command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_objcc ' '$cflags_pch_objcc -c $in -o $out'), depfile='$out.d', deps=deps) master_ninja.rule( 'alink', description='LIBTOOL-STATIC $out, POSTBUILDS', command='rm -f $out && ' './gyp-mac-tool filter-libtool libtool $libtool_flags ' '-static -o $out $in' '$postbuilds') master_ninja.rule( 'lipo', description='LIPO $out, POSTBUILDS', command='rm -f $out && lipo -create $in -output $out$postbuilds') master_ninja.rule( 'solipo', description='SOLIPO $out, POSTBUILDS', command=( 'rm -f $lib $lib.TOC && lipo -create $in -output $lib$postbuilds &&' '%(extract_toc)s > $lib.TOC' % { 'extract_toc': '{ otool -l $lib | grep LC_ID_DYLIB -A 5; ' 'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'})) # Record the public interface of $lib in $lib.TOC. See the corresponding # comment in the posix section above for details. solink_base = '$ld %(type)s $ldflags -o $lib %(suffix)s' mtime_preserving_solink_base = ( 'if [ ! -e $lib -o ! -e $lib.TOC ] || ' # Always force dependent targets to relink if this library # reexports something. Handling this correctly would require # recursive TOC dumping but this is rare in practice, so punt. 'otool -l $lib | grep -q LC_REEXPORT_DYLIB ; then ' '%(solink)s && %(extract_toc)s > $lib.TOC; ' 'else ' '%(solink)s && %(extract_toc)s > $lib.tmp && ' 'if ! cmp -s $lib.tmp $lib.TOC; then ' 'mv $lib.tmp $lib.TOC ; ' 'fi; ' 'fi' % { 'solink': solink_base, 'extract_toc': '{ otool -l $lib | grep LC_ID_DYLIB -A 5; ' 'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'}) solink_suffix = '@$link_file_list$postbuilds' master_ninja.rule( 'solink', description='SOLINK $lib, POSTBUILDS', restat=True, command=mtime_preserving_solink_base % {'suffix': solink_suffix, 'type': '-shared'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'solink_notoc', description='SOLINK $lib, POSTBUILDS', restat=True, command=solink_base % {'suffix':solink_suffix, 'type': '-shared'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'solink_module', description='SOLINK(module) $lib, POSTBUILDS', restat=True, command=mtime_preserving_solink_base % {'suffix': solink_suffix, 'type': '-bundle'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'solink_module_notoc', description='SOLINK(module) $lib, POSTBUILDS', restat=True, command=solink_base % {'suffix': solink_suffix, 'type': '-bundle'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'link', description='LINK $out, POSTBUILDS', command=('$ld $ldflags -o $out ' '$in $solibs $libs$postbuilds'), pool='link_pool') master_ninja.rule( 'preprocess_infoplist', description='PREPROCESS INFOPLIST $out', command=('$cc -E -P -Wno-trigraphs -x c $defines $in -o $out && ' 'plutil -convert xml1 $out $out')) master_ninja.rule( 'copy_infoplist', description='COPY INFOPLIST $in', command='$env ./gyp-mac-tool copy-info-plist $in $out $binary $keys') master_ninja.rule( 'merge_infoplist', description='MERGE INFOPLISTS $in', command='$env ./gyp-mac-tool merge-info-plist $out $in') master_ninja.rule( 'compile_xcassets', description='COMPILE XCASSETS $in', command='$env ./gyp-mac-tool compile-xcassets $keys $in') master_ninja.rule( 'mac_tool', description='MACTOOL $mactool_cmd $in', command='$env ./gyp-mac-tool $mactool_cmd $in $out $binary') master_ninja.rule( 'package_framework', description='PACKAGE FRAMEWORK $out, POSTBUILDS', command='./gyp-mac-tool package-framework $out $version$postbuilds ' '&& touch $out') if flavor == 'win': master_ninja.rule( 'stamp', description='STAMP $out', command='%s gyp-win-tool stamp $out' % sys.executable) master_ninja.rule( 'copy', description='COPY $in $out', command='%s gyp-win-tool recursive-mirror $in $out' % sys.executable) else: master_ninja.rule( 'stamp', description='STAMP $out', command='${postbuilds}touch $out') master_ninja.rule( 'copy', description='COPY $in $out', command='rm -rf $out && cp -af $in $out') master_ninja.newline() all_targets = set() for build_file in params['build_files']: for target in gyp.common.AllTargets(target_list, target_dicts, os.path.normpath(build_file)): all_targets.add(target) all_outputs = set() # target_outputs is a map from qualified target name to a Target object. target_outputs = {} # target_short_names is a map from target short name to a list of Target # objects. target_short_names = {} # short name of targets that were skipped because they didn't contain anything # interesting. # NOTE: there may be overlap between this an non_empty_target_names. empty_target_names = set() # Set of non-empty short target names. # NOTE: there may be overlap between this an empty_target_names. non_empty_target_names = set() for qualified_target in target_list: # qualified_target is like: third_party/icu/icu.gyp:icui18n#target build_file, name, toolset = \ gyp.common.ParseQualifiedTarget(qualified_target) this_make_global_settings = data[build_file].get('make_global_settings', []) assert make_global_settings == this_make_global_settings, ( "make_global_settings needs to be the same for all targets. %s vs. %s" % (this_make_global_settings, make_global_settings)) spec = target_dicts[qualified_target] if flavor == 'mac': gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) # If build_file is a symlink, we must not follow it because there's a chance # it could point to a path above toplevel_dir, and we cannot correctly deal # with that case at the moment. build_file = gyp.common.RelativePath(build_file, options.toplevel_dir, False) qualified_target_for_hash = gyp.common.QualifiedTarget(build_file, name, toolset) hash_for_rules = hashlib.md5(qualified_target_for_hash).hexdigest() base_path = os.path.dirname(build_file) obj = 'obj' if toolset != 'target': obj += '.' + toolset output_file = os.path.join(obj, base_path, name + '.ninja') ninja_output = StringIO() writer = NinjaWriter(hash_for_rules, target_outputs, base_path, build_dir, ninja_output, toplevel_build, output_file, flavor, toplevel_dir=options.toplevel_dir) target = writer.WriteSpec(spec, config_name, generator_flags) if ninja_output.tell() > 0: # Only create files for ninja files that actually have contents. with OpenOutput(os.path.join(toplevel_build, output_file)) as ninja_file: ninja_file.write(ninja_output.getvalue()) ninja_output.close() master_ninja.subninja(output_file) if target: if name != target.FinalOutput() and spec['toolset'] == 'target': target_short_names.setdefault(name, []).append(target) target_outputs[qualified_target] = target if qualified_target in all_targets: all_outputs.add(target.FinalOutput()) non_empty_target_names.add(name) else: empty_target_names.add(name) if target_short_names: # Write a short name to build this target. This benefits both the # "build chrome" case as well as the gyp tests, which expect to be # able to run actions and build libraries by their short name. master_ninja.newline() master_ninja.comment('Short names for targets.') for short_name in target_short_names: master_ninja.build(short_name, 'phony', [x.FinalOutput() for x in target_short_names[short_name]]) # Write phony targets for any empty targets that weren't written yet. As # short names are not necessarily unique only do this for short names that # haven't already been output for another target. empty_target_names = empty_target_names - non_empty_target_names if empty_target_names: master_ninja.newline() master_ninja.comment('Empty targets (output for completeness).') for name in sorted(empty_target_names): master_ninja.build(name, 'phony') if all_outputs: master_ninja.newline() master_ninja.build('all', 'phony', list(all_outputs)) master_ninja.default(generator_flags.get('default_target', 'all')) master_ninja_file.close() def PerformBuild(data, configurations, params): options = params['options'] for config in configurations: builddir = os.path.join(options.toplevel_dir, 'out', config) arguments = ['ninja', '-C', builddir] print 'Building [%s]: %s' % (config, arguments) subprocess.check_call(arguments) def CallGenerateOutputForConfig(arglist): # Ignore the interrupt signal so that the parent process catches it and # kills all multiprocessing children. signal.signal(signal.SIGINT, signal.SIG_IGN) (target_list, target_dicts, data, params, config_name) = arglist GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) def GenerateOutput(target_list, target_dicts, data, params): # Update target_dicts for iOS device builds. target_dicts = gyp.xcode_emulation.CloneConfigurationForDeviceAndEmulator( target_dicts) user_config = params.get('generator_flags', {}).get('config', None) if gyp.common.GetFlavor(params) == 'win': target_list, target_dicts = MSVSUtil.ShardTargets(target_list, target_dicts) target_list, target_dicts = MSVSUtil.InsertLargePdbShims( target_list, target_dicts, generator_default_variables) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['configurations'].keys() if params['parallel']: try: pool = multiprocessing.Pool(len(config_names)) arglists = [] for config_name in config_names: arglists.append( (target_list, target_dicts, data, params, config_name)) pool.map(CallGenerateOutputForConfig, arglists) except KeyboardInterrupt, e: pool.terminate() raise e else: for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
mit
JioCloud/nova
nova/tests/unit/objects/test_floating_ip.py
65
11358
# Copyright 2014 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock import netaddr from nova import exception from nova import objects from nova.objects import floating_ip from nova.tests.unit.objects import test_fixed_ip from nova.tests.unit.objects import test_network from nova.tests.unit.objects import test_objects fake_floating_ip = { 'created_at': None, 'updated_at': None, 'deleted_at': None, 'deleted': False, 'id': 123, 'address': '172.17.0.1', 'fixed_ip_id': None, 'project_id': None, 'host': None, 'auto_assigned': False, 'pool': None, 'interface': None, 'fixed_ip': None, } class _TestFloatingIPObject(object): def _compare(self, obj, db_obj): for field in obj.fields: if field in floating_ip.FLOATING_IP_OPTIONAL_ATTRS: if obj.obj_attr_is_set(field): obj_val = obj[field].id db_val = db_obj[field]['id'] else: continue else: obj_val = obj[field] db_val = db_obj[field] if isinstance(obj_val, netaddr.IPAddress): obj_val = str(obj_val) self.assertEqual(db_val, obj_val) @mock.patch('nova.db.floating_ip_get') def test_get_by_id(self, get): db_floatingip = dict(fake_floating_ip, fixed_ip=test_fixed_ip.fake_fixed_ip) get.return_value = db_floatingip floatingip = floating_ip.FloatingIP.get_by_id(self.context, 123) get.assert_called_once_with(self.context, 123) self._compare(floatingip, db_floatingip) @mock.patch('nova.db.floating_ip_get_by_address') def test_get_by_address(self, get): get.return_value = fake_floating_ip floatingip = floating_ip.FloatingIP.get_by_address(self.context, '1.2.3.4') get.assert_called_once_with(self.context, '1.2.3.4') self._compare(floatingip, fake_floating_ip) @mock.patch('nova.db.floating_ip_get_pools') def test_get_pool_names(self, get): get.return_value = [{'name': 'a'}, {'name': 'b'}] self.assertEqual(['a', 'b'], floating_ip.FloatingIP.get_pool_names(self.context)) @mock.patch('nova.db.floating_ip_allocate_address') def test_allocate_address(self, allocate): allocate.return_value = '1.2.3.4' self.assertEqual('1.2.3.4', floating_ip.FloatingIP.allocate_address(self.context, 'project', 'pool')) allocate.assert_called_with(self.context, 'project', 'pool', auto_assigned=False) @mock.patch('nova.db.floating_ip_fixed_ip_associate') def test_associate(self, associate): db_fixed = dict(test_fixed_ip.fake_fixed_ip, network=test_network.fake_network) associate.return_value = db_fixed floatingip = floating_ip.FloatingIP.associate(self.context, '172.17.0.1', '192.168.1.1', 'host') associate.assert_called_with(self.context, '172.17.0.1', '192.168.1.1', 'host') self.assertEqual(db_fixed['id'], floatingip.fixed_ip.id) self.assertEqual('172.17.0.1', str(floatingip.address)) self.assertEqual('host', floatingip.host) @mock.patch('nova.db.floating_ip_deallocate') def test_deallocate(self, deallocate): floating_ip.FloatingIP.deallocate(self.context, '1.2.3.4') deallocate.assert_called_with(self.context, '1.2.3.4') @mock.patch('nova.db.floating_ip_destroy') def test_destroy(self, destroy): floating_ip.FloatingIP.destroy(self.context, '1.2.3.4') destroy.assert_called_with(self.context, '1.2.3.4') @mock.patch('nova.db.floating_ip_disassociate') def test_disassociate(self, disassociate): db_fixed = dict(test_fixed_ip.fake_fixed_ip, network=test_network.fake_network) disassociate.return_value = db_fixed floatingip = floating_ip.FloatingIP.disassociate(self.context, '1.2.3.4') disassociate.assert_called_with(self.context, '1.2.3.4') self.assertEqual(db_fixed['id'], floatingip.fixed_ip.id) self.assertEqual('1.2.3.4', str(floatingip.address)) @mock.patch('nova.db.floating_ip_update') def test_save(self, update): update.return_value = fake_floating_ip floatingip = floating_ip.FloatingIP(context=self.context, id=123, address='1.2.3.4', host='foo') floatingip.obj_reset_changes(['address', 'id']) floatingip.save() self.assertEqual(set(), floatingip.obj_what_changed()) update.assert_called_with(self.context, '1.2.3.4', {'host': 'foo'}) def test_save_errors(self): floatingip = floating_ip.FloatingIP(context=self.context, id=123, host='foo') floatingip.obj_reset_changes() floating_ip.address = '1.2.3.4' self.assertRaises(exception.ObjectActionError, floatingip.save) floatingip.obj_reset_changes() floatingip.fixed_ip_id = 1 self.assertRaises(exception.ObjectActionError, floatingip.save) @mock.patch('nova.db.floating_ip_update') def test_save_no_fixedip(self, update): update.return_value = fake_floating_ip floatingip = floating_ip.FloatingIP(context=self.context, id=123) floatingip.fixed_ip = objects.FixedIP(context=self.context, id=456) self.assertNotIn('fixed_ip', update.calls[1]) @mock.patch('nova.db.floating_ip_get_all') def test_get_all(self, get): get.return_value = [fake_floating_ip] floatingips = floating_ip.FloatingIPList.get_all(self.context) self.assertEqual(1, len(floatingips)) self._compare(floatingips[0], fake_floating_ip) get.assert_called_with(self.context) @mock.patch('nova.db.floating_ip_get_all_by_host') def test_get_by_host(self, get): get.return_value = [fake_floating_ip] floatingips = floating_ip.FloatingIPList.get_by_host(self.context, 'host') self.assertEqual(1, len(floatingips)) self._compare(floatingips[0], fake_floating_ip) get.assert_called_with(self.context, 'host') @mock.patch('nova.db.floating_ip_get_all_by_project') def test_get_by_project(self, get): get.return_value = [fake_floating_ip] floatingips = floating_ip.FloatingIPList.get_by_project(self.context, 'project') self.assertEqual(1, len(floatingips)) self._compare(floatingips[0], fake_floating_ip) get.assert_called_with(self.context, 'project') @mock.patch('nova.db.floating_ip_get_by_fixed_address') def test_get_by_fixed_address(self, get): get.return_value = [fake_floating_ip] floatingips = floating_ip.FloatingIPList.get_by_fixed_address( self.context, '1.2.3.4') self.assertEqual(1, len(floatingips)) self._compare(floatingips[0], fake_floating_ip) get.assert_called_with(self.context, '1.2.3.4') @mock.patch('nova.db.floating_ip_get_by_fixed_ip_id') def test_get_by_fixed_ip_id(self, get): get.return_value = [fake_floating_ip] floatingips = floating_ip.FloatingIPList.get_by_fixed_ip_id( self.context, 123) self.assertEqual(1, len(floatingips)) self._compare(floatingips[0], fake_floating_ip) get.assert_called_with(self.context, 123) @mock.patch('nova.db.instance_floating_address_get_all') def test_get_addresses_by_instance(self, get_all): expected = ['1.2.3.4', '4.5.6.7'] get_all.return_value = list(expected) ips = floating_ip.FloatingIP.get_addresses_by_instance( self.context, {'uuid': '1234'}) self.assertEqual(expected, ips) get_all.assert_called_once_with(self.context, '1234') def test_make_ip_info(self): result = objects.FloatingIPList.make_ip_info('1.2.3.4', 'pool', 'eth0') self.assertEqual({'address': '1.2.3.4', 'pool': 'pool', 'interface': 'eth0'}, result) @mock.patch('nova.db.floating_ip_bulk_create') def test_bulk_create(self, create_mock): def fake_create(ctxt, ip_info, want_result=False): return [{'id': 1, 'address': ip['address'], 'fixed_ip_id': 1, 'project_id': 'foo', 'host': 'host', 'auto_assigned': False, 'pool': ip['pool'], 'interface': ip['interface'], 'fixed_ip': None, 'created_at': None, 'updated_at': None, 'deleted_at': None, 'deleted': False} for ip in ip_info] create_mock.side_effect = fake_create ips = [objects.FloatingIPList.make_ip_info('1.1.1.1', 'pool', 'eth0'), objects.FloatingIPList.make_ip_info('1.1.1.2', 'loop', 'eth1')] result = objects.FloatingIPList.create(None, ips) self.assertIs(result, None) result = objects.FloatingIPList.create(None, ips, want_result=True) self.assertEqual('1.1.1.1', str(result[0].address)) self.assertEqual('1.1.1.2', str(result[1].address)) @mock.patch('nova.db.floating_ip_bulk_destroy') def test_bulk_destroy(self, destroy_mock): ips = [{'address': '1.2.3.4'}, {'address': '4.5.6.7'}] objects.FloatingIPList.destroy(None, ips) destroy_mock.assert_called_once_with(None, ips) def test_backport_fixedip_1_1(self): floating = objects.FloatingIP() fixed = objects.FixedIP() floating.fixed_ip = fixed primitive = floating.obj_to_primitive(target_version='1.1') self.assertEqual('1.1', primitive['nova_object.data']['fixed_ip']['nova_object.version']) class TestFloatingIPObject(test_objects._LocalTest, _TestFloatingIPObject): pass class TestRemoteFloatingIPObject(test_objects._RemoteTest, _TestFloatingIPObject): pass
apache-2.0
quattor/aquilon
lib/aquilon/worker/commands/del_router_address.py
1
3148
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor # # 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. """Contains the logic for `aq del router address`.""" from aquilon.exceptions_ import ArgumentError, NotFoundException from aquilon.aqdb.model import ARecord, NetworkEnvironment from aquilon.aqdb.model.network import get_net_id_from_ip from aquilon.worker.broker import BrokerCommand from aquilon.worker.dbwrappers.dns import delete_dns_record from aquilon.worker.dbwrappers.change_management import ChangeManagement class CommandDelRouterAddress(BrokerCommand): requires_plenaries = True required_parameters = [] def render(self, session, plenaries, dbuser, ip, fqdn, network_environment, exporter, user, justification, reason, logger, **arguments): dbnet_env = NetworkEnvironment.get_unique_or_default(session, network_environment) self.az.check_network_environment(dbuser, dbnet_env) if fqdn: dbdns_rec = ARecord.get_unique(session, fqdn=fqdn, dns_environment=dbnet_env.dns_environment, compel=True) ip = dbdns_rec.ip elif not ip: raise ArgumentError("Please specify either --ip or --fqdn.") dbnetwork = get_net_id_from_ip(session, ip, dbnet_env) # Validate ChangeManagement cm = ChangeManagement(session, user, justification, reason, logger, self.command, **arguments) cm.consider(dbnetwork) cm.validate() dbrouter = None for rtaddr in dbnetwork.routers: if rtaddr.ip == ip: dbrouter = rtaddr break if not dbrouter: raise NotFoundException("IP address {0} is not a router on " "{1:l}.".format(ip, dbnetwork)) # Only remove the DNS record if its not assinged to an interface, # or is a service address. (This would be easier if service # address were not split from assignments) for dns_rec in dbrouter.dns_records: if dns_rec.is_unused: delete_dns_record(dns_rec, verify_assignments=True, exporter=exporter) dbnetwork.routers.remove(dbrouter) session.flush() # TODO: update the templates of Zebra hosts on the network plenaries.add(dbnetwork) plenaries.write() return
apache-2.0
Nealelab/cloudtools
cloudtools/start.py
1
10330
from __future__ import print_function import sys import re from subprocess import check_call from .utils import latest_sha, load_config, load_config_file COMPATIBILITY_VERSION = 1 init_script = 'gs://hail-common/cloudtools/init_notebook{}.py'.format(COMPATIBILITY_VERSION) # master machine type to memory map, used for setting spark.driver.memory property machine_mem = { 'n1-standard-1': 3.75, 'n1-standard-2': 7.5, 'n1-standard-4': 15, 'n1-standard-8': 30, 'n1-standard-16': 60, 'n1-standard-32': 120, 'n1-standard-64': 240, 'n1-highmem-2': 13, 'n1-highmem-4': 26, 'n1-highmem-8': 52, 'n1-highmem-16': 104, 'n1-highmem-32': 208, 'n1-highmem-64': 416, 'n1-highcpu-2': 1.8, 'n1-highcpu-4': 3.6, 'n1-highcpu-8': 7.2, 'n1-highcpu-16': 14.4, 'n1-highcpu-32': 28.8, 'n1-highcpu-64': 57.6 } def init_parser(parser): parser.add_argument('name', type=str, help='Cluster name.') # arguments with default parameters parser.add_argument('--hash', default='latest', type=str, help='Hail build to use for notebook initialization (default: %(default)s).') parser.add_argument('--spark', type=str, help='Spark version used to build Hail (default: 2.4.0 for 0.2 and 2.0.2 for 0.1)') parser.add_argument('--version', default='0.2', type=str, choices=['0.1', '0.2'], help='Hail version to use (default: %(default)s).') parser.add_argument('--master-machine-type', '--master', '-m', default='n1-highmem-8', type=str, help='Master machine type (default: %(default)s).') parser.add_argument('--master-memory-fraction', default=0.8, type=float, help='Fraction of master memory allocated to the JVM. ' 'Use a smaller value to reserve more memory ' 'for Python. (default: %(default)s)') parser.add_argument('--master-boot-disk-size', default=100, type=int, help='Disk size of master machine, in GB (default: %(default)s).') parser.add_argument('--num-master-local-ssds', default=0, type=int, help='Number of local SSDs to attach to the master machine (default: %(default)s).') parser.add_argument('--num-preemptible-workers', '--n-pre-workers', '-p', default=0, type=int, help='Number of preemptible worker machines (default: %(default)s).') parser.add_argument('--num-worker-local-ssds', default=0, type=int, help='Number of local SSDs to attach to each worker machine (default: %(default)s).') parser.add_argument('--num-workers', '--n-workers', '-w', default=2, type=int, help='Number of worker machines (default: %(default)s).') parser.add_argument('--preemptible-worker-boot-disk-size', default=40, type=int, help='Disk size of preemptible machines, in GB (default: %(default)s).') parser.add_argument('--worker-boot-disk-size', default=40, type=int, help='Disk size of worker machines, in GB (default: %(default)s).') parser.add_argument('--worker-machine-type', '--worker', help='Worker machine type (default: n1-standard-8, or n1-highmem-8 with --vep).') parser.add_argument('--zone', default='us-central1-b', help='Compute zone for the cluster (default: %(default)s).') parser.add_argument('--properties', help='Additional configuration properties for the cluster') parser.add_argument('--metadata', help='Comma-separated list of metadata to add: KEY1=VALUE1,KEY2=VALUE2...') parser.add_argument('--packages', '--pkgs', help='Comma-separated list of Python packages to be installed on the master node.') parser.add_argument('--project', help='Google Cloud project to start cluster (defaults to currently set project).') parser.add_argument('--configuration', help='Google Cloud configuration to start cluster (defaults to currently set configuration).') parser.add_argument('--max-idle', type=str, help='If specified, maximum idle time before shutdown (e.g. 60m).') parser.add_argument('--max-age', type=str, help='If specified, maximum age before shutdown (e.g. 60m).') parser.add_argument('--bucket', type=str, help='The Google Cloud Storage bucket to use for cluster staging (just the bucket name, no gs:// prefix).') # specify custom Hail jar and zip parser.add_argument('--jar', help='Hail jar to use for Jupyter notebook.') parser.add_argument('--zip', help='Hail zip to use for Jupyter notebook.') # initialization action flags parser.add_argument('--init', default='', help='Comma-separated list of init scripts to run.') parser.add_argument('--init_timeout', default='20m', help='Flag to specify a timeout period for the initialization action') parser.add_argument('--vep', action='store_true', help='Configure the cluster to run VEP.') parser.add_argument('--vep-reference', default='GRCh37', help='Set the reference genome version for VEP.', choices=['GRCh37', 'GRCh38']) parser.add_argument('--dry-run', action='store_true', help="Print gcloud dataproc command, but don't run it.") # custom config file parser.add_argument('--config-file', help='Pass in a custom json file to load configurations.') def main(args): if not args.spark: args.spark = '2.4.0' if args.version == '0.2' else '2.0.2' if args.hash == 'latest': hash = latest_sha(args.version, args.spark) else: hash_length = len(args.hash) if hash_length < 12: raise ValueError('--hash expects a 12 character git commit hash, received {}'.format(args.hash)) elif hash_length > 12: print('--hash expects a 12 character git commit hash, I will truncate this longer hash to tweleve characters: {}'.format(args.hash), file=sys.stderr) hash = args.hash[0:12] else: hash = args.hash if not args.config_file: conf = load_config(hash, args.version) else: conf = load_config_file(args.config_file) if args.spark not in conf.vars['supported_spark'].keys(): sys.stderr.write("ERROR: Hail version '{}' requires one of Spark {}." .format(args.version, ','.join(conf.vars['supported_spark'].keys()))) sys.exit(1) conf.configure(hash, args.spark) # parse Spark and HDFS configuration parameters, combine into properties argument conf.extend_flag('properties', { 'dataproc:dataproc.logging.stackdriver.enable': 'false', 'dataproc:dataproc.monitoring.stackdriver.enable': 'false' }) if args.properties: conf.parse_and_extend('properties', args.properties) # default to highmem machines if using VEP if not args.worker_machine_type: args.worker_machine_type = 'n1-highmem-8' if args.vep else 'n1-standard-8' # default initialization script to start up cluster with conf.extend_flag('initialization-actions', ['gs://dataproc-initialization-actions/conda/bootstrap-conda.sh', init_script]) # add VEP init script if args.vep: if args.version == '0.1': vep_init = 'gs://hail-common/vep/vep/vep85-init.sh' else: vep_init = 'gs://hail-common/vep/vep/vep{vep_version}-loftee-1.0-{vep_ref}-init-docker.sh'.format( vep_version=85 if args.vep_reference == 'GRCh37' else 95, vep_ref=args.vep_reference) conf.extend_flag('initialization-actions', [vep_init]) # add custom init scripts if args.init: conf.extend_flag('initialization-actions', args.init.split(',')) if args.jar and args.zip: conf.extend_flag('metadata', {'JAR': args.jar, 'ZIP': args.zip}) elif args.jar or args.zip: sys.stderr.write('ERROR: pass both --jar and --zip or neither') sys.exit(1) if args.metadata: conf.parse_and_extend('metadata', args.metadata) # if Python packages requested, add metadata variable if args.packages: metadata_pkgs = conf.flags['metadata'].get('PKGS') packages = [] split_regex = r'[|,]' if metadata_pkgs: packages.extend(re.split(split_regex, metadata_pkgs)) packages.extend(re.split(split_regex, args.packages)) conf.extend_flag('metadata', {'PKGS': '|'.join(packages)}) conf.vars['driver_memory'] = str(int(machine_mem[args.master_machine_type] * args.master_memory_fraction)) conf.flags['master-machine-type'] = args.master_machine_type conf.flags['master-boot-disk-size'] = '{}GB'.format(args.master_boot_disk_size) conf.flags['num-master-local-ssds'] = args.num_master_local_ssds conf.flags['num-preemptible-workers'] = args.num_preemptible_workers conf.flags['num-worker-local-ssds'] = args.num_worker_local_ssds conf.flags['num-workers'] = args.num_workers conf.flags['preemptible-worker-boot-disk-size']='{}GB'.format(args.preemptible_worker_boot_disk_size) conf.flags['worker-boot-disk-size'] = args.worker_boot_disk_size conf.flags['worker-machine-type'] = args.worker_machine_type conf.flags['zone'] = args.zone conf.flags['initialization-action-timeout'] = args.init_timeout if args.configuration: conf.flags['configuration'] = args.configuration if args.project: conf.flags['project'] = args.project if args.bucket: conf.flags['bucket'] = args.bucket # command to start cluster cmd = conf.get_command(args.name) if args.max_idle or args.max_age: cmd.insert(1, 'beta') if args.max_idle: cmd.append('--max-idle={}'.format(args.max_idle)) if args.max_age: cmd.append('--max-age={}'.format(args.max_age)) # print underlying gcloud command print(' '.join(cmd[:5]) + ' \\\n ' + ' \\\n '.join(cmd[5:])) # spin up cluster if not args.dry_run: print("Starting cluster '{}'...".format(args.name)) check_call(cmd)
mit
phammin1/QaManagement
QaManagement/env/Lib/site-packages/pip/_vendor/requests/packages/chardet/gb2312freq.py
3132
36011
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # GB2312 most frequently used character table # # Char to FreqOrder table , from hz6763 # 512 --> 0.79 -- 0.79 # 1024 --> 0.92 -- 0.13 # 2048 --> 0.98 -- 0.06 # 6768 --> 1.00 -- 0.02 # # Ideal Distribution Ratio = 0.79135/(1-0.79135) = 3.79 # Random Distribution Ration = 512 / (3755 - 512) = 0.157 # # Typical Distribution Ratio about 25% of Ideal one, still much higher that RDR GB2312_TYPICAL_DISTRIBUTION_RATIO = 0.9 GB2312_TABLE_SIZE = 3760 GB2312CharToFreqOrder = ( 1671, 749,1443,2364,3924,3807,2330,3921,1704,3463,2691,1511,1515, 572,3191,2205, 2361, 224,2558, 479,1711, 963,3162, 440,4060,1905,2966,2947,3580,2647,3961,3842, 2204, 869,4207, 970,2678,5626,2944,2956,1479,4048, 514,3595, 588,1346,2820,3409, 249,4088,1746,1873,2047,1774, 581,1813, 358,1174,3590,1014,1561,4844,2245, 670, 1636,3112, 889,1286, 953, 556,2327,3060,1290,3141, 613, 185,3477,1367, 850,3820, 1715,2428,2642,2303,2732,3041,2562,2648,3566,3946,1349, 388,3098,2091,1360,3585, 152,1687,1539, 738,1559, 59,1232,2925,2267,1388,1249,1741,1679,2960, 151,1566, 1125,1352,4271, 924,4296, 385,3166,4459, 310,1245,2850, 70,3285,2729,3534,3575, 2398,3298,3466,1960,2265, 217,3647, 864,1909,2084,4401,2773,1010,3269,5152, 853, 3051,3121,1244,4251,1895, 364,1499,1540,2313,1180,3655,2268, 562, 715,2417,3061, 544, 336,3768,2380,1752,4075, 950, 280,2425,4382, 183,2759,3272, 333,4297,2155, 1688,2356,1444,1039,4540, 736,1177,3349,2443,2368,2144,2225, 565, 196,1482,3406, 927,1335,4147, 692, 878,1311,1653,3911,3622,1378,4200,1840,2969,3149,2126,1816, 2534,1546,2393,2760, 737,2494, 13, 447, 245,2747, 38,2765,2129,2589,1079, 606, 360, 471,3755,2890, 404, 848, 699,1785,1236, 370,2221,1023,3746,2074,2026,2023, 2388,1581,2119, 812,1141,3091,2536,1519, 804,2053, 406,1596,1090, 784, 548,4414, 1806,2264,2936,1100, 343,4114,5096, 622,3358, 743,3668,1510,1626,5020,3567,2513, 3195,4115,5627,2489,2991, 24,2065,2697,1087,2719, 48,1634, 315, 68, 985,2052, 198,2239,1347,1107,1439, 597,2366,2172, 871,3307, 919,2487,2790,1867, 236,2570, 1413,3794, 906,3365,3381,1701,1982,1818,1524,2924,1205, 616,2586,2072,2004, 575, 253,3099, 32,1365,1182, 197,1714,2454,1201, 554,3388,3224,2748, 756,2587, 250, 2567,1507,1517,3529,1922,2761,2337,3416,1961,1677,2452,2238,3153, 615, 911,1506, 1474,2495,1265,1906,2749,3756,3280,2161, 898,2714,1759,3450,2243,2444, 563, 26, 3286,2266,3769,3344,2707,3677, 611,1402, 531,1028,2871,4548,1375, 261,2948, 835, 1190,4134, 353, 840,2684,1900,3082,1435,2109,1207,1674, 329,1872,2781,4055,2686, 2104, 608,3318,2423,2957,2768,1108,3739,3512,3271,3985,2203,1771,3520,1418,2054, 1681,1153, 225,1627,2929, 162,2050,2511,3687,1954, 124,1859,2431,1684,3032,2894, 585,4805,3969,2869,2704,2088,2032,2095,3656,2635,4362,2209, 256, 518,2042,2105, 3777,3657, 643,2298,1148,1779, 190, 989,3544, 414, 11,2135,2063,2979,1471, 403, 3678, 126, 770,1563, 671,2499,3216,2877, 600,1179, 307,2805,4937,1268,1297,2694, 252,4032,1448,1494,1331,1394, 127,2256, 222,1647,1035,1481,3056,1915,1048, 873, 3651, 210, 33,1608,2516, 200,1520, 415, 102, 0,3389,1287, 817, 91,3299,2940, 836,1814, 549,2197,1396,1669,2987,3582,2297,2848,4528,1070, 687, 20,1819, 121, 1552,1364,1461,1968,2617,3540,2824,2083, 177, 948,4938,2291, 110,4549,2066, 648, 3359,1755,2110,2114,4642,4845,1693,3937,3308,1257,1869,2123, 208,1804,3159,2992, 2531,2549,3361,2418,1350,2347,2800,2568,1291,2036,2680, 72, 842,1990, 212,1233, 1154,1586, 75,2027,3410,4900,1823,1337,2710,2676, 728,2810,1522,3026,4995, 157, 755,1050,4022, 710, 785,1936,2194,2085,1406,2777,2400, 150,1250,4049,1206, 807, 1910, 534, 529,3309,1721,1660, 274, 39,2827, 661,2670,1578, 925,3248,3815,1094, 4278,4901,4252, 41,1150,3747,2572,2227,4501,3658,4902,3813,3357,3617,2884,2258, 887, 538,4187,3199,1294,2439,3042,2329,2343,2497,1255, 107, 543,1527, 521,3478, 3568, 194,5062, 15, 961,3870,1241,1192,2664, 66,5215,3260,2111,1295,1127,2152, 3805,4135, 901,1164,1976, 398,1278, 530,1460, 748, 904,1054,1966,1426, 53,2909, 509, 523,2279,1534, 536,1019, 239,1685, 460,2353, 673,1065,2401,3600,4298,2272, 1272,2363, 284,1753,3679,4064,1695, 81, 815,2677,2757,2731,1386, 859, 500,4221, 2190,2566, 757,1006,2519,2068,1166,1455, 337,2654,3203,1863,1682,1914,3025,1252, 1409,1366, 847, 714,2834,2038,3209, 964,2970,1901, 885,2553,1078,1756,3049, 301, 1572,3326, 688,2130,1996,2429,1805,1648,2930,3421,2750,3652,3088, 262,1158,1254, 389,1641,1812, 526,1719, 923,2073,1073,1902, 468, 489,4625,1140, 857,2375,3070, 3319,2863, 380, 116,1328,2693,1161,2244, 273,1212,1884,2769,3011,1775,1142, 461, 3066,1200,2147,2212, 790, 702,2695,4222,1601,1058, 434,2338,5153,3640, 67,2360, 4099,2502, 618,3472,1329, 416,1132, 830,2782,1807,2653,3211,3510,1662, 192,2124, 296,3979,1739,1611,3684, 23, 118, 324, 446,1239,1225, 293,2520,3814,3795,2535, 3116, 17,1074, 467,2692,2201, 387,2922, 45,1326,3055,1645,3659,2817, 958, 243, 1903,2320,1339,2825,1784,3289, 356, 576, 865,2315,2381,3377,3916,1088,3122,1713, 1655, 935, 628,4689,1034,1327, 441, 800, 720, 894,1979,2183,1528,5289,2702,1071, 4046,3572,2399,1571,3281, 79, 761,1103, 327, 134, 758,1899,1371,1615, 879, 442, 215,2605,2579, 173,2048,2485,1057,2975,3317,1097,2253,3801,4263,1403,1650,2946, 814,4968,3487,1548,2644,1567,1285, 2, 295,2636, 97, 946,3576, 832, 141,4257, 3273, 760,3821,3521,3156,2607, 949,1024,1733,1516,1803,1920,2125,2283,2665,3180, 1501,2064,3560,2171,1592, 803,3518,1416, 732,3897,4258,1363,1362,2458, 119,1427, 602,1525,2608,1605,1639,3175, 694,3064, 10, 465, 76,2000,4846,4208, 444,3781, 1619,3353,2206,1273,3796, 740,2483, 320,1723,2377,3660,2619,1359,1137,1762,1724, 2345,2842,1850,1862, 912, 821,1866, 612,2625,1735,2573,3369,1093, 844, 89, 937, 930,1424,3564,2413,2972,1004,3046,3019,2011, 711,3171,1452,4178, 428, 801,1943, 432, 445,2811, 206,4136,1472, 730, 349, 73, 397,2802,2547, 998,1637,1167, 789, 396,3217, 154,1218, 716,1120,1780,2819,4826,1931,3334,3762,2139,1215,2627, 552, 3664,3628,3232,1405,2383,3111,1356,2652,3577,3320,3101,1703, 640,1045,1370,1246, 4996, 371,1575,2436,1621,2210, 984,4033,1734,2638, 16,4529, 663,2755,3255,1451, 3917,2257,1253,1955,2234,1263,2951, 214,1229, 617, 485, 359,1831,1969, 473,2310, 750,2058, 165, 80,2864,2419, 361,4344,2416,2479,1134, 796,3726,1266,2943, 860, 2715, 938, 390,2734,1313,1384, 248, 202, 877,1064,2854, 522,3907, 279,1602, 297, 2357, 395,3740, 137,2075, 944,4089,2584,1267,3802, 62,1533,2285, 178, 176, 780, 2440, 201,3707, 590, 478,1560,4354,2117,1075, 30, 74,4643,4004,1635,1441,2745, 776,2596, 238,1077,1692,1912,2844, 605, 499,1742,3947, 241,3053, 980,1749, 936, 2640,4511,2582, 515,1543,2162,5322,2892,2993, 890,2148,1924, 665,1827,3581,1032, 968,3163, 339,1044,1896, 270, 583,1791,1720,4367,1194,3488,3669, 43,2523,1657, 163,2167, 290,1209,1622,3378, 550, 634,2508,2510, 695,2634,2384,2512,1476,1414, 220,1469,2341,2138,2852,3183,2900,4939,2865,3502,1211,3680, 854,3227,1299,2976, 3172, 186,2998,1459, 443,1067,3251,1495, 321,1932,3054, 909, 753,1410,1828, 436, 2441,1119,1587,3164,2186,1258, 227, 231,1425,1890,3200,3942, 247, 959, 725,5254, 2741, 577,2158,2079, 929, 120, 174, 838,2813, 591,1115, 417,2024, 40,3240,1536, 1037, 291,4151,2354, 632,1298,2406,2500,3535,1825,1846,3451, 205,1171, 345,4238, 18,1163, 811, 685,2208,1217, 425,1312,1508,1175,4308,2552,1033, 587,1381,3059, 2984,3482, 340,1316,4023,3972, 792,3176, 519, 777,4690, 918, 933,4130,2981,3741, 90,3360,2911,2200,5184,4550, 609,3079,2030, 272,3379,2736, 363,3881,1130,1447, 286, 779, 357,1169,3350,3137,1630,1220,2687,2391, 747,1277,3688,2618,2682,2601, 1156,3196,5290,4034,3102,1689,3596,3128, 874, 219,2783, 798, 508,1843,2461, 269, 1658,1776,1392,1913,2983,3287,2866,2159,2372, 829,4076, 46,4253,2873,1889,1894, 915,1834,1631,2181,2318, 298, 664,2818,3555,2735, 954,3228,3117, 527,3511,2173, 681,2712,3033,2247,2346,3467,1652, 155,2164,3382, 113,1994, 450, 899, 494, 994, 1237,2958,1875,2336,1926,3727, 545,1577,1550, 633,3473, 204,1305,3072,2410,1956, 2471, 707,2134, 841,2195,2196,2663,3843,1026,4940, 990,3252,4997, 368,1092, 437, 3212,3258,1933,1829, 675,2977,2893, 412, 943,3723,4644,3294,3283,2230,2373,5154, 2389,2241,2661,2323,1404,2524, 593, 787, 677,3008,1275,2059, 438,2709,2609,2240, 2269,2246,1446, 36,1568,1373,3892,1574,2301,1456,3962, 693,2276,5216,2035,1143, 2720,1919,1797,1811,2763,4137,2597,1830,1699,1488,1198,2090, 424,1694, 312,3634, 3390,4179,3335,2252,1214, 561,1059,3243,2295,2561, 975,5155,2321,2751,3772, 472, 1537,3282,3398,1047,2077,2348,2878,1323,3340,3076, 690,2906, 51, 369, 170,3541, 1060,2187,2688,3670,2541,1083,1683, 928,3918, 459, 109,4427, 599,3744,4286, 143, 2101,2730,2490, 82,1588,3036,2121, 281,1860, 477,4035,1238,2812,3020,2716,3312, 1530,2188,2055,1317, 843, 636,1808,1173,3495, 649, 181,1002, 147,3641,1159,2414, 3750,2289,2795, 813,3123,2610,1136,4368, 5,3391,4541,2174, 420, 429,1728, 754, 1228,2115,2219, 347,2223,2733, 735,1518,3003,2355,3134,1764,3948,3329,1888,2424, 1001,1234,1972,3321,3363,1672,1021,1450,1584, 226, 765, 655,2526,3404,3244,2302, 3665, 731, 594,2184, 319,1576, 621, 658,2656,4299,2099,3864,1279,2071,2598,2739, 795,3086,3699,3908,1707,2352,2402,1382,3136,2475,1465,4847,3496,3865,1085,3004, 2591,1084, 213,2287,1963,3565,2250, 822, 793,4574,3187,1772,1789,3050, 595,1484, 1959,2770,1080,2650, 456, 422,2996, 940,3322,4328,4345,3092,2742, 965,2784, 739, 4124, 952,1358,2498,2949,2565, 332,2698,2378, 660,2260,2473,4194,3856,2919, 535, 1260,2651,1208,1428,1300,1949,1303,2942, 433,2455,2450,1251,1946, 614,1269, 641, 1306,1810,2737,3078,2912, 564,2365,1419,1415,1497,4460,2367,2185,1379,3005,1307, 3218,2175,1897,3063, 682,1157,4040,4005,1712,1160,1941,1399, 394, 402,2952,1573, 1151,2986,2404, 862, 299,2033,1489,3006, 346, 171,2886,3401,1726,2932, 168,2533, 47,2507,1030,3735,1145,3370,1395,1318,1579,3609,4560,2857,4116,1457,2529,1965, 504,1036,2690,2988,2405, 745,5871, 849,2397,2056,3081, 863,2359,3857,2096, 99, 1397,1769,2300,4428,1643,3455,1978,1757,3718,1440, 35,4879,3742,1296,4228,2280, 160,5063,1599,2013, 166, 520,3479,1646,3345,3012, 490,1937,1545,1264,2182,2505, 1096,1188,1369,1436,2421,1667,2792,2460,1270,2122, 727,3167,2143, 806,1706,1012, 1800,3037, 960,2218,1882, 805, 139,2456,1139,1521, 851,1052,3093,3089, 342,2039, 744,5097,1468,1502,1585,2087, 223, 939, 326,2140,2577, 892,2481,1623,4077, 982, 3708, 135,2131, 87,2503,3114,2326,1106, 876,1616, 547,2997,2831,2093,3441,4530, 4314, 9,3256,4229,4148, 659,1462,1986,1710,2046,2913,2231,4090,4880,5255,3392, 3274,1368,3689,4645,1477, 705,3384,3635,1068,1529,2941,1458,3782,1509, 100,1656, 2548, 718,2339, 408,1590,2780,3548,1838,4117,3719,1345,3530, 717,3442,2778,3220, 2898,1892,4590,3614,3371,2043,1998,1224,3483, 891, 635, 584,2559,3355, 733,1766, 1729,1172,3789,1891,2307, 781,2982,2271,1957,1580,5773,2633,2005,4195,3097,1535, 3213,1189,1934,5693,3262, 586,3118,1324,1598, 517,1564,2217,1868,1893,4445,3728, 2703,3139,1526,1787,1992,3882,2875,1549,1199,1056,2224,1904,2711,5098,4287, 338, 1993,3129,3489,2689,1809,2815,1997, 957,1855,3898,2550,3275,3057,1105,1319, 627, 1505,1911,1883,3526, 698,3629,3456,1833,1431, 746, 77,1261,2017,2296,1977,1885, 125,1334,1600, 525,1798,1109,2222,1470,1945, 559,2236,1186,3443,2476,1929,1411, 2411,3135,1777,3372,2621,1841,1613,3229, 668,1430,1839,2643,2916, 195,1989,2671, 2358,1387, 629,3205,2293,5256,4439, 123,1310, 888,1879,4300,3021,3605,1003,1162, 3192,2910,2010, 140,2395,2859, 55,1082,2012,2901, 662, 419,2081,1438, 680,2774, 4654,3912,1620,1731,1625,5035,4065,2328, 512,1344, 802,5443,2163,2311,2537, 524, 3399, 98,1155,2103,1918,2606,3925,2816,1393,2465,1504,3773,2177,3963,1478,4346, 180,1113,4655,3461,2028,1698, 833,2696,1235,1322,1594,4408,3623,3013,3225,2040, 3022, 541,2881, 607,3632,2029,1665,1219, 639,1385,1686,1099,2803,3231,1938,3188, 2858, 427, 676,2772,1168,2025, 454,3253,2486,3556, 230,1950, 580, 791,1991,1280, 1086,1974,2034, 630, 257,3338,2788,4903,1017, 86,4790, 966,2789,1995,1696,1131, 259,3095,4188,1308, 179,1463,5257, 289,4107,1248, 42,3413,1725,2288, 896,1947, 774,4474,4254, 604,3430,4264, 392,2514,2588, 452, 237,1408,3018, 988,4531,1970, 3034,3310, 540,2370,1562,1288,2990, 502,4765,1147, 4,1853,2708, 207, 294,2814, 4078,2902,2509, 684, 34,3105,3532,2551, 644, 709,2801,2344, 573,1727,3573,3557, 2021,1081,3100,4315,2100,3681, 199,2263,1837,2385, 146,3484,1195,2776,3949, 997, 1939,3973,1008,1091,1202,1962,1847,1149,4209,5444,1076, 493, 117,5400,2521, 972, 1490,2934,1796,4542,2374,1512,2933,2657, 413,2888,1135,2762,2314,2156,1355,2369, 766,2007,2527,2170,3124,2491,2593,2632,4757,2437, 234,3125,3591,1898,1750,1376, 1942,3468,3138, 570,2127,2145,3276,4131, 962, 132,1445,4196, 19, 941,3624,3480, 3366,1973,1374,4461,3431,2629, 283,2415,2275, 808,2887,3620,2112,2563,1353,3610, 955,1089,3103,1053, 96, 88,4097, 823,3808,1583, 399, 292,4091,3313, 421,1128, 642,4006, 903,2539,1877,2082, 596, 29,4066,1790, 722,2157, 130, 995,1569, 769, 1485, 464, 513,2213, 288,1923,1101,2453,4316, 133, 486,2445, 50, 625, 487,2207, 57, 423, 481,2962, 159,3729,1558, 491, 303, 482, 501, 240,2837, 112,3648,2392, 1783, 362, 8,3433,3422, 610,2793,3277,1390,1284,1654, 21,3823, 734, 367, 623, 193, 287, 374,1009,1483, 816, 476, 313,2255,2340,1262,2150,2899,1146,2581, 782, 2116,1659,2018,1880, 255,3586,3314,1110,2867,2137,2564, 986,2767,5185,2006, 650, 158, 926, 762, 881,3157,2717,2362,3587, 306,3690,3245,1542,3077,2427,1691,2478, 2118,2985,3490,2438, 539,2305, 983, 129,1754, 355,4201,2386, 827,2923, 104,1773, 2838,2771, 411,2905,3919, 376, 767, 122,1114, 828,2422,1817,3506, 266,3460,1007, 1609,4998, 945,2612,4429,2274, 726,1247,1964,2914,2199,2070,4002,4108, 657,3323, 1422, 579, 455,2764,4737,1222,2895,1670, 824,1223,1487,2525, 558, 861,3080, 598, 2659,2515,1967, 752,2583,2376,2214,4180, 977, 704,2464,4999,2622,4109,1210,2961, 819,1541, 142,2284, 44, 418, 457,1126,3730,4347,4626,1644,1876,3671,1864, 302, 1063,5694, 624, 723,1984,3745,1314,1676,2488,1610,1449,3558,3569,2166,2098, 409, 1011,2325,3704,2306, 818,1732,1383,1824,1844,3757, 999,2705,3497,1216,1423,2683, 2426,2954,2501,2726,2229,1475,2554,5064,1971,1794,1666,2014,1343, 783, 724, 191, 2434,1354,2220,5065,1763,2752,2472,4152, 131, 175,2885,3434, 92,1466,4920,2616, 3871,3872,3866, 128,1551,1632, 669,1854,3682,4691,4125,1230, 188,2973,3290,1302, 1213, 560,3266, 917, 763,3909,3249,1760, 868,1958, 764,1782,2097, 145,2277,3774, 4462, 64,1491,3062, 971,2132,3606,2442, 221,1226,1617, 218, 323,1185,3207,3147, 571, 619,1473,1005,1744,2281, 449,1887,2396,3685, 275, 375,3816,1743,3844,3731, 845,1983,2350,4210,1377, 773, 967,3499,3052,3743,2725,4007,1697,1022,3943,1464, 3264,2855,2722,1952,1029,2839,2467, 84,4383,2215, 820,1391,2015,2448,3672, 377, 1948,2168, 797,2545,3536,2578,2645, 94,2874,1678, 405,1259,3071, 771, 546,1315, 470,1243,3083, 895,2468, 981, 969,2037, 846,4181, 653,1276,2928, 14,2594, 557, 3007,2474, 156, 902,1338,1740,2574, 537,2518, 973,2282,2216,2433,1928, 138,2903, 1293,2631,1612, 646,3457, 839,2935, 111, 496,2191,2847, 589,3186, 149,3994,2060, 4031,2641,4067,3145,1870, 37,3597,2136,1025,2051,3009,3383,3549,1121,1016,3261, 1301, 251,2446,2599,2153, 872,3246, 637, 334,3705, 831, 884, 921,3065,3140,4092, 2198,1944, 246,2964, 108,2045,1152,1921,2308,1031, 203,3173,4170,1907,3890, 810, 1401,2003,1690, 506, 647,1242,2828,1761,1649,3208,2249,1589,3709,2931,5156,1708, 498, 666,2613, 834,3817,1231, 184,2851,1124, 883,3197,2261,3710,1765,1553,2658, 1178,2639,2351, 93,1193, 942,2538,2141,4402, 235,1821, 870,1591,2192,1709,1871, 3341,1618,4126,2595,2334, 603, 651, 69, 701, 268,2662,3411,2555,1380,1606, 503, 448, 254,2371,2646, 574,1187,2309,1770, 322,2235,1292,1801, 305, 566,1133, 229, 2067,2057, 706, 167, 483,2002,2672,3295,1820,3561,3067, 316, 378,2746,3452,1112, 136,1981, 507,1651,2917,1117, 285,4591, 182,2580,3522,1304, 335,3303,1835,2504, 1795,1792,2248, 674,1018,2106,2449,1857,2292,2845, 976,3047,1781,2600,2727,1389, 1281, 52,3152, 153, 265,3950, 672,3485,3951,4463, 430,1183, 365, 278,2169, 27, 1407,1336,2304, 209,1340,1730,2202,1852,2403,2883, 979,1737,1062, 631,2829,2542, 3876,2592, 825,2086,2226,3048,3625, 352,1417,3724, 542, 991, 431,1351,3938,1861, 2294, 826,1361,2927,3142,3503,1738, 463,2462,2723, 582,1916,1595,2808, 400,3845, 3891,2868,3621,2254, 58,2492,1123, 910,2160,2614,1372,1603,1196,1072,3385,1700, 3267,1980, 696, 480,2430, 920, 799,1570,2920,1951,2041,4047,2540,1321,4223,2469, 3562,2228,1271,2602, 401,2833,3351,2575,5157, 907,2312,1256, 410, 263,3507,1582, 996, 678,1849,2316,1480, 908,3545,2237, 703,2322, 667,1826,2849,1531,2604,2999, 2407,3146,2151,2630,1786,3711, 469,3542, 497,3899,2409, 858, 837,4446,3393,1274, 786, 620,1845,2001,3311, 484, 308,3367,1204,1815,3691,2332,1532,2557,1842,2020, 2724,1927,2333,4440, 567, 22,1673,2728,4475,1987,1858,1144,1597, 101,1832,3601, 12, 974,3783,4391, 951,1412, 1,3720, 453,4608,4041, 528,1041,1027,3230,2628, 1129, 875,1051,3291,1203,2262,1069,2860,2799,2149,2615,3278, 144,1758,3040, 31, 475,1680, 366,2685,3184, 311,1642,4008,2466,5036,1593,1493,2809, 216,1420,1668, 233, 304,2128,3284, 232,1429,1768,1040,2008,3407,2740,2967,2543, 242,2133, 778, 1565,2022,2620, 505,2189,2756,1098,2273, 372,1614, 708, 553,2846,2094,2278, 169, 3626,2835,4161, 228,2674,3165, 809,1454,1309, 466,1705,1095, 900,3423, 880,2667, 3751,5258,2317,3109,2571,4317,2766,1503,1342, 866,4447,1118, 63,2076, 314,1881, 1348,1061, 172, 978,3515,1747, 532, 511,3970, 6, 601, 905,2699,3300,1751, 276, 1467,3725,2668, 65,4239,2544,2779,2556,1604, 578,2451,1802, 992,2331,2624,1320, 3446, 713,1513,1013, 103,2786,2447,1661, 886,1702, 916, 654,3574,2031,1556, 751, 2178,2821,2179,1498,1538,2176, 271, 914,2251,2080,1325, 638,1953,2937,3877,2432, 2754, 95,3265,1716, 260,1227,4083, 775, 106,1357,3254, 426,1607, 555,2480, 772, 1985, 244,2546, 474, 495,1046,2611,1851,2061, 71,2089,1675,2590, 742,3758,2843, 3222,1433, 267,2180,2576,2826,2233,2092,3913,2435, 956,1745,3075, 856,2113,1116, 451, 3,1988,2896,1398, 993,2463,1878,2049,1341,2718,2721,2870,2108, 712,2904, 4363,2753,2324, 277,2872,2349,2649, 384, 987, 435, 691,3000, 922, 164,3939, 652, 1500,1184,4153,2482,3373,2165,4848,2335,3775,3508,3154,2806,2830,1554,2102,1664, 2530,1434,2408, 893,1547,2623,3447,2832,2242,2532,3169,2856,3223,2078, 49,3770, 3469, 462, 318, 656,2259,3250,3069, 679,1629,2758, 344,1138,1104,3120,1836,1283, 3115,2154,1437,4448, 934, 759,1999, 794,2862,1038, 533,2560,1722,2342, 855,2626, 1197,1663,4476,3127, 85,4240,2528, 25,1111,1181,3673, 407,3470,4561,2679,2713, 768,1925,2841,3986,1544,1165, 932, 373,1240,2146,1930,2673, 721,4766, 354,4333, 391,2963, 187, 61,3364,1442,1102, 330,1940,1767, 341,3809,4118, 393,2496,2062, 2211, 105, 331, 300, 439, 913,1332, 626, 379,3304,1557, 328, 689,3952, 309,1555, 931, 317,2517,3027, 325, 569, 686,2107,3084, 60,1042,1333,2794, 264,3177,4014, 1628, 258,3712, 7,4464,1176,1043,1778, 683, 114,1975, 78,1492, 383,1886, 510, 386, 645,5291,2891,2069,3305,4138,3867,2939,2603,2493,1935,1066,1848,3588,1015, 1282,1289,4609, 697,1453,3044,2666,3611,1856,2412, 54, 719,1330, 568,3778,2459, 1748, 788, 492, 551,1191,1000, 488,3394,3763, 282,1799, 348,2016,1523,3155,2390, 1049, 382,2019,1788,1170, 729,2968,3523, 897,3926,2785,2938,3292, 350,2319,3238, 1718,1717,2655,3453,3143,4465, 161,2889,2980,2009,1421, 56,1908,1640,2387,2232, 1917,1874,2477,4921, 148, 83,3438, 592,4245,2882,1822,1055, 741, 115,1496,1624, 381,1638,4592,1020, 516,3214, 458, 947,4575,1432, 211,1514,2926,1865,2142, 189, 852,1221,1400,1486, 882,2299,4036, 351, 28,1122, 700,6479,6480,6481,6482,6483, # last 512 #Everything below is of no interest for detection purpose 5508,6484,3900,3414,3974,4441,4024,3537,4037,5628,5099,3633,6485,3148,6486,3636, 5509,3257,5510,5973,5445,5872,4941,4403,3174,4627,5873,6276,2286,4230,5446,5874, 5122,6102,6103,4162,5447,5123,5323,4849,6277,3980,3851,5066,4246,5774,5067,6278, 3001,2807,5695,3346,5775,5974,5158,5448,6487,5975,5976,5776,3598,6279,5696,4806, 4211,4154,6280,6488,6489,6490,6281,4212,5037,3374,4171,6491,4562,4807,4722,4827, 5977,6104,4532,4079,5159,5324,5160,4404,3858,5359,5875,3975,4288,4610,3486,4512, 5325,3893,5360,6282,6283,5560,2522,4231,5978,5186,5449,2569,3878,6284,5401,3578, 4415,6285,4656,5124,5979,2506,4247,4449,3219,3417,4334,4969,4329,6492,4576,4828, 4172,4416,4829,5402,6286,3927,3852,5361,4369,4830,4477,4867,5876,4173,6493,6105, 4657,6287,6106,5877,5450,6494,4155,4868,5451,3700,5629,4384,6288,6289,5878,3189, 4881,6107,6290,6495,4513,6496,4692,4515,4723,5100,3356,6497,6291,3810,4080,5561, 3570,4430,5980,6498,4355,5697,6499,4724,6108,6109,3764,4050,5038,5879,4093,3226, 6292,5068,5217,4693,3342,5630,3504,4831,4377,4466,4309,5698,4431,5777,6293,5778, 4272,3706,6110,5326,3752,4676,5327,4273,5403,4767,5631,6500,5699,5880,3475,5039, 6294,5562,5125,4348,4301,4482,4068,5126,4593,5700,3380,3462,5981,5563,3824,5404, 4970,5511,3825,4738,6295,6501,5452,4516,6111,5881,5564,6502,6296,5982,6503,4213, 4163,3454,6504,6112,4009,4450,6113,4658,6297,6114,3035,6505,6115,3995,4904,4739, 4563,4942,4110,5040,3661,3928,5362,3674,6506,5292,3612,4791,5565,4149,5983,5328, 5259,5021,4725,4577,4564,4517,4364,6298,5405,4578,5260,4594,4156,4157,5453,3592, 3491,6507,5127,5512,4709,4922,5984,5701,4726,4289,6508,4015,6116,5128,4628,3424, 4241,5779,6299,4905,6509,6510,5454,5702,5780,6300,4365,4923,3971,6511,5161,3270, 3158,5985,4100, 867,5129,5703,6117,5363,3695,3301,5513,4467,6118,6512,5455,4232, 4242,4629,6513,3959,4478,6514,5514,5329,5986,4850,5162,5566,3846,4694,6119,5456, 4869,5781,3779,6301,5704,5987,5515,4710,6302,5882,6120,4392,5364,5705,6515,6121, 6516,6517,3736,5988,5457,5989,4695,2457,5883,4551,5782,6303,6304,6305,5130,4971, 6122,5163,6123,4870,3263,5365,3150,4871,6518,6306,5783,5069,5706,3513,3498,4409, 5330,5632,5366,5458,5459,3991,5990,4502,3324,5991,5784,3696,4518,5633,4119,6519, 4630,5634,4417,5707,4832,5992,3418,6124,5993,5567,4768,5218,6520,4595,3458,5367, 6125,5635,6126,4202,6521,4740,4924,6307,3981,4069,4385,6308,3883,2675,4051,3834, 4302,4483,5568,5994,4972,4101,5368,6309,5164,5884,3922,6127,6522,6523,5261,5460, 5187,4164,5219,3538,5516,4111,3524,5995,6310,6311,5369,3181,3386,2484,5188,3464, 5569,3627,5708,6524,5406,5165,4677,4492,6312,4872,4851,5885,4468,5996,6313,5709, 5710,6128,2470,5886,6314,5293,4882,5785,3325,5461,5101,6129,5711,5786,6525,4906, 6526,6527,4418,5887,5712,4808,2907,3701,5713,5888,6528,3765,5636,5331,6529,6530, 3593,5889,3637,4943,3692,5714,5787,4925,6315,6130,5462,4405,6131,6132,6316,5262, 6531,6532,5715,3859,5716,5070,4696,5102,3929,5788,3987,4792,5997,6533,6534,3920, 4809,5000,5998,6535,2974,5370,6317,5189,5263,5717,3826,6536,3953,5001,4883,3190, 5463,5890,4973,5999,4741,6133,6134,3607,5570,6000,4711,3362,3630,4552,5041,6318, 6001,2950,2953,5637,4646,5371,4944,6002,2044,4120,3429,6319,6537,5103,4833,6538, 6539,4884,4647,3884,6003,6004,4758,3835,5220,5789,4565,5407,6540,6135,5294,4697, 4852,6320,6321,3206,4907,6541,6322,4945,6542,6136,6543,6323,6005,4631,3519,6544, 5891,6545,5464,3784,5221,6546,5571,4659,6547,6324,6137,5190,6548,3853,6549,4016, 4834,3954,6138,5332,3827,4017,3210,3546,4469,5408,5718,3505,4648,5790,5131,5638, 5791,5465,4727,4318,6325,6326,5792,4553,4010,4698,3439,4974,3638,4335,3085,6006, 5104,5042,5166,5892,5572,6327,4356,4519,5222,5573,5333,5793,5043,6550,5639,5071, 4503,6328,6139,6551,6140,3914,3901,5372,6007,5640,4728,4793,3976,3836,4885,6552, 4127,6553,4451,4102,5002,6554,3686,5105,6555,5191,5072,5295,4611,5794,5296,6556, 5893,5264,5894,4975,5466,5265,4699,4976,4370,4056,3492,5044,4886,6557,5795,4432, 4769,4357,5467,3940,4660,4290,6141,4484,4770,4661,3992,6329,4025,4662,5022,4632, 4835,4070,5297,4663,4596,5574,5132,5409,5895,6142,4504,5192,4664,5796,5896,3885, 5575,5797,5023,4810,5798,3732,5223,4712,5298,4084,5334,5468,6143,4052,4053,4336, 4977,4794,6558,5335,4908,5576,5224,4233,5024,4128,5469,5225,4873,6008,5045,4729, 4742,4633,3675,4597,6559,5897,5133,5577,5003,5641,5719,6330,6560,3017,2382,3854, 4406,4811,6331,4393,3964,4946,6561,2420,3722,6562,4926,4378,3247,1736,4442,6332, 5134,6333,5226,3996,2918,5470,4319,4003,4598,4743,4744,4485,3785,3902,5167,5004, 5373,4394,5898,6144,4874,1793,3997,6334,4085,4214,5106,5642,4909,5799,6009,4419, 4189,3330,5899,4165,4420,5299,5720,5227,3347,6145,4081,6335,2876,3930,6146,3293, 3786,3910,3998,5900,5300,5578,2840,6563,5901,5579,6147,3531,5374,6564,6565,5580, 4759,5375,6566,6148,3559,5643,6336,6010,5517,6337,6338,5721,5902,3873,6011,6339, 6567,5518,3868,3649,5722,6568,4771,4947,6569,6149,4812,6570,2853,5471,6340,6341, 5644,4795,6342,6012,5723,6343,5724,6013,4349,6344,3160,6150,5193,4599,4514,4493, 5168,4320,6345,4927,3666,4745,5169,5903,5005,4928,6346,5725,6014,4730,4203,5046, 4948,3395,5170,6015,4150,6016,5726,5519,6347,5047,3550,6151,6348,4197,4310,5904, 6571,5581,2965,6152,4978,3960,4291,5135,6572,5301,5727,4129,4026,5905,4853,5728, 5472,6153,6349,4533,2700,4505,5336,4678,3583,5073,2994,4486,3043,4554,5520,6350, 6017,5800,4487,6351,3931,4103,5376,6352,4011,4321,4311,4190,5136,6018,3988,3233, 4350,5906,5645,4198,6573,5107,3432,4191,3435,5582,6574,4139,5410,6353,5411,3944, 5583,5074,3198,6575,6354,4358,6576,5302,4600,5584,5194,5412,6577,6578,5585,5413, 5303,4248,5414,3879,4433,6579,4479,5025,4854,5415,6355,4760,4772,3683,2978,4700, 3797,4452,3965,3932,3721,4910,5801,6580,5195,3551,5907,3221,3471,3029,6019,3999, 5908,5909,5266,5267,3444,3023,3828,3170,4796,5646,4979,4259,6356,5647,5337,3694, 6357,5648,5338,4520,4322,5802,3031,3759,4071,6020,5586,4836,4386,5048,6581,3571, 4679,4174,4949,6154,4813,3787,3402,3822,3958,3215,3552,5268,4387,3933,4950,4359, 6021,5910,5075,3579,6358,4234,4566,5521,6359,3613,5049,6022,5911,3375,3702,3178, 4911,5339,4521,6582,6583,4395,3087,3811,5377,6023,6360,6155,4027,5171,5649,4421, 4249,2804,6584,2270,6585,4000,4235,3045,6156,5137,5729,4140,4312,3886,6361,4330, 6157,4215,6158,3500,3676,4929,4331,3713,4930,5912,4265,3776,3368,5587,4470,4855, 3038,4980,3631,6159,6160,4132,4680,6161,6362,3923,4379,5588,4255,6586,4121,6587, 6363,4649,6364,3288,4773,4774,6162,6024,6365,3543,6588,4274,3107,3737,5050,5803, 4797,4522,5589,5051,5730,3714,4887,5378,4001,4523,6163,5026,5522,4701,4175,2791, 3760,6589,5473,4224,4133,3847,4814,4815,4775,3259,5416,6590,2738,6164,6025,5304, 3733,5076,5650,4816,5590,6591,6165,6592,3934,5269,6593,3396,5340,6594,5804,3445, 3602,4042,4488,5731,5732,3525,5591,4601,5196,6166,6026,5172,3642,4612,3202,4506, 4798,6366,3818,5108,4303,5138,5139,4776,3332,4304,2915,3415,4434,5077,5109,4856, 2879,5305,4817,6595,5913,3104,3144,3903,4634,5341,3133,5110,5651,5805,6167,4057, 5592,2945,4371,5593,6596,3474,4182,6367,6597,6168,4507,4279,6598,2822,6599,4777, 4713,5594,3829,6169,3887,5417,6170,3653,5474,6368,4216,2971,5228,3790,4579,6369, 5733,6600,6601,4951,4746,4555,6602,5418,5475,6027,3400,4665,5806,6171,4799,6028, 5052,6172,3343,4800,4747,5006,6370,4556,4217,5476,4396,5229,5379,5477,3839,5914, 5652,5807,4714,3068,4635,5808,6173,5342,4192,5078,5419,5523,5734,6174,4557,6175, 4602,6371,6176,6603,5809,6372,5735,4260,3869,5111,5230,6029,5112,6177,3126,4681, 5524,5915,2706,3563,4748,3130,6178,4018,5525,6604,6605,5478,4012,4837,6606,4534, 4193,5810,4857,3615,5479,6030,4082,3697,3539,4086,5270,3662,4508,4931,5916,4912, 5811,5027,3888,6607,4397,3527,3302,3798,2775,2921,2637,3966,4122,4388,4028,4054, 1633,4858,5079,3024,5007,3982,3412,5736,6608,3426,3236,5595,3030,6179,3427,3336, 3279,3110,6373,3874,3039,5080,5917,5140,4489,3119,6374,5812,3405,4494,6031,4666, 4141,6180,4166,6032,5813,4981,6609,5081,4422,4982,4112,3915,5653,3296,3983,6375, 4266,4410,5654,6610,6181,3436,5082,6611,5380,6033,3819,5596,4535,5231,5306,5113, 6612,4952,5918,4275,3113,6613,6376,6182,6183,5814,3073,4731,4838,5008,3831,6614, 4888,3090,3848,4280,5526,5232,3014,5655,5009,5737,5420,5527,6615,5815,5343,5173, 5381,4818,6616,3151,4953,6617,5738,2796,3204,4360,2989,4281,5739,5174,5421,5197, 3132,5141,3849,5142,5528,5083,3799,3904,4839,5480,2880,4495,3448,6377,6184,5271, 5919,3771,3193,6034,6035,5920,5010,6036,5597,6037,6378,6038,3106,5422,6618,5423, 5424,4142,6619,4889,5084,4890,4313,5740,6620,3437,5175,5307,5816,4199,5198,5529, 5817,5199,5656,4913,5028,5344,3850,6185,2955,5272,5011,5818,4567,4580,5029,5921, 3616,5233,6621,6622,6186,4176,6039,6379,6380,3352,5200,5273,2908,5598,5234,3837, 5308,6623,6624,5819,4496,4323,5309,5201,6625,6626,4983,3194,3838,4167,5530,5922, 5274,6381,6382,3860,3861,5599,3333,4292,4509,6383,3553,5481,5820,5531,4778,6187, 3955,3956,4324,4389,4218,3945,4325,3397,2681,5923,4779,5085,4019,5482,4891,5382, 5383,6040,4682,3425,5275,4094,6627,5310,3015,5483,5657,4398,5924,3168,4819,6628, 5925,6629,5532,4932,4613,6041,6630,4636,6384,4780,4204,5658,4423,5821,3989,4683, 5822,6385,4954,6631,5345,6188,5425,5012,5384,3894,6386,4490,4104,6632,5741,5053, 6633,5823,5926,5659,5660,5927,6634,5235,5742,5824,4840,4933,4820,6387,4859,5928, 4955,6388,4143,3584,5825,5346,5013,6635,5661,6389,5014,5484,5743,4337,5176,5662, 6390,2836,6391,3268,6392,6636,6042,5236,6637,4158,6638,5744,5663,4471,5347,3663, 4123,5143,4293,3895,6639,6640,5311,5929,5826,3800,6189,6393,6190,5664,5348,3554, 3594,4749,4603,6641,5385,4801,6043,5827,4183,6642,5312,5426,4761,6394,5665,6191, 4715,2669,6643,6644,5533,3185,5427,5086,5930,5931,5386,6192,6044,6645,4781,4013, 5745,4282,4435,5534,4390,4267,6045,5746,4984,6046,2743,6193,3501,4087,5485,5932, 5428,4184,4095,5747,4061,5054,3058,3862,5933,5600,6646,5144,3618,6395,3131,5055, 5313,6396,4650,4956,3855,6194,3896,5202,4985,4029,4225,6195,6647,5828,5486,5829, 3589,3002,6648,6397,4782,5276,6649,6196,6650,4105,3803,4043,5237,5830,6398,4096, 3643,6399,3528,6651,4453,3315,4637,6652,3984,6197,5535,3182,3339,6653,3096,2660, 6400,6654,3449,5934,4250,4236,6047,6401,5831,6655,5487,3753,4062,5832,6198,6199, 6656,3766,6657,3403,4667,6048,6658,4338,2897,5833,3880,2797,3780,4326,6659,5748, 5015,6660,5387,4351,5601,4411,6661,3654,4424,5935,4339,4072,5277,4568,5536,6402, 6662,5238,6663,5349,5203,6200,5204,6201,5145,4536,5016,5056,4762,5834,4399,4957, 6202,6403,5666,5749,6664,4340,6665,5936,5177,5667,6666,6667,3459,4668,6404,6668, 6669,4543,6203,6670,4276,6405,4480,5537,6671,4614,5205,5668,6672,3348,2193,4763, 6406,6204,5937,5602,4177,5669,3419,6673,4020,6205,4443,4569,5388,3715,3639,6407, 6049,4058,6206,6674,5938,4544,6050,4185,4294,4841,4651,4615,5488,6207,6408,6051, 5178,3241,3509,5835,6208,4958,5836,4341,5489,5278,6209,2823,5538,5350,5206,5429, 6675,4638,4875,4073,3516,4684,4914,4860,5939,5603,5389,6052,5057,3237,5490,3791, 6676,6409,6677,4821,4915,4106,5351,5058,4243,5539,4244,5604,4842,4916,5239,3028, 3716,5837,5114,5605,5390,5940,5430,6210,4332,6678,5540,4732,3667,3840,6053,4305, 3408,5670,5541,6410,2744,5240,5750,6679,3234,5606,6680,5607,5671,3608,4283,4159, 4400,5352,4783,6681,6411,6682,4491,4802,6211,6412,5941,6413,6414,5542,5751,6683, 4669,3734,5942,6684,6415,5943,5059,3328,4670,4144,4268,6685,6686,6687,6688,4372, 3603,6689,5944,5491,4373,3440,6416,5543,4784,4822,5608,3792,4616,5838,5672,3514, 5391,6417,4892,6690,4639,6691,6054,5673,5839,6055,6692,6056,5392,6212,4038,5544, 5674,4497,6057,6693,5840,4284,5675,4021,4545,5609,6418,4454,6419,6213,4113,4472, 5314,3738,5087,5279,4074,5610,4959,4063,3179,4750,6058,6420,6214,3476,4498,4716, 5431,4960,4685,6215,5241,6694,6421,6216,6695,5841,5945,6422,3748,5946,5179,3905, 5752,5545,5947,4374,6217,4455,6423,4412,6218,4803,5353,6696,3832,5280,6219,4327, 4702,6220,6221,6059,4652,5432,6424,3749,4751,6425,5753,4986,5393,4917,5948,5030, 5754,4861,4733,6426,4703,6697,6222,4671,5949,4546,4961,5180,6223,5031,3316,5281, 6698,4862,4295,4934,5207,3644,6427,5842,5950,6428,6429,4570,5843,5282,6430,6224, 5088,3239,6060,6699,5844,5755,6061,6431,2701,5546,6432,5115,5676,4039,3993,3327, 4752,4425,5315,6433,3941,6434,5677,4617,4604,3074,4581,6225,5433,6435,6226,6062, 4823,5756,5116,6227,3717,5678,4717,5845,6436,5679,5846,6063,5847,6064,3977,3354, 6437,3863,5117,6228,5547,5394,4499,4524,6229,4605,6230,4306,4500,6700,5951,6065, 3693,5952,5089,4366,4918,6701,6231,5548,6232,6702,6438,4704,5434,6703,6704,5953, 4168,6705,5680,3420,6706,5242,4407,6066,3812,5757,5090,5954,4672,4525,3481,5681, 4618,5395,5354,5316,5955,6439,4962,6707,4526,6440,3465,4673,6067,6441,5682,6708, 5435,5492,5758,5683,4619,4571,4674,4804,4893,4686,5493,4753,6233,6068,4269,6442, 6234,5032,4705,5146,5243,5208,5848,6235,6443,4963,5033,4640,4226,6236,5849,3387, 6444,6445,4436,4437,5850,4843,5494,4785,4894,6709,4361,6710,5091,5956,3331,6237, 4987,5549,6069,6711,4342,3517,4473,5317,6070,6712,6071,4706,6446,5017,5355,6713, 6714,4988,5436,6447,4734,5759,6715,4735,4547,4456,4754,6448,5851,6449,6450,3547, 5852,5318,6451,6452,5092,4205,6716,6238,4620,4219,5611,6239,6072,4481,5760,5957, 5958,4059,6240,6453,4227,4537,6241,5761,4030,4186,5244,5209,3761,4457,4876,3337, 5495,5181,6242,5959,5319,5612,5684,5853,3493,5854,6073,4169,5613,5147,4895,6074, 5210,6717,5182,6718,3830,6243,2798,3841,6075,6244,5855,5614,3604,4606,5496,5685, 5118,5356,6719,6454,5960,5357,5961,6720,4145,3935,4621,5119,5962,4261,6721,6455, 4786,5963,4375,4582,6245,6246,6247,6076,5437,4877,5856,3376,4380,6248,4160,6722, 5148,6456,5211,6457,6723,4718,6458,6724,6249,5358,4044,3297,6459,6250,5857,5615, 5497,5245,6460,5498,6725,6251,6252,5550,3793,5499,2959,5396,6461,6462,4572,5093, 5500,5964,3806,4146,6463,4426,5762,5858,6077,6253,4755,3967,4220,5965,6254,4989, 5501,6464,4352,6726,6078,4764,2290,5246,3906,5438,5283,3767,4964,2861,5763,5094, 6255,6256,4622,5616,5859,5860,4707,6727,4285,4708,4824,5617,6257,5551,4787,5212, 4965,4935,4687,6465,6728,6466,5686,6079,3494,4413,2995,5247,5966,5618,6729,5967, 5764,5765,5687,5502,6730,6731,6080,5397,6467,4990,6258,6732,4538,5060,5619,6733, 4719,5688,5439,5018,5149,5284,5503,6734,6081,4607,6259,5120,3645,5861,4583,6260, 4584,4675,5620,4098,5440,6261,4863,2379,3306,4585,5552,5689,4586,5285,6735,4864, 6736,5286,6082,6737,4623,3010,4788,4381,4558,5621,4587,4896,3698,3161,5248,4353, 4045,6262,3754,5183,4588,6738,6263,6739,6740,5622,3936,6741,6468,6742,6264,5095, 6469,4991,5968,6743,4992,6744,6083,4897,6745,4256,5766,4307,3108,3968,4444,5287, 3889,4343,6084,4510,6085,4559,6086,4898,5969,6746,5623,5061,4919,5249,5250,5504, 5441,6265,5320,4878,3242,5862,5251,3428,6087,6747,4237,5624,5442,6266,5553,4539, 6748,2585,3533,5398,4262,6088,5150,4736,4438,6089,6267,5505,4966,6749,6268,6750, 6269,5288,5554,3650,6090,6091,4624,6092,5690,6751,5863,4270,5691,4277,5555,5864, 6752,5692,4720,4865,6470,5151,4688,4825,6753,3094,6754,6471,3235,4653,6755,5213, 5399,6756,3201,4589,5865,4967,6472,5866,6473,5019,3016,6757,5321,4756,3957,4573, 6093,4993,5767,4721,6474,6758,5625,6759,4458,6475,6270,6760,5556,4994,5214,5252, 6271,3875,5768,6094,5034,5506,4376,5769,6761,2120,6476,5253,5770,6762,5771,5970, 3990,5971,5557,5558,5772,6477,6095,2787,4641,5972,5121,6096,6097,6272,6763,3703, 5867,5507,6273,4206,6274,4789,6098,6764,3619,3646,3833,3804,2394,3788,4936,3978, 4866,4899,6099,6100,5559,6478,6765,3599,5868,6101,5869,5870,6275,6766,4527,6767) # flake8: noqa
mit
jrmontag/Data-Science-45min-Intros
python_multiprocessing/run_3.py
25
1120
#!/usr/bin/env python from multiprocessing import Process, Queue import time def bad_ass_function(**kwargs): n = int(kwargs["n"]) q = kwargs["queue"] t = time.time u = t() + n while t() < u: pass return_str = "finished {}s of badass-ery".format(n) q.put(return_str) def dump_queue(q): print("emptying queue:") while not q.empty(): print(q.get()) print("queue is empty") if __name__ == "__main__": n = 3 queue = Queue() # Process takes keyword args: target=function_name, args=function_args_tuple, kwargs=function_kwargs_dict p1 = Process(target=bad_ass_function,kwargs={"n":n,"queue":queue}) # calls "p.run" in a new thread #p1.start() # block this thread until p1 terminates #p1.join() # create two new Process objects #n = 5 #p2 = Process(target=bad_ass_function,kwargs={"n":n,"queue":queue}) #time.sleep(1) #p3 = Process(target=bad_ass_function,kwargs={"n":n,"queue":queue}) #p2.start() #p3.start() #dump_queue(queue) #p3.join() #dump_queue(queue)
unlicense
sunils34/buffer-django-nonrel
tests/regressiontests/forms/localflavor/sk.py
89
4333
from django.contrib.localflavor.sk.forms import (SKRegionSelect, SKPostalCodeField, SKDistrictSelect) from utils import LocalFlavorTestCase class SKLocalFlavorTests(LocalFlavorTestCase): def test_SKRegionSelect(self): f = SKRegionSelect() out = u'''<select name="regions"> <option value="BB">Banska Bystrica region</option> <option value="BA">Bratislava region</option> <option value="KE">Kosice region</option> <option value="NR">Nitra region</option> <option value="PO">Presov region</option> <option value="TN">Trencin region</option> <option value="TT" selected="selected">Trnava region</option> <option value="ZA">Zilina region</option> </select>''' self.assertEqual(f.render('regions', 'TT'), out) def test_SKDistrictSelect(self): f = SKDistrictSelect() out = u'''<select name="Districts"> <option value="BB">Banska Bystrica</option> <option value="BS">Banska Stiavnica</option> <option value="BJ">Bardejov</option> <option value="BN">Banovce nad Bebravou</option> <option value="BR">Brezno</option> <option value="BA1">Bratislava I</option> <option value="BA2">Bratislava II</option> <option value="BA3">Bratislava III</option> <option value="BA4">Bratislava IV</option> <option value="BA5">Bratislava V</option> <option value="BY">Bytca</option> <option value="CA">Cadca</option> <option value="DT">Detva</option> <option value="DK">Dolny Kubin</option> <option value="DS">Dunajska Streda</option> <option value="GA">Galanta</option> <option value="GL">Gelnica</option> <option value="HC">Hlohovec</option> <option value="HE">Humenne</option> <option value="IL">Ilava</option> <option value="KK">Kezmarok</option> <option value="KN">Komarno</option> <option value="KE1">Kosice I</option> <option value="KE2">Kosice II</option> <option value="KE3">Kosice III</option> <option value="KE4">Kosice IV</option> <option value="KEO">Kosice - okolie</option> <option value="KA">Krupina</option> <option value="KM">Kysucke Nove Mesto</option> <option value="LV">Levice</option> <option value="LE">Levoca</option> <option value="LM">Liptovsky Mikulas</option> <option value="LC">Lucenec</option> <option value="MA">Malacky</option> <option value="MT">Martin</option> <option value="ML">Medzilaborce</option> <option value="MI">Michalovce</option> <option value="MY">Myjava</option> <option value="NO">Namestovo</option> <option value="NR">Nitra</option> <option value="NM">Nove Mesto nad Vahom</option> <option value="NZ">Nove Zamky</option> <option value="PE">Partizanske</option> <option value="PK">Pezinok</option> <option value="PN">Piestany</option> <option value="PT">Poltar</option> <option value="PP">Poprad</option> <option value="PB">Povazska Bystrica</option> <option value="PO">Presov</option> <option value="PD">Prievidza</option> <option value="PU">Puchov</option> <option value="RA">Revuca</option> <option value="RS">Rimavska Sobota</option> <option value="RV">Roznava</option> <option value="RK" selected="selected">Ruzomberok</option> <option value="SB">Sabinov</option> <option value="SC">Senec</option> <option value="SE">Senica</option> <option value="SI">Skalica</option> <option value="SV">Snina</option> <option value="SO">Sobrance</option> <option value="SN">Spisska Nova Ves</option> <option value="SL">Stara Lubovna</option> <option value="SP">Stropkov</option> <option value="SK">Svidnik</option> <option value="SA">Sala</option> <option value="TO">Topolcany</option> <option value="TV">Trebisov</option> <option value="TN">Trencin</option> <option value="TT">Trnava</option> <option value="TR">Turcianske Teplice</option> <option value="TS">Tvrdosin</option> <option value="VK">Velky Krtis</option> <option value="VT">Vranov nad Toplou</option> <option value="ZM">Zlate Moravce</option> <option value="ZV">Zvolen</option> <option value="ZC">Zarnovica</option> <option value="ZH">Ziar nad Hronom</option> <option value="ZA">Zilina</option> </select>''' self.assertEqual(f.render('Districts', 'RK'), out) def test_SKPostalCodeField(self): error_format = [u'Enter a postal code in the format XXXXX or XXX XX.'] valid = { '91909': '91909', '917 01': '91701', } invalid = { '84545x': error_format, } self.assertFieldOutput(SKPostalCodeField, valid, invalid)
bsd-3-clause
sometallgit/AutoUploader
Python27/Lib/test/test_threading_local.py
10
6609
import unittest from doctest import DocTestSuite from test import test_support as support import weakref import gc # Modules under test _thread = support.import_module('thread') threading = support.import_module('threading') import _threading_local class Weak(object): pass def target(local, weaklist): weak = Weak() local.weak = weak weaklist.append(weakref.ref(weak)) class BaseLocalTest: def test_local_refs(self): self._local_refs(20) self._local_refs(50) self._local_refs(100) def _local_refs(self, n): local = self._local() weaklist = [] for i in range(n): t = threading.Thread(target=target, args=(local, weaklist)) t.start() t.join() del t gc.collect() self.assertEqual(len(weaklist), n) # XXX _threading_local keeps the local of the last stopped thread alive. deadlist = [weak for weak in weaklist if weak() is None] self.assertIn(len(deadlist), (n-1, n)) # Assignment to the same thread local frees it sometimes (!) local.someothervar = None gc.collect() deadlist = [weak for weak in weaklist if weak() is None] self.assertIn(len(deadlist), (n-1, n), (n, len(deadlist))) def test_derived(self): # Issue 3088: if there is a threads switch inside the __init__ # of a threading.local derived class, the per-thread dictionary # is created but not correctly set on the object. # The first member set may be bogus. import time class Local(self._local): def __init__(self): time.sleep(0.01) local = Local() def f(i): local.x = i # Simply check that the variable is correctly set self.assertEqual(local.x, i) with support.start_threads(threading.Thread(target=f, args=(i,)) for i in range(10)): pass def test_derived_cycle_dealloc(self): # http://bugs.python.org/issue6990 class Local(self._local): pass locals = None passed = [False] e1 = threading.Event() e2 = threading.Event() def f(): # 1) Involve Local in a cycle cycle = [Local()] cycle.append(cycle) cycle[0].foo = 'bar' # 2) GC the cycle (triggers threadmodule.c::local_clear # before local_dealloc) del cycle gc.collect() e1.set() e2.wait() # 4) New Locals should be empty passed[0] = all(not hasattr(local, 'foo') for local in locals) t = threading.Thread(target=f) t.start() e1.wait() # 3) New Locals should recycle the original's address. Creating # them in the thread overwrites the thread state and avoids the # bug locals = [Local() for i in range(10)] e2.set() t.join() self.assertTrue(passed[0]) def test_arguments(self): # Issue 1522237 from thread import _local as local from _threading_local import local as py_local for cls in (local, py_local): class MyLocal(cls): def __init__(self, *args, **kwargs): pass MyLocal(a=1) MyLocal(1) self.assertRaises(TypeError, cls, a=1) self.assertRaises(TypeError, cls, 1) def _test_one_class(self, c): self._failed = "No error message set or cleared." obj = c() e1 = threading.Event() e2 = threading.Event() def f1(): obj.x = 'foo' obj.y = 'bar' del obj.y e1.set() e2.wait() def f2(): try: foo = obj.x except AttributeError: # This is expected -- we haven't set obj.x in this thread yet! self._failed = "" # passed else: self._failed = ('Incorrectly got value %r from class %r\n' % (foo, c)) sys.stderr.write(self._failed) t1 = threading.Thread(target=f1) t1.start() e1.wait() t2 = threading.Thread(target=f2) t2.start() t2.join() # The test is done; just let t1 know it can exit, and wait for it. e2.set() t1.join() self.assertFalse(self._failed, self._failed) def test_threading_local(self): self._test_one_class(self._local) def test_threading_local_subclass(self): class LocalSubclass(self._local): """To test that subclasses behave properly.""" self._test_one_class(LocalSubclass) def _test_dict_attribute(self, cls): obj = cls() obj.x = 5 self.assertEqual(obj.__dict__, {'x': 5}) with self.assertRaises(AttributeError): obj.__dict__ = {} with self.assertRaises(AttributeError): del obj.__dict__ def test_dict_attribute(self): self._test_dict_attribute(self._local) def test_dict_attribute_subclass(self): class LocalSubclass(self._local): """To test that subclasses behave properly.""" self._test_dict_attribute(LocalSubclass) class ThreadLocalTest(unittest.TestCase, BaseLocalTest): _local = _thread._local # Fails for the pure Python implementation def test_cycle_collection(self): class X: pass x = X() x.local = self._local() x.local.x = x wr = weakref.ref(x) del x gc.collect() self.assertIsNone(wr()) class PyThreadingLocalTest(unittest.TestCase, BaseLocalTest): _local = _threading_local.local def test_main(): suite = unittest.TestSuite() suite.addTest(DocTestSuite('_threading_local')) suite.addTest(unittest.makeSuite(ThreadLocalTest)) suite.addTest(unittest.makeSuite(PyThreadingLocalTest)) try: from thread import _local except ImportError: pass else: import _threading_local local_orig = _threading_local.local def setUp(test): _threading_local.local = _local def tearDown(test): _threading_local.local = local_orig suite.addTest(DocTestSuite('_threading_local', setUp=setUp, tearDown=tearDown) ) support.run_unittest(suite) if __name__ == '__main__': test_main()
mit
honghaoz/UW-Info-Session-iOS
UW-Info-Session-1.0/GAE Support/uw-info2/libs/requests/packages/chardet/jpcntx.py
949
19104
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .compat import wrap_ord NUM_OF_CATEGORY = 6 DONT_KNOW = -1 ENOUGH_REL_THRESHOLD = 100 MAX_REL_THRESHOLD = 1000 MINIMUM_DATA_THRESHOLD = 4 # This is hiragana 2-char sequence table, the number in each cell represents its frequency category jp2CharContext = ( (0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1), (2,4,0,4,0,3,0,4,0,3,4,4,4,2,4,3,3,4,3,2,3,3,4,2,3,3,3,2,4,1,4,3,3,1,5,4,3,4,3,4,3,5,3,0,3,5,4,2,0,3,1,0,3,3,0,3,3,0,1,1,0,4,3,0,3,3,0,4,0,2,0,3,5,5,5,5,4,0,4,1,0,3,4), (0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2), (0,4,0,5,0,5,0,4,0,4,5,4,4,3,5,3,5,1,5,3,4,3,4,4,3,4,3,3,4,3,5,4,4,3,5,5,3,5,5,5,3,5,5,3,4,5,5,3,1,3,2,0,3,4,0,4,2,0,4,2,1,5,3,2,3,5,0,4,0,2,0,5,4,4,5,4,5,0,4,0,0,4,4), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,3,0,4,0,3,0,3,0,4,5,4,3,3,3,3,4,3,5,4,4,3,5,4,4,3,4,3,4,4,4,4,5,3,4,4,3,4,5,5,4,5,5,1,4,5,4,3,0,3,3,1,3,3,0,4,4,0,3,3,1,5,3,3,3,5,0,4,0,3,0,4,4,3,4,3,3,0,4,1,1,3,4), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,4,0,3,0,3,0,4,0,3,4,4,3,2,2,1,2,1,3,1,3,3,3,3,3,4,3,1,3,3,5,3,3,0,4,3,0,5,4,3,3,5,4,4,3,4,4,5,0,1,2,0,1,2,0,2,2,0,1,0,0,5,2,2,1,4,0,3,0,1,0,4,4,3,5,4,3,0,2,1,0,4,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,3,0,5,0,4,0,2,1,4,4,2,4,1,4,2,4,2,4,3,3,3,4,3,3,3,3,1,4,2,3,3,3,1,4,4,1,1,1,4,3,3,2,0,2,4,3,2,0,3,3,0,3,1,1,0,0,0,3,3,0,4,2,2,3,4,0,4,0,3,0,4,4,5,3,4,4,0,3,0,0,1,4), (1,4,0,4,0,4,0,4,0,3,5,4,4,3,4,3,5,4,3,3,4,3,5,4,4,4,4,3,4,2,4,3,3,1,5,4,3,2,4,5,4,5,5,4,4,5,4,4,0,3,2,2,3,3,0,4,3,1,3,2,1,4,3,3,4,5,0,3,0,2,0,4,5,5,4,5,4,0,4,0,0,5,4), (0,5,0,5,0,4,0,3,0,4,4,3,4,3,3,3,4,0,4,4,4,3,4,3,4,3,3,1,4,2,4,3,4,0,5,4,1,4,5,4,4,5,3,2,4,3,4,3,2,4,1,3,3,3,2,3,2,0,4,3,3,4,3,3,3,4,0,4,0,3,0,4,5,4,4,4,3,0,4,1,0,1,3), (0,3,1,4,0,3,0,2,0,3,4,4,3,1,4,2,3,3,4,3,4,3,4,3,4,4,3,2,3,1,5,4,4,1,4,4,3,5,4,4,3,5,5,4,3,4,4,3,1,2,3,1,2,2,0,3,2,0,3,1,0,5,3,3,3,4,3,3,3,3,4,4,4,4,5,4,2,0,3,3,2,4,3), (0,2,0,3,0,1,0,1,0,0,3,2,0,0,2,0,1,0,2,1,3,3,3,1,2,3,1,0,1,0,4,2,1,1,3,3,0,4,3,3,1,4,3,3,0,3,3,2,0,0,0,0,1,0,0,2,0,0,0,0,0,4,1,0,2,3,2,2,2,1,3,3,3,4,4,3,2,0,3,1,0,3,3), (0,4,0,4,0,3,0,3,0,4,4,4,3,3,3,3,3,3,4,3,4,2,4,3,4,3,3,2,4,3,4,5,4,1,4,5,3,5,4,5,3,5,4,0,3,5,5,3,1,3,3,2,2,3,0,3,4,1,3,3,2,4,3,3,3,4,0,4,0,3,0,4,5,4,4,5,3,0,4,1,0,3,4), (0,2,0,3,0,3,0,0,0,2,2,2,1,0,1,0,0,0,3,0,3,0,3,0,1,3,1,0,3,1,3,3,3,1,3,3,3,0,1,3,1,3,4,0,0,3,1,1,0,3,2,0,0,0,0,1,3,0,1,0,0,3,3,2,0,3,0,0,0,0,0,3,4,3,4,3,3,0,3,0,0,2,3), (2,3,0,3,0,2,0,1,0,3,3,4,3,1,3,1,1,1,3,1,4,3,4,3,3,3,0,0,3,1,5,4,3,1,4,3,2,5,5,4,4,4,4,3,3,4,4,4,0,2,1,1,3,2,0,1,2,0,0,1,0,4,1,3,3,3,0,3,0,1,0,4,4,4,5,5,3,0,2,0,0,4,4), (0,2,0,1,0,3,1,3,0,2,3,3,3,0,3,1,0,0,3,0,3,2,3,1,3,2,1,1,0,0,4,2,1,0,2,3,1,4,3,2,0,4,4,3,1,3,1,3,0,1,0,0,1,0,0,0,1,0,0,0,0,4,1,1,1,2,0,3,0,0,0,3,4,2,4,3,2,0,1,0,0,3,3), (0,1,0,4,0,5,0,4,0,2,4,4,2,3,3,2,3,3,5,3,3,3,4,3,4,2,3,0,4,3,3,3,4,1,4,3,2,1,5,5,3,4,5,1,3,5,4,2,0,3,3,0,1,3,0,4,2,0,1,3,1,4,3,3,3,3,0,3,0,1,0,3,4,4,4,5,5,0,3,0,1,4,5), (0,2,0,3,0,3,0,0,0,2,3,1,3,0,4,0,1,1,3,0,3,4,3,2,3,1,0,3,3,2,3,1,3,0,2,3,0,2,1,4,1,2,2,0,0,3,3,0,0,2,0,0,0,1,0,0,0,0,2,2,0,3,2,1,3,3,0,2,0,2,0,0,3,3,1,2,4,0,3,0,2,2,3), (2,4,0,5,0,4,0,4,0,2,4,4,4,3,4,3,3,3,1,2,4,3,4,3,4,4,5,0,3,3,3,3,2,0,4,3,1,4,3,4,1,4,4,3,3,4,4,3,1,2,3,0,4,2,0,4,1,0,3,3,0,4,3,3,3,4,0,4,0,2,0,3,5,3,4,5,2,0,3,0,0,4,5), (0,3,0,4,0,1,0,1,0,1,3,2,2,1,3,0,3,0,2,0,2,0,3,0,2,0,0,0,1,0,1,1,0,0,3,1,0,0,0,4,0,3,1,0,2,1,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,2,2,3,1,0,3,0,0,0,1,4,4,4,3,0,0,4,0,0,1,4), (1,4,1,5,0,3,0,3,0,4,5,4,4,3,5,3,3,4,4,3,4,1,3,3,3,3,2,1,4,1,5,4,3,1,4,4,3,5,4,4,3,5,4,3,3,4,4,4,0,3,3,1,2,3,0,3,1,0,3,3,0,5,4,4,4,4,4,4,3,3,5,4,4,3,3,5,4,0,3,2,0,4,4), (0,2,0,3,0,1,0,0,0,1,3,3,3,2,4,1,3,0,3,1,3,0,2,2,1,1,0,0,2,0,4,3,1,0,4,3,0,4,4,4,1,4,3,1,1,3,3,1,0,2,0,0,1,3,0,0,0,0,2,0,0,4,3,2,4,3,5,4,3,3,3,4,3,3,4,3,3,0,2,1,0,3,3), (0,2,0,4,0,3,0,2,0,2,5,5,3,4,4,4,4,1,4,3,3,0,4,3,4,3,1,3,3,2,4,3,0,3,4,3,0,3,4,4,2,4,4,0,4,5,3,3,2,2,1,1,1,2,0,1,5,0,3,3,2,4,3,3,3,4,0,3,0,2,0,4,4,3,5,5,0,0,3,0,2,3,3), (0,3,0,4,0,3,0,1,0,3,4,3,3,1,3,3,3,0,3,1,3,0,4,3,3,1,1,0,3,0,3,3,0,0,4,4,0,1,5,4,3,3,5,0,3,3,4,3,0,2,0,1,1,1,0,1,3,0,1,2,1,3,3,2,3,3,0,3,0,1,0,1,3,3,4,4,1,0,1,2,2,1,3), (0,1,0,4,0,4,0,3,0,1,3,3,3,2,3,1,1,0,3,0,3,3,4,3,2,4,2,0,1,0,4,3,2,0,4,3,0,5,3,3,2,4,4,4,3,3,3,4,0,1,3,0,0,1,0,0,1,0,0,0,0,4,2,3,3,3,0,3,0,0,0,4,4,4,5,3,2,0,3,3,0,3,5), (0,2,0,3,0,0,0,3,0,1,3,0,2,0,0,0,1,0,3,1,1,3,3,0,0,3,0,0,3,0,2,3,1,0,3,1,0,3,3,2,0,4,2,2,0,2,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,2,1,2,0,1,0,1,0,0,0,1,3,1,2,0,0,0,1,0,0,1,4), (0,3,0,3,0,5,0,1,0,2,4,3,1,3,3,2,1,1,5,2,1,0,5,1,2,0,0,0,3,3,2,2,3,2,4,3,0,0,3,3,1,3,3,0,2,5,3,4,0,3,3,0,1,2,0,2,2,0,3,2,0,2,2,3,3,3,0,2,0,1,0,3,4,4,2,5,4,0,3,0,0,3,5), (0,3,0,3,0,3,0,1,0,3,3,3,3,0,3,0,2,0,2,1,1,0,2,0,1,0,0,0,2,1,0,0,1,0,3,2,0,0,3,3,1,2,3,1,0,3,3,0,0,1,0,0,0,0,0,2,0,0,0,0,0,2,3,1,2,3,0,3,0,1,0,3,2,1,0,4,3,0,1,1,0,3,3), (0,4,0,5,0,3,0,3,0,4,5,5,4,3,5,3,4,3,5,3,3,2,5,3,4,4,4,3,4,3,4,5,5,3,4,4,3,4,4,5,4,4,4,3,4,5,5,4,2,3,4,2,3,4,0,3,3,1,4,3,2,4,3,3,5,5,0,3,0,3,0,5,5,5,5,4,4,0,4,0,1,4,4), (0,4,0,4,0,3,0,3,0,3,5,4,4,2,3,2,5,1,3,2,5,1,4,2,3,2,3,3,4,3,3,3,3,2,5,4,1,3,3,5,3,4,4,0,4,4,3,1,1,3,1,0,2,3,0,2,3,0,3,0,0,4,3,1,3,4,0,3,0,2,0,4,4,4,3,4,5,0,4,0,0,3,4), (0,3,0,3,0,3,1,2,0,3,4,4,3,3,3,0,2,2,4,3,3,1,3,3,3,1,1,0,3,1,4,3,2,3,4,4,2,4,4,4,3,4,4,3,2,4,4,3,1,3,3,1,3,3,0,4,1,0,2,2,1,4,3,2,3,3,5,4,3,3,5,4,4,3,3,0,4,0,3,2,2,4,4), (0,2,0,1,0,0,0,0,0,1,2,1,3,0,0,0,0,0,2,0,1,2,1,0,0,1,0,0,0,0,3,0,0,1,0,1,1,3,1,0,0,0,1,1,0,1,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,1,2,2,0,3,4,0,0,0,1,1,0,0,1,0,0,0,0,0,1,1), (0,1,0,0,0,1,0,0,0,0,4,0,4,1,4,0,3,0,4,0,3,0,4,0,3,0,3,0,4,1,5,1,4,0,0,3,0,5,0,5,2,0,1,0,0,0,2,1,4,0,1,3,0,0,3,0,0,3,1,1,4,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0), (1,4,0,5,0,3,0,2,0,3,5,4,4,3,4,3,5,3,4,3,3,0,4,3,3,3,3,3,3,2,4,4,3,1,3,4,4,5,4,4,3,4,4,1,3,5,4,3,3,3,1,2,2,3,3,1,3,1,3,3,3,5,3,3,4,5,0,3,0,3,0,3,4,3,4,4,3,0,3,0,2,4,3), (0,1,0,4,0,0,0,0,0,1,4,0,4,1,4,2,4,0,3,0,1,0,1,0,0,0,0,0,2,0,3,1,1,1,0,3,0,0,0,1,2,1,0,0,1,1,1,1,0,1,0,0,0,1,0,0,3,0,0,0,0,3,2,0,2,2,0,1,0,0,0,2,3,2,3,3,0,0,0,0,2,1,0), (0,5,1,5,0,3,0,3,0,5,4,4,5,1,5,3,3,0,4,3,4,3,5,3,4,3,3,2,4,3,4,3,3,0,3,3,1,4,4,3,4,4,4,3,4,5,5,3,2,3,1,1,3,3,1,3,1,1,3,3,2,4,5,3,3,5,0,4,0,3,0,4,4,3,5,3,3,0,3,4,0,4,3), (0,5,0,5,0,3,0,2,0,4,4,3,5,2,4,3,3,3,4,4,4,3,5,3,5,3,3,1,4,0,4,3,3,0,3,3,0,4,4,4,4,5,4,3,3,5,5,3,2,3,1,2,3,2,0,1,0,0,3,2,2,4,4,3,1,5,0,4,0,3,0,4,3,1,3,2,1,0,3,3,0,3,3), (0,4,0,5,0,5,0,4,0,4,5,5,5,3,4,3,3,2,5,4,4,3,5,3,5,3,4,0,4,3,4,4,3,2,4,4,3,4,5,4,4,5,5,0,3,5,5,4,1,3,3,2,3,3,1,3,1,0,4,3,1,4,4,3,4,5,0,4,0,2,0,4,3,4,4,3,3,0,4,0,0,5,5), (0,4,0,4,0,5,0,1,1,3,3,4,4,3,4,1,3,0,5,1,3,0,3,1,3,1,1,0,3,0,3,3,4,0,4,3,0,4,4,4,3,4,4,0,3,5,4,1,0,3,0,0,2,3,0,3,1,0,3,1,0,3,2,1,3,5,0,3,0,1,0,3,2,3,3,4,4,0,2,2,0,4,4), (2,4,0,5,0,4,0,3,0,4,5,5,4,3,5,3,5,3,5,3,5,2,5,3,4,3,3,4,3,4,5,3,2,1,5,4,3,2,3,4,5,3,4,1,2,5,4,3,0,3,3,0,3,2,0,2,3,0,4,1,0,3,4,3,3,5,0,3,0,1,0,4,5,5,5,4,3,0,4,2,0,3,5), (0,5,0,4,0,4,0,2,0,5,4,3,4,3,4,3,3,3,4,3,4,2,5,3,5,3,4,1,4,3,4,4,4,0,3,5,0,4,4,4,4,5,3,1,3,4,5,3,3,3,3,3,3,3,0,2,2,0,3,3,2,4,3,3,3,5,3,4,1,3,3,5,3,2,0,0,0,0,4,3,1,3,3), (0,1,0,3,0,3,0,1,0,1,3,3,3,2,3,3,3,0,3,0,0,0,3,1,3,0,0,0,2,2,2,3,0,0,3,2,0,1,2,4,1,3,3,0,0,3,3,3,0,1,0,0,2,1,0,0,3,0,3,1,0,3,0,0,1,3,0,2,0,1,0,3,3,1,3,3,0,0,1,1,0,3,3), (0,2,0,3,0,2,1,4,0,2,2,3,1,1,3,1,1,0,2,0,3,1,2,3,1,3,0,0,1,0,4,3,2,3,3,3,1,4,2,3,3,3,3,1,0,3,1,4,0,1,1,0,1,2,0,1,1,0,1,1,0,3,1,3,2,2,0,1,0,0,0,2,3,3,3,1,0,0,0,0,0,2,3), (0,5,0,4,0,5,0,2,0,4,5,5,3,3,4,3,3,1,5,4,4,2,4,4,4,3,4,2,4,3,5,5,4,3,3,4,3,3,5,5,4,5,5,1,3,4,5,3,1,4,3,1,3,3,0,3,3,1,4,3,1,4,5,3,3,5,0,4,0,3,0,5,3,3,1,4,3,0,4,0,1,5,3), (0,5,0,5,0,4,0,2,0,4,4,3,4,3,3,3,3,3,5,4,4,4,4,4,4,5,3,3,5,2,4,4,4,3,4,4,3,3,4,4,5,5,3,3,4,3,4,3,3,4,3,3,3,3,1,2,2,1,4,3,3,5,4,4,3,4,0,4,0,3,0,4,4,4,4,4,1,0,4,2,0,2,4), (0,4,0,4,0,3,0,1,0,3,5,2,3,0,3,0,2,1,4,2,3,3,4,1,4,3,3,2,4,1,3,3,3,0,3,3,0,0,3,3,3,5,3,3,3,3,3,2,0,2,0,0,2,0,0,2,0,0,1,0,0,3,1,2,2,3,0,3,0,2,0,4,4,3,3,4,1,0,3,0,0,2,4), (0,0,0,4,0,0,0,0,0,0,1,0,1,0,2,0,0,0,0,0,1,0,2,0,1,0,0,0,0,0,3,1,3,0,3,2,0,0,0,1,0,3,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,0,2,0,0,0,0,0,0,2), (0,2,1,3,0,2,0,2,0,3,3,3,3,1,3,1,3,3,3,3,3,3,4,2,2,1,2,1,4,0,4,3,1,3,3,3,2,4,3,5,4,3,3,3,3,3,3,3,0,1,3,0,2,0,0,1,0,0,1,0,0,4,2,0,2,3,0,3,3,0,3,3,4,2,3,1,4,0,1,2,0,2,3), (0,3,0,3,0,1,0,3,0,2,3,3,3,0,3,1,2,0,3,3,2,3,3,2,3,2,3,1,3,0,4,3,2,0,3,3,1,4,3,3,2,3,4,3,1,3,3,1,1,0,1,1,0,1,0,1,0,1,0,0,0,4,1,1,0,3,0,3,1,0,2,3,3,3,3,3,1,0,0,2,0,3,3), (0,0,0,0,0,0,0,0,0,0,3,0,2,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,3,0,3,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,2,0,2,3,0,0,0,0,0,0,0,0,3), (0,2,0,3,1,3,0,3,0,2,3,3,3,1,3,1,3,1,3,1,3,3,3,1,3,0,2,3,1,1,4,3,3,2,3,3,1,2,2,4,1,3,3,0,1,4,2,3,0,1,3,0,3,0,0,1,3,0,2,0,0,3,3,2,1,3,0,3,0,2,0,3,4,4,4,3,1,0,3,0,0,3,3), (0,2,0,1,0,2,0,0,0,1,3,2,2,1,3,0,1,1,3,0,3,2,3,1,2,0,2,0,1,1,3,3,3,0,3,3,1,1,2,3,2,3,3,1,2,3,2,0,0,1,0,0,0,0,0,0,3,0,1,0,0,2,1,2,1,3,0,3,0,0,0,3,4,4,4,3,2,0,2,0,0,2,4), (0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,3,1,0,0,0,0,0,0,0,3), (0,3,0,3,0,2,0,3,0,3,3,3,2,3,2,2,2,0,3,1,3,3,3,2,3,3,0,0,3,0,3,2,2,0,2,3,1,4,3,4,3,3,2,3,1,5,4,4,0,3,1,2,1,3,0,3,1,1,2,0,2,3,1,3,1,3,0,3,0,1,0,3,3,4,4,2,1,0,2,1,0,2,4), (0,1,0,3,0,1,0,2,0,1,4,2,5,1,4,0,2,0,2,1,3,1,4,0,2,1,0,0,2,1,4,1,1,0,3,3,0,5,1,3,2,3,3,1,0,3,2,3,0,1,0,0,0,0,0,0,1,0,0,0,0,4,0,1,0,3,0,2,0,1,0,3,3,3,4,3,3,0,0,0,0,2,3), (0,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,0,0,1,0,0,0,0,0,3), (0,1,0,3,0,4,0,3,0,2,4,3,1,0,3,2,2,1,3,1,2,2,3,1,1,1,2,1,3,0,1,2,0,1,3,2,1,3,0,5,5,1,0,0,1,3,2,1,0,3,0,0,1,0,0,0,0,0,3,4,0,1,1,1,3,2,0,2,0,1,0,2,3,3,1,2,3,0,1,0,1,0,4), (0,0,0,1,0,3,0,3,0,2,2,1,0,0,4,0,3,0,3,1,3,0,3,0,3,0,1,0,3,0,3,1,3,0,3,3,0,0,1,2,1,1,1,0,1,2,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,2,2,1,2,0,0,2,0,0,0,0,2,3,3,3,3,0,0,0,0,1,4), (0,0,0,3,0,3,0,0,0,0,3,1,1,0,3,0,1,0,2,0,1,0,0,0,0,0,0,0,1,0,3,0,2,0,2,3,0,0,2,2,3,1,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,2,0,0,0,0,2,3), (2,4,0,5,0,5,0,4,0,3,4,3,3,3,4,3,3,3,4,3,4,4,5,4,5,5,5,2,3,0,5,5,4,1,5,4,3,1,5,4,3,4,4,3,3,4,3,3,0,3,2,0,2,3,0,3,0,0,3,3,0,5,3,2,3,3,0,3,0,3,0,3,4,5,4,5,3,0,4,3,0,3,4), (0,3,0,3,0,3,0,3,0,3,3,4,3,2,3,2,3,0,4,3,3,3,3,3,3,3,3,0,3,2,4,3,3,1,3,4,3,4,4,4,3,4,4,3,2,4,4,1,0,2,0,0,1,1,0,2,0,0,3,1,0,5,3,2,1,3,0,3,0,1,2,4,3,2,4,3,3,0,3,2,0,4,4), (0,3,0,3,0,1,0,0,0,1,4,3,3,2,3,1,3,1,4,2,3,2,4,2,3,4,3,0,2,2,3,3,3,0,3,3,3,0,3,4,1,3,3,0,3,4,3,3,0,1,1,0,1,0,0,0,4,0,3,0,0,3,1,2,1,3,0,4,0,1,0,4,3,3,4,3,3,0,2,0,0,3,3), (0,3,0,4,0,1,0,3,0,3,4,3,3,0,3,3,3,1,3,1,3,3,4,3,3,3,0,0,3,1,5,3,3,1,3,3,2,5,4,3,3,4,5,3,2,5,3,4,0,1,0,0,0,0,0,2,0,0,1,1,0,4,2,2,1,3,0,3,0,2,0,4,4,3,5,3,2,0,1,1,0,3,4), (0,5,0,4,0,5,0,2,0,4,4,3,3,2,3,3,3,1,4,3,4,1,5,3,4,3,4,0,4,2,4,3,4,1,5,4,0,4,4,4,4,5,4,1,3,5,4,2,1,4,1,1,3,2,0,3,1,0,3,2,1,4,3,3,3,4,0,4,0,3,0,4,4,4,3,3,3,0,4,2,0,3,4), (1,4,0,4,0,3,0,1,0,3,3,3,1,1,3,3,2,2,3,3,1,0,3,2,2,1,2,0,3,1,2,1,2,0,3,2,0,2,2,3,3,4,3,0,3,3,1,2,0,1,1,3,1,2,0,0,3,0,1,1,0,3,2,2,3,3,0,3,0,0,0,2,3,3,4,3,3,0,1,0,0,1,4), (0,4,0,4,0,4,0,0,0,3,4,4,3,1,4,2,3,2,3,3,3,1,4,3,4,0,3,0,4,2,3,3,2,2,5,4,2,1,3,4,3,4,3,1,3,3,4,2,0,2,1,0,3,3,0,0,2,0,3,1,0,4,4,3,4,3,0,4,0,1,0,2,4,4,4,4,4,0,3,2,0,3,3), (0,0,0,1,0,4,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,3,2,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,2), (0,2,0,3,0,4,0,4,0,1,3,3,3,0,4,0,2,1,2,1,1,1,2,0,3,1,1,0,1,0,3,1,0,0,3,3,2,0,1,1,0,0,0,0,0,1,0,2,0,2,2,0,3,1,0,0,1,0,1,1,0,1,2,0,3,0,0,0,0,1,0,0,3,3,4,3,1,0,1,0,3,0,2), (0,0,0,3,0,5,0,0,0,0,1,0,2,0,3,1,0,1,3,0,0,0,2,0,0,0,1,0,0,0,1,1,0,0,4,0,0,0,2,3,0,1,4,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,3,0,0,0,0,0,3), (0,2,0,5,0,5,0,1,0,2,4,3,3,2,5,1,3,2,3,3,3,0,4,1,2,0,3,0,4,0,2,2,1,1,5,3,0,0,1,4,2,3,2,0,3,3,3,2,0,2,4,1,1,2,0,1,1,0,3,1,0,1,3,1,2,3,0,2,0,0,0,1,3,5,4,4,4,0,3,0,0,1,3), (0,4,0,5,0,4,0,4,0,4,5,4,3,3,4,3,3,3,4,3,4,4,5,3,4,5,4,2,4,2,3,4,3,1,4,4,1,3,5,4,4,5,5,4,4,5,5,5,2,3,3,1,4,3,1,3,3,0,3,3,1,4,3,4,4,4,0,3,0,4,0,3,3,4,4,5,0,0,4,3,0,4,5), (0,4,0,4,0,3,0,3,0,3,4,4,4,3,3,2,4,3,4,3,4,3,5,3,4,3,2,1,4,2,4,4,3,1,3,4,2,4,5,5,3,4,5,4,1,5,4,3,0,3,2,2,3,2,1,3,1,0,3,3,3,5,3,3,3,5,4,4,2,3,3,4,3,3,3,2,1,0,3,2,1,4,3), (0,4,0,5,0,4,0,3,0,3,5,5,3,2,4,3,4,0,5,4,4,1,4,4,4,3,3,3,4,3,5,5,2,3,3,4,1,2,5,5,3,5,5,2,3,5,5,4,0,3,2,0,3,3,1,1,5,1,4,1,0,4,3,2,3,5,0,4,0,3,0,5,4,3,4,3,0,0,4,1,0,4,4), (1,3,0,4,0,2,0,2,0,2,5,5,3,3,3,3,3,0,4,2,3,4,4,4,3,4,0,0,3,4,5,4,3,3,3,3,2,5,5,4,5,5,5,4,3,5,5,5,1,3,1,0,1,0,0,3,2,0,4,2,0,5,2,3,2,4,1,3,0,3,0,4,5,4,5,4,3,0,4,2,0,5,4), (0,3,0,4,0,5,0,3,0,3,4,4,3,2,3,2,3,3,3,3,3,2,4,3,3,2,2,0,3,3,3,3,3,1,3,3,3,0,4,4,3,4,4,1,1,4,4,2,0,3,1,0,1,1,0,4,1,0,2,3,1,3,3,1,3,4,0,3,0,1,0,3,1,3,0,0,1,0,2,0,0,4,4), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,3,0,3,0,2,0,3,0,1,5,4,3,3,3,1,4,2,1,2,3,4,4,2,4,4,5,0,3,1,4,3,4,0,4,3,3,3,2,3,2,5,3,4,3,2,2,3,0,0,3,0,2,1,0,1,2,0,0,0,0,2,1,1,3,1,0,2,0,4,0,3,4,4,4,5,2,0,2,0,0,1,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,4,2,1,1,0,1,0,3,2,0,0,3,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,1,0,0,0,2,0,0,0,1,4,0,4,2,1,0,0,0,0,0,1), (0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,3,1,0,0,0,2,0,2,1,0,0,1,2,1,0,1,1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,1,3,1,0,0,0,0,0,1,0,0,2,1,0,0,0,0,0,0,0,0,2), (0,4,0,4,0,4,0,3,0,4,4,3,4,2,4,3,2,0,4,4,4,3,5,3,5,3,3,2,4,2,4,3,4,3,1,4,0,2,3,4,4,4,3,3,3,4,4,4,3,4,1,3,4,3,2,1,2,1,3,3,3,4,4,3,3,5,0,4,0,3,0,4,3,3,3,2,1,0,3,0,0,3,3), (0,4,0,3,0,3,0,3,0,3,5,5,3,3,3,3,4,3,4,3,3,3,4,4,4,3,3,3,3,4,3,5,3,3,1,3,2,4,5,5,5,5,4,3,4,5,5,3,2,2,3,3,3,3,2,3,3,1,2,3,2,4,3,3,3,4,0,4,0,2,0,4,3,2,2,1,2,0,3,0,0,4,1), ) class JapaneseContextAnalysis: def __init__(self): self.reset() def reset(self): self._mTotalRel = 0 # total sequence received # category counters, each interger counts sequence in its category self._mRelSample = [0] * NUM_OF_CATEGORY # if last byte in current buffer is not the last byte of a character, # we need to know how many bytes to skip in next buffer self._mNeedToSkipCharNum = 0 self._mLastCharOrder = -1 # The order of previous char # If this flag is set to True, detection is done and conclusion has # been made self._mDone = False def feed(self, aBuf, aLen): if self._mDone: return # The buffer we got is byte oriented, and a character may span in more than one # buffers. In case the last one or two byte in last buffer is not # complete, we record how many byte needed to complete that character # and skip these bytes here. We can choose to record those bytes as # well and analyse the character once it is complete, but since a # character will not make much difference, by simply skipping # this character will simply our logic and improve performance. i = self._mNeedToSkipCharNum while i < aLen: order, charLen = self.get_order(aBuf[i:i + 2]) i += charLen if i > aLen: self._mNeedToSkipCharNum = i - aLen self._mLastCharOrder = -1 else: if (order != -1) and (self._mLastCharOrder != -1): self._mTotalRel += 1 if self._mTotalRel > MAX_REL_THRESHOLD: self._mDone = True break self._mRelSample[jp2CharContext[self._mLastCharOrder][order]] += 1 self._mLastCharOrder = order def got_enough_data(self): return self._mTotalRel > ENOUGH_REL_THRESHOLD def get_confidence(self): # This is just one way to calculate confidence. It works well for me. if self._mTotalRel > MINIMUM_DATA_THRESHOLD: return (self._mTotalRel - self._mRelSample[0]) / self._mTotalRel else: return DONT_KNOW def get_order(self, aBuf): return -1, 1 class SJISContextAnalysis(JapaneseContextAnalysis): def get_order(self, aBuf): if not aBuf: return -1, 1 # find out current char's byte length first_char = wrap_ord(aBuf[0]) if ((0x81 <= first_char <= 0x9F) or (0xE0 <= first_char <= 0xFC)): charLen = 2 else: charLen = 1 # return its order if it is hiragana if len(aBuf) > 1: second_char = wrap_ord(aBuf[1]) if (first_char == 202) and (0x9F <= second_char <= 0xF1): return second_char - 0x9F, charLen return -1, charLen class EUCJPContextAnalysis(JapaneseContextAnalysis): def get_order(self, aBuf): if not aBuf: return -1, 1 # find out current char's byte length first_char = wrap_ord(aBuf[0]) if (first_char == 0x8E) or (0xA1 <= first_char <= 0xFE): charLen = 2 elif first_char == 0x8F: charLen = 3 else: charLen = 1 # return its order if it is hiragana if len(aBuf) > 1: second_char = wrap_ord(aBuf[1]) if (first_char == 0xA4) and (0xA1 <= second_char <= 0xF3): return second_char - 0xA1, charLen return -1, charLen # flake8: noqa
gpl-3.0
vathpela/systemd
hwdb/ids_parser.py
11
13410
#!/usr/bin/env python3 import re import sys from pyparsing import (Word, White, Literal, Regex, LineEnd, SkipTo, ZeroOrMore, OneOrMore, Combine, Optional, Suppress, stringEnd, pythonStyleComment) EOL = LineEnd().suppress() NUM1 = Word('0123456789abcdefABCDEF', exact=1) NUM2 = Word('0123456789abcdefABCDEF', exact=2) NUM3 = Word('0123456789abcdefABCDEF', exact=3) NUM4 = Word('0123456789abcdefABCDEF', exact=4) NUM6 = Word('0123456789abcdefABCDEF', exact=6) TAB = White('\t', exact=1).suppress() COMMENTLINE = pythonStyleComment + EOL EMPTYLINE = LineEnd() text_eol = lambda name: Regex(r'[^\n]+')(name) + EOL # text_eol = lambda name: Word(printables + ' ' + '®üäßçõãİó ×²⁶´‐“\u200E\u200B')(name) + EOL def klass_grammar(): klass_line = Literal('C ').suppress() + NUM2('klass') + text_eol('text') subclass_line = TAB + NUM2('subclass') + text_eol('text') protocol_line = TAB + TAB + NUM2('protocol') + text_eol('name') subclass = (subclass_line('SUBCLASS') - ZeroOrMore(protocol_line('PROTOCOLS*') ^ COMMENTLINE.suppress())) klass = (klass_line('KLASS') - ZeroOrMore(subclass('SUBCLASSES*') ^ COMMENTLINE.suppress())) return klass def usb_ids_grammar(): vendor_line = NUM4('vendor') + text_eol('text') device_line = TAB + NUM4('device') + text_eol('text') vendor = (vendor_line('VENDOR') + ZeroOrMore(device_line('VENDOR_DEV*') ^ COMMENTLINE.suppress())) klass = klass_grammar() other_line = (Literal('AT ') ^ Literal('HID ') ^ Literal('R ') ^ Literal('PHY ') ^ Literal('BIAS ') ^ Literal('HUT ') ^ Literal('L ') ^ Literal('VT ') ^ Literal('HCC ')) + text_eol('text') other_group = (other_line - ZeroOrMore(TAB + text_eol('text'))) commentgroup = OneOrMore(COMMENTLINE).suppress() ^ EMPTYLINE.suppress() grammar = OneOrMore(vendor('VENDORS*') ^ klass('CLASSES*') ^ other_group.suppress() ^ commentgroup) + stringEnd() grammar.parseWithTabs() return grammar def pci_ids_grammar(): vendor_line = NUM4('vendor') + text_eol('text') device_line = TAB + NUM4('device') + text_eol('text') subvendor_line = TAB + TAB + NUM4('a') + White(' ') + NUM4('b') + text_eol('name') device = (device_line('DEVICE') + ZeroOrMore(subvendor_line('SUBVENDORS*') ^ COMMENTLINE.suppress())) vendor = (vendor_line('VENDOR') + ZeroOrMore(device('DEVICES*') ^ COMMENTLINE.suppress())) klass = klass_grammar() commentgroup = OneOrMore(COMMENTLINE).suppress() ^ EMPTYLINE.suppress() grammar = OneOrMore(vendor('VENDORS*') ^ klass('CLASSES*') ^ commentgroup) + stringEnd() grammar.parseWithTabs() return grammar def sdio_ids_grammar(): vendor_line = NUM4('vendor') + text_eol('text') device_line = TAB + NUM4('device') + text_eol('text') vendor = (vendor_line('VENDOR') + ZeroOrMore(device_line('DEVICES*') ^ COMMENTLINE.suppress())) klass = klass_grammar() commentgroup = OneOrMore(COMMENTLINE).suppress() ^ EMPTYLINE.suppress() grammar = OneOrMore(vendor('VENDORS*') ^ klass('CLASSES*') ^ commentgroup) + stringEnd() grammar.parseWithTabs() return grammar def oui_grammar(type): prefix_line = (Combine(NUM2 - Suppress('-') - NUM2 - Suppress('-') - NUM2)('prefix') - Literal('(hex)') - text_eol('text')) if type == 'small': vendor_line = (NUM3('start') - '000-' - NUM3('end') - 'FFF' - Literal('(base 16)') - text_eol('text2')) elif type == 'medium': vendor_line = (NUM1('start') - '00000-' - NUM1('end') - 'FFFFF' - Literal('(base 16)') - text_eol('text2')) else: assert type == 'large' vendor_line = (NUM6('start') - Literal('(base 16)') - text_eol('text2')) extra_line = TAB - TAB - TAB - TAB - SkipTo(EOL) vendor = prefix_line + vendor_line + ZeroOrMore(extra_line) + Optional(EMPTYLINE) grammar = (Literal('OUI') + text_eol('header') + text_eol('header') + text_eol('header') + EMPTYLINE + OneOrMore(vendor('VENDORS*')) + stringEnd()) grammar.parseWithTabs() return grammar def header(file, *sources): print('''\ # This file is part of systemd. # # Data imported from:{}{}'''.format(' ' if len(sources) == 1 else '\n# ', '\n# '.join(sources)), file=file) def add_item(items, key, value): if key in items: print(f'Ignoring duplicate entry: {key} = "{items[key]}", "{value}"') else: items[key] = value def usb_vendor_model(p): items = {} for vendor_group in p.VENDORS: vendor = vendor_group.VENDOR.vendor.upper() text = vendor_group.VENDOR.text.strip() add_item(items, (vendor,), text) for vendor_dev in vendor_group.VENDOR_DEV: device = vendor_dev.device.upper() text = vendor_dev.text.strip() add_item(items, (vendor, device), text) with open('20-usb-vendor-model.hwdb', 'wt') as out: header(out, 'http://www.linux-usb.org/usb.ids') for key in sorted(items): if len(key) == 1: p, n = 'usb:v{}*', 'VENDOR' else: p, n = 'usb:v{}p{}*', 'MODEL', print('', p.format(*key), f' ID_{n}_FROM_DATABASE={items[key]}', sep='\n', file=out) print(f'Wrote {out.name}') def usb_classes(p): items = {} for klass_group in p.CLASSES: klass = klass_group.KLASS.klass.upper() text = klass_group.KLASS.text.strip() if klass != '00' and not re.match(r'(\?|None|Unused)\s*$', text): add_item(items, (klass,), text) for subclass_group in klass_group.SUBCLASSES: subclass = subclass_group.subclass.upper() text = subclass_group.text.strip() if subclass != '00' and not re.match(r'(\?|None|Unused)\s*$', text): add_item(items, (klass, subclass), text) for protocol_group in subclass_group.PROTOCOLS: protocol = protocol_group.protocol.upper() text = protocol_group.name.strip() if klass != '00' and not re.match(r'(\?|None|Unused)\s*$', text): add_item(items, (klass, subclass, protocol), text) with open('20-usb-classes.hwdb', 'wt') as out: header(out, 'http://www.linux-usb.org/usb.ids') for key in sorted(items): if len(key) == 1: p, n = 'usb:v*p*d*dc{}*', 'CLASS' elif len(key) == 2: p, n = 'usb:v*p*d*dc{}dsc{}*', 'SUBCLASS' else: p, n = 'usb:v*p*d*dc{}dsc{}dp{}*', 'PROTOCOL' print('', p.format(*key), f' ID_USB_{n}_FROM_DATABASE={items[key]}', sep='\n', file=out) print(f'Wrote {out.name}') def pci_vendor_model(p): items = {} for vendor_group in p.VENDORS: vendor = vendor_group.VENDOR.vendor.upper() text = vendor_group.VENDOR.text.strip() add_item(items, (vendor,), text) for device_group in vendor_group.DEVICES: device = device_group.device.upper() text = device_group.text.strip() add_item(items, (vendor, device), text) for subvendor_group in device_group.SUBVENDORS: sub_vendor = subvendor_group.a.upper() sub_model = subvendor_group.b.upper() sub_text = subvendor_group.name.strip() if sub_text.startswith(text): sub_text = sub_text[len(text):].lstrip() if sub_text: sub_text = f' ({sub_text})' add_item(items, (vendor, device, sub_vendor, sub_model), text + sub_text) with open('20-pci-vendor-model.hwdb', 'wt') as out: header(out, 'http://pci-ids.ucw.cz/v2.2/pci.ids') for key in sorted(items): if len(key) == 1: p, n = 'pci:v0000{}*', 'VENDOR' elif len(key) == 2: p, n = 'pci:v0000{}d0000{}*', 'MODEL' else: p, n = 'pci:v0000{}d0000{}sv0000{}sd0000{}*', 'MODEL' print('', p.format(*key), f' ID_{n}_FROM_DATABASE={items[key]}', sep='\n', file=out) print(f'Wrote {out.name}') def pci_classes(p): items = {} for klass_group in p.CLASSES: klass = klass_group.KLASS.klass.upper() text = klass_group.KLASS.text.strip() add_item(items, (klass,), text) for subclass_group in klass_group.SUBCLASSES: subclass = subclass_group.subclass.upper() text = subclass_group.text.strip() add_item(items, (klass, subclass), text) for protocol_group in subclass_group.PROTOCOLS: protocol = protocol_group.protocol.upper() text = protocol_group.name.strip() add_item(items, (klass, subclass, protocol), text) with open('20-pci-classes.hwdb', 'wt') as out: header(out, 'http://pci-ids.ucw.cz/v2.2/pci.ids') for key in sorted(items): if len(key) == 1: p, n = 'pci:v*d*sv*sd*bc{}*', 'CLASS' elif len(key) == 2: p, n = 'pci:v*d*sv*sd*bc{}sc{}*', 'SUBCLASS' else: p, n = 'pci:v*d*sv*sd*bc{}sc{}i{}*', 'INTERFACE' print('', p.format(*key), f' ID_PCI_{n}_FROM_DATABASE={items[key]}', sep='\n', file=out) print(f'Wrote {out.name}') def sdio_vendor_model(p): items = {} for vendor_group in p.VENDORS: vendor = vendor_group.VENDOR.vendor.upper() text = vendor_group.VENDOR.text.strip() add_item(items, (vendor,), text) for device_group in vendor_group.DEVICES: device = device_group.device.upper() text = device_group.text.strip() add_item(items, (vendor, device), text) with open('20-sdio-vendor-model.hwdb', 'wt') as out: header(out, 'hwdb/sdio.ids') for key in sorted(items): if len(key) == 1: p, n = 'sdio:c*v{}*', 'VENDOR' else: p, n = 'sdio:c*v{}d{}*', 'MODEL' print('', p.format(*key), f' ID_{n}_FROM_DATABASE={items[key]}', sep='\n', file=out) print(f'Wrote {out.name}') def sdio_classes(p): items = {} for klass_group in p.CLASSES: klass = klass_group.KLASS.klass.upper() text = klass_group.KLASS.text.strip() add_item(items, klass, text) with open('20-sdio-classes.hwdb', 'wt') as out: header(out, 'hwdb/sdio.ids') for klass in sorted(items): print(f'', f'sdio:c{klass}v*d*', f' ID_SDIO_CLASS_FROM_DATABASE={items[klass]}', sep='\n', file=out) print(f'Wrote {out.name}') # MAC Address Block Large/Medium/Small # Large MA-L 24/24 bit (OUI) # Medium MA-M 28/20 bit (OUI prefix owned by IEEE) # Small MA-S 36/12 bit (OUI prefix owned by IEEE) def oui(p1, p2, p3): prefixes = set() items = {} for p, check in ((p1, False), (p2, False), (p3, True)): for vendor_group in p.VENDORS: prefix = vendor_group.prefix.upper() if check: if prefix in prefixes: continue else: prefixes.add(prefix) start = vendor_group.start.upper() end = vendor_group.end.upper() if end and start != end: print(f'{prefix:} {start} != {end}', file=sys.stderr) text = vendor_group.text.strip() key = prefix + start if end else prefix add_item(items, key, text) with open('20-OUI.hwdb', 'wt') as out: header(out, 'https://services13.ieee.org/RST/standards-ra-web/rest/assignments/download/?registry=MA-L&format=txt', 'https://services13.ieee.org/RST/standards-ra-web/rest/assignments/download/?registry=MA-M&format=txt', 'https://services13.ieee.org/RST/standards-ra-web/rest/assignments/download/?registry=MA-S&format=txt') for pattern in sorted(items): print(f'', f'OUI:{pattern}*', f' ID_OUI_FROM_DATABASE={items[pattern]}', sep='\n', file=out) print(f'Wrote {out.name}') if __name__ == '__main__': args = sys.argv[1:] if not args or 'usb' in args: p = usb_ids_grammar().parseFile(open('usb.ids', errors='replace')) usb_vendor_model(p) usb_classes(p) if not args or 'pci' in args: p = pci_ids_grammar().parseFile(open('pci.ids', errors='replace')) pci_vendor_model(p) pci_classes(p) if not args or 'sdio' in args: p = pci_ids_grammar().parseFile(open('sdio.ids', errors='replace')) sdio_vendor_model(p) sdio_classes(p) if not args or 'oui' in args: p = oui_grammar('small').parseFile(open('ma-small.txt')) p2 = oui_grammar('medium').parseFile(open('ma-medium.txt')) p3 = oui_grammar('large').parseFile(open('ma-large.txt')) oui(p, p2, p3)
gpl-2.0
spraints/for-example
mercurial/lsprofcalltree.py
100
2760
""" lsprofcalltree.py - lsprof output which is readable by kcachegrind Authors: * David Allouche <david <at> allouche.net> * Jp Calderone & Itamar Shtull-Trauring * Johan Dahlin This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. """ def label(code): if isinstance(code, str): return '~' + code # built-in functions ('~' sorts at the end) else: return '%s %s:%d' % (code.co_name, code.co_filename, code.co_firstlineno) class KCacheGrind(object): def __init__(self, profiler): self.data = profiler.getstats() self.out_file = None def output(self, out_file): self.out_file = out_file print >> out_file, 'events: Ticks' self._print_summary() for entry in self.data: self._entry(entry) def _print_summary(self): max_cost = 0 for entry in self.data: totaltime = int(entry.totaltime * 1000) max_cost = max(max_cost, totaltime) print >> self.out_file, 'summary: %d' % (max_cost,) def _entry(self, entry): out_file = self.out_file code = entry.code #print >> out_file, 'ob=%s' % (code.co_filename,) if isinstance(code, str): print >> out_file, 'fi=~' else: print >> out_file, 'fi=%s' % (code.co_filename,) print >> out_file, 'fn=%s' % (label(code),) inlinetime = int(entry.inlinetime * 1000) if isinstance(code, str): print >> out_file, '0 ', inlinetime else: print >> out_file, '%d %d' % (code.co_firstlineno, inlinetime) # recursive calls are counted in entry.calls if entry.calls: calls = entry.calls else: calls = [] if isinstance(code, str): lineno = 0 else: lineno = code.co_firstlineno for subentry in calls: self._subentry(lineno, subentry) print >> out_file def _subentry(self, lineno, subentry): out_file = self.out_file code = subentry.code #print >> out_file, 'cob=%s' % (code.co_filename,) print >> out_file, 'cfn=%s' % (label(code),) if isinstance(code, str): print >> out_file, 'cfi=~' print >> out_file, 'calls=%d 0' % (subentry.callcount,) else: print >> out_file, 'cfi=%s' % (code.co_filename,) print >> out_file, 'calls=%d %d' % ( subentry.callcount, code.co_firstlineno) totaltime = int(subentry.totaltime * 1000) print >> out_file, '%d %d' % (lineno, totaltime)
gpl-2.0
basho/cache_proxy
tests/lib/server_modules.py
1
3306
#!/usr/bin/env python #coding: utf-8 #file : server_modules.py #author : ning #date : 2014-02-24 13:00:28 import os import sys from utils import * import conf class ServerBase: ''' Sub class should implement: _alive, _pre_deploy, status, and init self.args ''' def __init__(self, name, host, port, path): self.args = { 'name' : name, 'host' : host, 'port' : port, 'path' : path, #startcmd and runcmd will used to generate the control script #used for the start cmd 'startcmd' : '', #process name you see in `ps -aux`, used this to generate stop cmd 'runcmd' : '', 'logfile' : '', } def __str__(self): return TT('[$name:$host:$port]', self.args) def deploy(self): logging.info('deploy %s' % self) self._run(TTCMD('mkdir -p $path/bin && \ mkdir -p $path/conf && \ mkdir -p $path/log && \ mkdir -p $path/data', self.args)) self._pre_deploy() self._gen_control_script() def _gen_control_script(self): content = file(os.path.join(WORKDIR, 'conf/control.sh')).read() content = TT(content, self.args) control_filename = TT('${path}/${name}_control', self.args) fout = open(control_filename, 'w+') fout.write(content) fout.close() os.chmod(control_filename, 0755) def start(self): if self._alive(): logging.warn('%s already running' %(self) ) return logging.debug('starting %s' % self) t1 = time.time() sleeptime = .1 cmd = TT("cd $path && ./${name}_control start", self.args) print 'Cmd is: ' + cmd; self._run(cmd) while not self._alive(): lets_sleep(sleeptime) if sleeptime < 5: sleeptime *= 2 else: sleeptime = 5 logging.warn('%s still not alive' % self) t2 = time.time() logging.info('%s start ok in %.2f seconds' %(self, t2-t1) ) if not self._alive(): logging.debug('service is not reporting as alive after start') def stop(self): if not self._alive(): logging.warn('%s already stop' %(self) ) return cmd = TT("cd $path && ./${name}_control stop", self.args) self._run(cmd) t1 = time.time() while self._alive(): lets_sleep() t2 = time.time() logging.info('%s stop ok in %.2f seconds' %(self, t2-t1) ) def pid(self): cmd = TT("pgrep -f '^$runcmd'", self.args) return self._run(cmd) def status(self): logging.warn("status: not implement") def _alive(self): logging.warn("_alive: not implement") def _run(self, raw_cmd): ret = system(raw_cmd, logging.debug) logging.debug('return : [%d] [%s] ' % (len(ret), shorten(ret)) ) return ret def clean(self): cmd = TT("rm -rf $path", self.args) self._run(cmd) def host(self): return self.args['host'] def port(self): return self.args['port']
apache-2.0
xuewei4d/scikit-learn
sklearn/utils/tests/test_sparsefuncs.py
8
31943
import pytest import numpy as np import scipy.sparse as sp from scipy import linalg from numpy.testing import assert_array_almost_equal, assert_array_equal from numpy.random import RandomState from sklearn.datasets import make_classification from sklearn.utils.sparsefuncs import (mean_variance_axis, incr_mean_variance_axis, inplace_column_scale, inplace_row_scale, inplace_swap_row, inplace_swap_column, min_max_axis, count_nonzero, csc_median_axis_0) from sklearn.utils.sparsefuncs_fast import (assign_rows_csr, inplace_csr_row_normalize_l1, inplace_csr_row_normalize_l2, csr_row_norms) from sklearn.utils._testing import assert_allclose def test_mean_variance_axis0(): X, _ = make_classification(5, 4, random_state=0) # Sparsify the array a little bit X[0, 0] = 0 X[2, 1] = 0 X[4, 3] = 0 X_lil = sp.lil_matrix(X) X_lil[1, 0] = 0 X[1, 0] = 0 with pytest.raises(TypeError): mean_variance_axis(X_lil, axis=0) X_csr = sp.csr_matrix(X_lil) X_csc = sp.csc_matrix(X_lil) expected_dtypes = [(np.float32, np.float32), (np.float64, np.float64), (np.int32, np.float64), (np.int64, np.float64)] for input_dtype, output_dtype in expected_dtypes: X_test = X.astype(input_dtype) for X_sparse in (X_csr, X_csc): X_sparse = X_sparse.astype(input_dtype) X_means, X_vars = mean_variance_axis(X_sparse, axis=0) assert X_means.dtype == output_dtype assert X_vars.dtype == output_dtype assert_array_almost_equal(X_means, np.mean(X_test, axis=0)) assert_array_almost_equal(X_vars, np.var(X_test, axis=0)) def test_mean_variance_axis1(): X, _ = make_classification(5, 4, random_state=0) # Sparsify the array a little bit X[0, 0] = 0 X[2, 1] = 0 X[4, 3] = 0 X_lil = sp.lil_matrix(X) X_lil[1, 0] = 0 X[1, 0] = 0 with pytest.raises(TypeError): mean_variance_axis(X_lil, axis=1) X_csr = sp.csr_matrix(X_lil) X_csc = sp.csc_matrix(X_lil) expected_dtypes = [(np.float32, np.float32), (np.float64, np.float64), (np.int32, np.float64), (np.int64, np.float64)] for input_dtype, output_dtype in expected_dtypes: X_test = X.astype(input_dtype) for X_sparse in (X_csr, X_csc): X_sparse = X_sparse.astype(input_dtype) X_means, X_vars = mean_variance_axis(X_sparse, axis=0) assert X_means.dtype == output_dtype assert X_vars.dtype == output_dtype assert_array_almost_equal(X_means, np.mean(X_test, axis=0)) assert_array_almost_equal(X_vars, np.var(X_test, axis=0)) @pytest.mark.parametrize(['Xw', 'X', 'weights'], [ ([[0, 0, 1], [0, 2, 3]], [[0, 0, 1], [0, 2, 3]], [1, 1, 1]), ([[0, 0, 1], [0, 1, 1]], [[0, 0, 0, 1], [0, 1, 1, 1]], [1, 2, 1]), ([[0, 0, 1], [0, 1, 1]], [[0, 0, 1], [0, 1, 1]], None), ([[0, np.nan, 2], [0, np.nan, np.nan]], [[0, np.nan, 2], [0, np.nan, np.nan]], [1., 1., 1.]), ([[0, 0], [1, np.nan], [2, 0], [0, 3], [np.nan, np.nan], [np.nan, 2]], [[0, 0, 0], [1, 1, np.nan], [2, 2, 0], [0, 0, 3], [np.nan, np.nan, np.nan], [np.nan, np.nan, 2]], [2., 1.]), ([[1, 0, 1], [0, 3, 1]], [[1, 0, 0, 0, 1], [0, 3, 3, 3, 1]], np.array([1, 3, 1])) ] ) @pytest.mark.parametrize("sparse_constructor", [sp.csc_matrix, sp.csr_matrix]) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_incr_mean_variance_axis_weighted_axis1(Xw, X, weights, sparse_constructor, dtype): axis = 1 Xw_sparse = sparse_constructor(Xw).astype(dtype) X_sparse = sparse_constructor(X).astype(dtype) last_mean = np.zeros(np.shape(Xw)[0], dtype=dtype) last_var = np.zeros_like(last_mean, dtype=dtype) last_n = np.zeros_like(last_mean, dtype=np.int64) means0, vars0, n_incr0 = incr_mean_variance_axis( X=X_sparse, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n, weights=None) means_w0, vars_w0, n_incr_w0 = incr_mean_variance_axis( X=Xw_sparse, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n, weights=weights) assert means_w0.dtype == dtype assert vars_w0.dtype == dtype assert n_incr_w0.dtype == dtype means_simple, vars_simple = mean_variance_axis(X=X_sparse, axis=axis) assert_array_almost_equal(means0, means_w0) assert_array_almost_equal(means0, means_simple) assert_array_almost_equal(vars0, vars_w0) assert_array_almost_equal(vars0, vars_simple) assert_array_almost_equal(n_incr0, n_incr_w0) # check second round for incremental means1, vars1, n_incr1 = incr_mean_variance_axis( X=X_sparse, axis=axis, last_mean=means0, last_var=vars0, last_n=n_incr0, weights=None) means_w1, vars_w1, n_incr_w1 = incr_mean_variance_axis( X=Xw_sparse, axis=axis, last_mean=means_w0, last_var=vars_w0, last_n=n_incr_w0, weights=weights) assert_array_almost_equal(means1, means_w1) assert_array_almost_equal(vars1, vars_w1) assert_array_almost_equal(n_incr1, n_incr_w1) assert means_w1.dtype == dtype assert vars_w1.dtype == dtype assert n_incr_w1.dtype == dtype @pytest.mark.parametrize(['Xw', 'X', 'weights'], [ ([[0, 0, 1], [0, 2, 3]], [[0, 0, 1], [0, 2, 3]], [1, 1]), ([[0, 0, 1], [0, 1, 1]], [[0, 0, 1], [0, 1, 1], [0, 1, 1]], [1, 2]), ([[0, 0, 1], [0, 1, 1]], [[0, 0, 1], [0, 1, 1]], None), ([[0, np.nan, 2], [0, np.nan, np.nan]], [[0, np.nan, 2], [0, np.nan, np.nan]], [1., 1.]), ([[0, 0, 1, np.nan, 2, 0], [0, 3, np.nan, np.nan, np.nan, 2]], [[0, 0, 1, np.nan, 2, 0], [0, 0, 1, np.nan, 2, 0], [0, 3, np.nan, np.nan, np.nan, 2]], [2., 1.]), ([[1, 0, 1], [0, 0, 1]], [[1, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]], np.array([1, 3])) ] ) @pytest.mark.parametrize("sparse_constructor", [sp.csc_matrix, sp.csr_matrix]) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_incr_mean_variance_axis_weighted_axis0(Xw, X, weights, sparse_constructor, dtype): axis = 0 Xw_sparse = sparse_constructor(Xw).astype(dtype) X_sparse = sparse_constructor(X).astype(dtype) last_mean = np.zeros(np.size(Xw, 1), dtype=dtype) last_var = np.zeros_like(last_mean) last_n = np.zeros_like(last_mean, dtype=np.int64) means0, vars0, n_incr0 = incr_mean_variance_axis( X=X_sparse, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n, weights=None) means_w0, vars_w0, n_incr_w0 = incr_mean_variance_axis( X=Xw_sparse, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n, weights=weights) assert means_w0.dtype == dtype assert vars_w0.dtype == dtype assert n_incr_w0.dtype == dtype means_simple, vars_simple = mean_variance_axis(X=X_sparse, axis=axis) assert_array_almost_equal(means0, means_w0) assert_array_almost_equal(means0, means_simple) assert_array_almost_equal(vars0, vars_w0) assert_array_almost_equal(vars0, vars_simple) assert_array_almost_equal(n_incr0, n_incr_w0) # check second round for incremental means1, vars1, n_incr1 = incr_mean_variance_axis( X=X_sparse, axis=axis, last_mean=means0, last_var=vars0, last_n=n_incr0, weights=None) means_w1, vars_w1, n_incr_w1 = incr_mean_variance_axis( X=Xw_sparse, axis=axis, last_mean=means_w0, last_var=vars_w0, last_n=n_incr_w0, weights=weights) assert_array_almost_equal(means1, means_w1) assert_array_almost_equal(vars1, vars_w1) assert_array_almost_equal(n_incr1, n_incr_w1) assert means_w1.dtype == dtype assert vars_w1.dtype == dtype assert n_incr_w1.dtype == dtype def test_incr_mean_variance_axis(): for axis in [0, 1]: rng = np.random.RandomState(0) n_features = 50 n_samples = 10 if axis == 0: data_chunks = [rng.randint(0, 2, size=n_features) for i in range(n_samples)] else: data_chunks = [rng.randint(0, 2, size=n_samples) for i in range(n_features)] # default params for incr_mean_variance last_mean = np.zeros(n_features) if axis == 0 else np.zeros(n_samples) last_var = np.zeros_like(last_mean) last_n = np.zeros_like(last_mean, dtype=np.int64) # Test errors X = np.array(data_chunks[0]) X = np.atleast_2d(X) X = X.T if axis == 1 else X X_lil = sp.lil_matrix(X) X_csr = sp.csr_matrix(X_lil) with pytest.raises(TypeError): incr_mean_variance_axis(X=axis, axis=last_mean, last_mean=last_var, last_var=last_n) with pytest.raises(TypeError): incr_mean_variance_axis(X_lil, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n) # Test _incr_mean_and_var with a 1 row input X_means, X_vars = mean_variance_axis(X_csr, axis) X_means_incr, X_vars_incr, n_incr = \ incr_mean_variance_axis(X_csr, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n) assert_array_almost_equal(X_means, X_means_incr) assert_array_almost_equal(X_vars, X_vars_incr) # X.shape[axis] picks # samples assert_array_equal(X.shape[axis], n_incr) X_csc = sp.csc_matrix(X_lil) X_means, X_vars = mean_variance_axis(X_csc, axis) assert_array_almost_equal(X_means, X_means_incr) assert_array_almost_equal(X_vars, X_vars_incr) assert_array_equal(X.shape[axis], n_incr) # Test _incremental_mean_and_var with whole data X = np.vstack(data_chunks) X = X.T if axis == 1 else X X_lil = sp.lil_matrix(X) X_csr = sp.csr_matrix(X_lil) X_csc = sp.csc_matrix(X_lil) expected_dtypes = [(np.float32, np.float32), (np.float64, np.float64), (np.int32, np.float64), (np.int64, np.float64)] for input_dtype, output_dtype in expected_dtypes: for X_sparse in (X_csr, X_csc): X_sparse = X_sparse.astype(input_dtype) last_mean = last_mean.astype(output_dtype) last_var = last_var.astype(output_dtype) X_means, X_vars = mean_variance_axis(X_sparse, axis) X_means_incr, X_vars_incr, n_incr = \ incr_mean_variance_axis(X_sparse, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n) assert X_means_incr.dtype == output_dtype assert X_vars_incr.dtype == output_dtype assert_array_almost_equal(X_means, X_means_incr) assert_array_almost_equal(X_vars, X_vars_incr) assert_array_equal(X.shape[axis], n_incr) @pytest.mark.parametrize( "sparse_constructor", [sp.csc_matrix, sp.csr_matrix] ) def test_incr_mean_variance_axis_dim_mismatch(sparse_constructor): """Check that we raise proper error when axis=1 and the dimension mismatch. Non-regression test for: https://github.com/scikit-learn/scikit-learn/pull/18655 """ n_samples, n_features = 60, 4 rng = np.random.RandomState(42) X = sparse_constructor(rng.rand(n_samples, n_features)) last_mean = np.zeros(n_features) last_var = np.zeros_like(last_mean) last_n = np.zeros(last_mean.shape, dtype=np.int64) kwargs = dict(last_mean=last_mean, last_var=last_var, last_n=last_n) mean0, var0, _ = incr_mean_variance_axis(X, axis=0, **kwargs) assert_allclose(np.mean(X.toarray(), axis=0), mean0) assert_allclose(np.var(X.toarray(), axis=0), var0) # test ValueError if axis=1 and last_mean.size == n_features with pytest.raises(ValueError): incr_mean_variance_axis(X, axis=1, **kwargs) # test inconsistent shapes of last_mean, last_var, last_n kwargs = dict(last_mean=last_mean[:-1], last_var=last_var, last_n=last_n) with pytest.raises(ValueError): incr_mean_variance_axis(X, axis=0, **kwargs) @pytest.mark.parametrize( "X1, X2", [ (sp.random(5, 2, density=0.8, format='csr', random_state=0), sp.random(13, 2, density=0.8, format='csr', random_state=0)), (sp.random(5, 2, density=0.8, format='csr', random_state=0), sp.hstack([sp.csr_matrix(np.full((13, 1), fill_value=np.nan)), sp.random(13, 1, density=0.8, random_state=42)], format="csr")) ] ) def test_incr_mean_variance_axis_equivalence_mean_variance(X1, X2): # non-regression test for: # https://github.com/scikit-learn/scikit-learn/issues/16448 # check that computing the incremental mean and variance is equivalent to # computing the mean and variance on the stacked dataset. axis = 0 last_mean, last_var = np.zeros(X1.shape[1]), np.zeros(X1.shape[1]) last_n = np.zeros(X1.shape[1], dtype=np.int64) updated_mean, updated_var, updated_n = incr_mean_variance_axis( X1, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n ) updated_mean, updated_var, updated_n = incr_mean_variance_axis( X2, axis=axis, last_mean=updated_mean, last_var=updated_var, last_n=updated_n ) X = sp.vstack([X1, X2]) assert_allclose(updated_mean, np.nanmean(X.A, axis=axis)) assert_allclose(updated_var, np.nanvar(X.A, axis=axis)) assert_allclose(updated_n, np.count_nonzero(~np.isnan(X.A), axis=0)) def test_incr_mean_variance_no_new_n(): # check the behaviour when we update the variance with an empty matrix axis = 0 X1 = sp.random(5, 1, density=0.8, random_state=0).tocsr() X2 = sp.random(0, 1, density=0.8, random_state=0).tocsr() last_mean, last_var = np.zeros(X1.shape[1]), np.zeros(X1.shape[1]) last_n = np.zeros(X1.shape[1], dtype=np.int64) last_mean, last_var, last_n = incr_mean_variance_axis( X1, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n ) # update statistic with a column which should ignored updated_mean, updated_var, updated_n = incr_mean_variance_axis( X2, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n ) assert_allclose(updated_mean, last_mean) assert_allclose(updated_var, last_var) assert_allclose(updated_n, last_n) def test_incr_mean_variance_n_float(): # check the behaviour when last_n is just a number axis = 0 X = sp.random(5, 2, density=0.8, random_state=0).tocsr() last_mean, last_var = np.zeros(X.shape[1]), np.zeros(X.shape[1]) last_n = 0 _, _, new_n = incr_mean_variance_axis( X, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n ) assert_allclose(new_n, np.full(X.shape[1], X.shape[0])) @pytest.mark.parametrize("axis", [0, 1]) @pytest.mark.parametrize("sparse_constructor", [sp.csc_matrix, sp.csr_matrix]) def test_incr_mean_variance_axis_ignore_nan(axis, sparse_constructor): old_means = np.array([535., 535., 535., 535.]) old_variances = np.array([4225., 4225., 4225., 4225.]) old_sample_count = np.array([2, 2, 2, 2], dtype=np.int64) X = sparse_constructor( np.array([[170, 170, 170, 170], [430, 430, 430, 430], [300, 300, 300, 300]])) X_nan = sparse_constructor( np.array([[170, np.nan, 170, 170], [np.nan, 170, 430, 430], [430, 430, np.nan, 300], [300, 300, 300, np.nan]])) # we avoid creating specific data for axis 0 and 1: translating the data is # enough. if axis: X = X.T X_nan = X_nan.T # take a copy of the old statistics since they are modified in place. X_means, X_vars, X_sample_count = incr_mean_variance_axis( X, axis=axis, last_mean=old_means.copy(), last_var=old_variances.copy(), last_n=old_sample_count.copy()) X_nan_means, X_nan_vars, X_nan_sample_count = incr_mean_variance_axis( X_nan, axis=axis, last_mean=old_means.copy(), last_var=old_variances.copy(), last_n=old_sample_count.copy()) assert_allclose(X_nan_means, X_means) assert_allclose(X_nan_vars, X_vars) assert_allclose(X_nan_sample_count, X_sample_count) def test_mean_variance_illegal_axis(): X, _ = make_classification(5, 4, random_state=0) # Sparsify the array a little bit X[0, 0] = 0 X[2, 1] = 0 X[4, 3] = 0 X_csr = sp.csr_matrix(X) with pytest.raises(ValueError): mean_variance_axis(X_csr, axis=-3) with pytest.raises(ValueError): mean_variance_axis(X_csr, axis=2) with pytest.raises(ValueError): mean_variance_axis(X_csr, axis=-1) with pytest.raises(ValueError): incr_mean_variance_axis(X_csr, axis=-3, last_mean=None, last_var=None, last_n=None) with pytest.raises(ValueError): incr_mean_variance_axis(X_csr, axis=2, last_mean=None, last_var=None, last_n=None) with pytest.raises(ValueError): incr_mean_variance_axis(X_csr, axis=-1, last_mean=None, last_var=None, last_n=None) def test_densify_rows(): for dtype in (np.float32, np.float64): X = sp.csr_matrix([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=dtype) X_rows = np.array([0, 2, 3], dtype=np.intp) out = np.ones((6, X.shape[1]), dtype=dtype) out_rows = np.array([1, 3, 4], dtype=np.intp) expect = np.ones_like(out) expect[out_rows] = X[X_rows, :].toarray() assign_rows_csr(X, X_rows, out_rows, out) assert_array_equal(out, expect) def test_inplace_column_scale(): rng = np.random.RandomState(0) X = sp.rand(100, 200, 0.05) Xr = X.tocsr() Xc = X.tocsc() XA = X.toarray() scale = rng.rand(200) XA *= scale inplace_column_scale(Xc, scale) inplace_column_scale(Xr, scale) assert_array_almost_equal(Xr.toarray(), Xc.toarray()) assert_array_almost_equal(XA, Xc.toarray()) assert_array_almost_equal(XA, Xr.toarray()) with pytest.raises(TypeError): inplace_column_scale(X.tolil(), scale) X = X.astype(np.float32) scale = scale.astype(np.float32) Xr = X.tocsr() Xc = X.tocsc() XA = X.toarray() XA *= scale inplace_column_scale(Xc, scale) inplace_column_scale(Xr, scale) assert_array_almost_equal(Xr.toarray(), Xc.toarray()) assert_array_almost_equal(XA, Xc.toarray()) assert_array_almost_equal(XA, Xr.toarray()) with pytest.raises(TypeError): inplace_column_scale(X.tolil(), scale) def test_inplace_row_scale(): rng = np.random.RandomState(0) X = sp.rand(100, 200, 0.05) Xr = X.tocsr() Xc = X.tocsc() XA = X.toarray() scale = rng.rand(100) XA *= scale.reshape(-1, 1) inplace_row_scale(Xc, scale) inplace_row_scale(Xr, scale) assert_array_almost_equal(Xr.toarray(), Xc.toarray()) assert_array_almost_equal(XA, Xc.toarray()) assert_array_almost_equal(XA, Xr.toarray()) with pytest.raises(TypeError): inplace_column_scale(X.tolil(), scale) X = X.astype(np.float32) scale = scale.astype(np.float32) Xr = X.tocsr() Xc = X.tocsc() XA = X.toarray() XA *= scale.reshape(-1, 1) inplace_row_scale(Xc, scale) inplace_row_scale(Xr, scale) assert_array_almost_equal(Xr.toarray(), Xc.toarray()) assert_array_almost_equal(XA, Xc.toarray()) assert_array_almost_equal(XA, Xr.toarray()) with pytest.raises(TypeError): inplace_column_scale(X.tolil(), scale) def test_inplace_swap_row(): X = np.array([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) swap = linalg.get_blas_funcs(('swap',), (X,)) swap = swap[0] X[0], X[-1] = swap(X[0], X[-1]) inplace_swap_row(X_csr, 0, -1) inplace_swap_row(X_csc, 0, -1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) X[2], X[3] = swap(X[2], X[3]) inplace_swap_row(X_csr, 2, 3) inplace_swap_row(X_csc, 2, 3) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) with pytest.raises(TypeError): inplace_swap_row(X_csr.tolil()) X = np.array([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float32) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) swap = linalg.get_blas_funcs(('swap',), (X,)) swap = swap[0] X[0], X[-1] = swap(X[0], X[-1]) inplace_swap_row(X_csr, 0, -1) inplace_swap_row(X_csc, 0, -1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) X[2], X[3] = swap(X[2], X[3]) inplace_swap_row(X_csr, 2, 3) inplace_swap_row(X_csc, 2, 3) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) with pytest.raises(TypeError): inplace_swap_row(X_csr.tolil()) def test_inplace_swap_column(): X = np.array([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) swap = linalg.get_blas_funcs(('swap',), (X,)) swap = swap[0] X[:, 0], X[:, -1] = swap(X[:, 0], X[:, -1]) inplace_swap_column(X_csr, 0, -1) inplace_swap_column(X_csc, 0, -1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) X[:, 0], X[:, 1] = swap(X[:, 0], X[:, 1]) inplace_swap_column(X_csr, 0, 1) inplace_swap_column(X_csc, 0, 1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) with pytest.raises(TypeError): inplace_swap_column(X_csr.tolil()) X = np.array([[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float32) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) swap = linalg.get_blas_funcs(('swap',), (X,)) swap = swap[0] X[:, 0], X[:, -1] = swap(X[:, 0], X[:, -1]) inplace_swap_column(X_csr, 0, -1) inplace_swap_column(X_csc, 0, -1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) X[:, 0], X[:, 1] = swap(X[:, 0], X[:, 1]) inplace_swap_column(X_csr, 0, 1) inplace_swap_column(X_csc, 0, 1) assert_array_equal(X_csr.toarray(), X_csc.toarray()) assert_array_equal(X, X_csc.toarray()) assert_array_equal(X, X_csr.toarray()) with pytest.raises(TypeError): inplace_swap_column(X_csr.tolil()) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) @pytest.mark.parametrize("axis", [0, 1, None]) @pytest.mark.parametrize("sparse_format", [sp.csr_matrix, sp.csc_matrix]) @pytest.mark.parametrize( "missing_values, min_func, max_func, ignore_nan", [(0, np.min, np.max, False), (np.nan, np.nanmin, np.nanmax, True)] ) @pytest.mark.parametrize("large_indices", [True, False]) def test_min_max(dtype, axis, sparse_format, missing_values, min_func, max_func, ignore_nan, large_indices): X = np.array([[0, 3, 0], [2, -1, missing_values], [0, 0, 0], [9, missing_values, 7], [4, 0, 5]], dtype=dtype) X_sparse = sparse_format(X) if large_indices: X_sparse.indices = X_sparse.indices.astype('int64') X_sparse.indptr = X_sparse.indptr.astype('int64') mins_sparse, maxs_sparse = min_max_axis(X_sparse, axis=axis, ignore_nan=ignore_nan) assert_array_equal(mins_sparse, min_func(X, axis=axis)) assert_array_equal(maxs_sparse, max_func(X, axis=axis)) def test_min_max_axis_errors(): X = np.array([[0, 3, 0], [2, -1, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) with pytest.raises(TypeError): min_max_axis(X_csr.tolil(), axis=0) with pytest.raises(ValueError): min_max_axis(X_csr, axis=2) with pytest.raises(ValueError): min_max_axis(X_csc, axis=-3) def test_count_nonzero(): X = np.array([[0, 3, 0], [2, -1, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64) X_csr = sp.csr_matrix(X) X_csc = sp.csc_matrix(X) X_nonzero = X != 0 sample_weight = [.5, .2, .3, .1, .1] X_nonzero_weighted = X_nonzero * np.array(sample_weight)[:, None] for axis in [0, 1, -1, -2, None]: assert_array_almost_equal(count_nonzero(X_csr, axis=axis), X_nonzero.sum(axis=axis)) assert_array_almost_equal(count_nonzero(X_csr, axis=axis, sample_weight=sample_weight), X_nonzero_weighted.sum(axis=axis)) with pytest.raises(TypeError): count_nonzero(X_csc) with pytest.raises(ValueError): count_nonzero(X_csr, axis=2) assert (count_nonzero(X_csr, axis=0).dtype == count_nonzero(X_csr, axis=1).dtype) assert (count_nonzero(X_csr, axis=0, sample_weight=sample_weight).dtype == count_nonzero(X_csr, axis=1, sample_weight=sample_weight).dtype) # Check dtypes with large sparse matrices too # XXX: test fails on 32bit (Windows/Linux) try: X_csr.indices = X_csr.indices.astype(np.int64) X_csr.indptr = X_csr.indptr.astype(np.int64) assert (count_nonzero(X_csr, axis=0).dtype == count_nonzero(X_csr, axis=1).dtype) assert (count_nonzero(X_csr, axis=0, sample_weight=sample_weight).dtype == count_nonzero(X_csr, axis=1, sample_weight=sample_weight).dtype) except TypeError as e: assert ("according to the rule 'safe'" in e.args[0] and np.intp().nbytes < 8), e def test_csc_row_median(): # Test csc_row_median actually calculates the median. # Test that it gives the same output when X is dense. rng = np.random.RandomState(0) X = rng.rand(100, 50) dense_median = np.median(X, axis=0) csc = sp.csc_matrix(X) sparse_median = csc_median_axis_0(csc) assert_array_equal(sparse_median, dense_median) # Test that it gives the same output when X is sparse X = rng.rand(51, 100) X[X < 0.7] = 0.0 ind = rng.randint(0, 50, 10) X[ind] = -X[ind] csc = sp.csc_matrix(X) dense_median = np.median(X, axis=0) sparse_median = csc_median_axis_0(csc) assert_array_equal(sparse_median, dense_median) # Test for toy data. X = [[0, -2], [-1, -1], [1, 0], [2, 1]] csc = sp.csc_matrix(X) assert_array_equal(csc_median_axis_0(csc), np.array([0.5, -0.5])) X = [[0, -2], [-1, -5], [1, -3]] csc = sp.csc_matrix(X) assert_array_equal(csc_median_axis_0(csc), np.array([0., -3])) # Test that it raises an Error for non-csc matrices. with pytest.raises(TypeError): csc_median_axis_0(sp.csr_matrix(X)) def test_inplace_normalize(): ones = np.ones((10, 1)) rs = RandomState(10) for inplace_csr_row_normalize in (inplace_csr_row_normalize_l1, inplace_csr_row_normalize_l2): for dtype in (np.float64, np.float32): X = rs.randn(10, 5).astype(dtype) X_csr = sp.csr_matrix(X) for index_dtype in [np.int32, np.int64]: # csr_matrix will use int32 indices by default, # up-casting those to int64 when necessary if index_dtype is np.int64: X_csr.indptr = X_csr.indptr.astype(index_dtype) X_csr.indices = X_csr.indices.astype(index_dtype) assert X_csr.indices.dtype == index_dtype assert X_csr.indptr.dtype == index_dtype inplace_csr_row_normalize(X_csr) assert X_csr.dtype == dtype if inplace_csr_row_normalize is inplace_csr_row_normalize_l2: X_csr.data **= 2 assert_array_almost_equal(np.abs(X_csr).sum(axis=1), ones) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_csr_row_norms(dtype): # checks that csr_row_norms returns the same output as # scipy.sparse.linalg.norm, and that the dype is the same as X.dtype. X = sp.random(100, 10, format='csr', dtype=dtype, random_state=42) scipy_norms = sp.linalg.norm(X, axis=1)**2 norms = csr_row_norms(X) assert norms.dtype == dtype rtol = 1e-6 if dtype == np.float32 else 1e-7 assert_allclose(norms, scipy_norms, rtol=rtol)
bsd-3-clause
beni55/copperhead
tests/test_reduce.py
5
2870
# # Copyright 2012 NVIDIA Corporation # # 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 copperhead import * import numpy as np import unittest from create_tests import create_tests @cu def test_reduce(x, p): return reduce(op_add, x, p) @cu def test_sum(x): return sum(x) @cu def test_reduce_as_sum(x): return reduce(op_add, x, 0) @cu def test_any(x): return any(x) @cu def test_all(x): return all(x) @cu def test_min(x): return min(x) @cu def test_max(x): return max(x) class ReduceTest(unittest.TestCase): def setUp(self): source = [1,2,3,4,5] prefix = 1 self.golden_s = sum(source) self.golden_r = self.golden_s + prefix self.int32 = (np.array(source, dtype=np.int32), np.int32(prefix)) self.negative = [False, False, False, False, False] self.positive = [True, True, True, True, True] self.indeterminate = [False, True, False, True, False] def run_test(self, target, f, g, *args): with target: self.assertEqual(f(*args), g) @create_tests(*runtime.backends) def testReduce(self, target): self.run_test(target, test_reduce, self.golden_r, *self.int32) @create_tests(*runtime.backends) def testSum(self, target): self.run_test(target, test_sum, self.golden_s, self.int32[0]) @create_tests(*runtime.backends) def testSumAsReduce(self, target): self.run_test(target, test_reduce_as_sum, self.golden_s, self.int32[0]) @create_tests(*runtime.backends) def testAny(self, target): self.run_test(target, test_any, False, self.negative) self.run_test(target, test_any, True, self.positive) self.run_test(target, test_any, True, self.indeterminate) @create_tests(*runtime.backends) def testAll(self, target): self.run_test(target, test_all, False, self.negative) self.run_test(target, test_all, True, self.positive) self.run_test(target, test_all, False, self.indeterminate) @create_tests(*runtime.backends) def testMax(self, target): self.run_test(target, test_max, 5, self.int32[0]) @create_tests(*runtime.backends) def testMin(self, target): self.run_test(target, test_min, 1, self.int32[0]) if __name__ == "__main__": unittest.main()
apache-2.0
codrut3/tensorflow
tensorflow/contrib/factorization/python/ops/kmeans_test.py
13
19945
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for KMeans.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import time import numpy as np from sklearn.cluster import KMeans as SklearnKMeans # pylint: disable=g-import-not-at-top from tensorflow.contrib.factorization.python.ops import kmeans as kmeans_lib from tensorflow.python.estimator import run_config from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.platform import benchmark from tensorflow.python.platform import flags from tensorflow.python.platform import test from tensorflow.python.training import input as input_lib from tensorflow.python.training import queue_runner FLAGS = flags.FLAGS def normalize(x): return x / np.sqrt(np.sum(x * x, axis=-1, keepdims=True)) def cosine_similarity(x, y): return np.dot(normalize(x), np.transpose(normalize(y))) def make_random_centers(num_centers, num_dims, center_norm=500): return np.round( np.random.rand(num_centers, num_dims).astype(np.float32) * center_norm) def make_random_points(centers, num_points, max_offset=20): num_centers, num_dims = centers.shape assignments = np.random.choice(num_centers, num_points) offsets = np.round( np.random.randn(num_points, num_dims).astype(np.float32) * max_offset) return (centers[assignments] + offsets, assignments, np.add.reduce( offsets * offsets, 1)) class KMeansTestBase(test.TestCase): def input_fn(self, batch_size=None, points=None, randomize=None, num_epochs=None): """Returns an input_fn that randomly selects batches from given points.""" batch_size = batch_size or self.batch_size points = points if points is not None else self.points num_points = points.shape[0] if randomize is None: randomize = (self.use_mini_batch and self.mini_batch_steps_per_iteration <= 1) def _fn(): x = constant_op.constant(points) if batch_size == num_points: return input_lib.limit_epochs(x, num_epochs=num_epochs), None if randomize: indices = random_ops.random_uniform( constant_op.constant([batch_size]), minval=0, maxval=num_points - 1, dtype=dtypes.int32, seed=10) else: # We need to cycle through the indices sequentially. We create a queue # to maintain the list of indices. q = data_flow_ops.FIFOQueue(num_points, dtypes.int32, ()) # Conditionally initialize the Queue. def _init_q(): with ops.control_dependencies( [q.enqueue_many(math_ops.range(num_points))]): return control_flow_ops.no_op() init_q = control_flow_ops.cond(q.size() <= 0, _init_q, control_flow_ops.no_op) with ops.control_dependencies([init_q]): offsets = q.dequeue_many(batch_size) with ops.control_dependencies([q.enqueue_many(offsets)]): indices = array_ops.identity(offsets) batch = array_ops.gather(x, indices) return (input_lib.limit_epochs(batch, num_epochs=num_epochs), None) return _fn @staticmethod def config(tf_random_seed): return run_config.RunConfig().replace(tf_random_seed=tf_random_seed) @property def initial_clusters(self): return kmeans_lib.KMeansClustering.KMEANS_PLUS_PLUS_INIT @property def batch_size(self): return self.num_points @property def use_mini_batch(self): return False @property def mini_batch_steps_per_iteration(self): return 1 class KMeansTest(KMeansTestBase): def setUp(self): np.random.seed(3) self.num_centers = 5 self.num_dims = 2 self.num_points = 1000 self.true_centers = make_random_centers(self.num_centers, self.num_dims) self.points, _, self.scores = make_random_points(self.true_centers, self.num_points) self.true_score = np.add.reduce(self.scores) def _kmeans(self, relative_tolerance=None): return kmeans_lib.KMeansClustering( self.num_centers, initial_clusters=self.initial_clusters, distance_metric=kmeans_lib.KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE, use_mini_batch=self.use_mini_batch, mini_batch_steps_per_iteration=self.mini_batch_steps_per_iteration, random_seed=24, relative_tolerance=relative_tolerance) def test_clusters(self): kmeans = self._kmeans() kmeans.train(input_fn=self.input_fn(), steps=1) clusters = kmeans.cluster_centers() self.assertAllEqual(list(clusters.shape), [self.num_centers, self.num_dims]) def test_fit(self): kmeans = self._kmeans() kmeans.train(input_fn=self.input_fn(), steps=1) score1 = kmeans.score(input_fn=self.input_fn(batch_size=self.num_points)) steps = 10 * self.num_points // self.batch_size kmeans.train(input_fn=self.input_fn(), steps=steps) score2 = kmeans.score(input_fn=self.input_fn(batch_size=self.num_points)) self.assertTrue(score1 > score2) self.assertNear(self.true_score, score2, self.true_score * 0.05) def test_monitor(self): if self.use_mini_batch: # We don't test for use_mini_batch case since the loss value can be noisy. return kmeans = kmeans_lib.KMeansClustering( self.num_centers, initial_clusters=self.initial_clusters, distance_metric=kmeans_lib.KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE, use_mini_batch=self.use_mini_batch, mini_batch_steps_per_iteration=self.mini_batch_steps_per_iteration, config=self.config(14), random_seed=12, relative_tolerance=1e-4) kmeans.train( input_fn=self.input_fn(), # Force it to train until the relative tolerance monitor stops it. steps=None) score = kmeans.score(input_fn=self.input_fn(batch_size=self.num_points)) self.assertNear(self.true_score, score, self.true_score * 0.01) def test_infer(self): kmeans = self._kmeans() # Make a call to fit to initialize the cluster centers. max_steps = 1 kmeans.train(input_fn=self.input_fn(), max_steps=max_steps) clusters = kmeans.cluster_centers() # Make a small test set num_points = 10 points, true_assignments, true_offsets = make_random_points( clusters, num_points) input_fn = self.input_fn(batch_size=num_points, points=points, num_epochs=1) # Test predict assignments = list(kmeans.predict_cluster_index(input_fn)) self.assertAllEqual(assignments, true_assignments) # Test score score = kmeans.score(input_fn=lambda: (constant_op.constant(points), None)) self.assertNear(score, np.sum(true_offsets), 0.01 * score) # Test transform transform = list(kmeans.transform(input_fn)) true_transform = np.maximum( 0, np.sum(np.square(points), axis=1, keepdims=True) - 2 * np.dot(points, np.transpose(clusters)) + np.transpose( np.sum(np.square(clusters), axis=1, keepdims=True))) self.assertAllClose(transform, true_transform, rtol=0.05, atol=10) class KMeansTestMultiStageInit(KMeansTestBase): def test_random(self): points = np.array( [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]], dtype=np.float32) kmeans = kmeans_lib.KMeansClustering( num_clusters=points.shape[0], initial_clusters=kmeans_lib.KMeansClustering.RANDOM_INIT, distance_metric=kmeans_lib.KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE, use_mini_batch=True, mini_batch_steps_per_iteration=100, random_seed=24, relative_tolerance=None) kmeans.train( input_fn=self.input_fn(batch_size=1, points=points, randomize=False), steps=1) clusters = kmeans.cluster_centers() self.assertAllEqual(points, clusters) def test_kmeans_plus_plus_batch_just_right(self): points = np.array([[1, 2]], dtype=np.float32) kmeans = kmeans_lib.KMeansClustering( num_clusters=points.shape[0], initial_clusters=kmeans_lib.KMeansClustering.KMEANS_PLUS_PLUS_INIT, distance_metric=kmeans_lib.KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE, use_mini_batch=True, mini_batch_steps_per_iteration=100, random_seed=24, relative_tolerance=None) kmeans.train( input_fn=self.input_fn(batch_size=1, points=points, randomize=False), steps=1) clusters = kmeans.cluster_centers() self.assertAllEqual(points, clusters) def test_kmeans_plus_plus_batch_too_small(self): points = np.array( [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]], dtype=np.float32) kmeans = kmeans_lib.KMeansClustering( num_clusters=points.shape[0], initial_clusters=kmeans_lib.KMeansClustering.KMEANS_PLUS_PLUS_INIT, distance_metric=kmeans_lib.KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE, use_mini_batch=True, mini_batch_steps_per_iteration=100, random_seed=24, relative_tolerance=None) with self.assertRaisesOpError(AssertionError): kmeans.train( input_fn=self.input_fn(batch_size=4, points=points, randomize=False), steps=1) class MiniBatchKMeansTest(KMeansTest): @property def batch_size(self): return 50 @property def use_mini_batch(self): return True class FullBatchAsyncKMeansTest(KMeansTest): @property def batch_size(self): return 50 @property def use_mini_batch(self): return True @property def mini_batch_steps_per_iteration(self): return self.num_points // self.batch_size class KMeansCosineDistanceTest(KMeansTestBase): def setUp(self): self.points = np.array( [[2.5, 0.1], [2, 0.2], [3, 0.1], [4, 0.2], [0.1, 2.5], [0.2, 2], [0.1, 3], [0.2, 4]], dtype=np.float32) self.num_points = self.points.shape[0] self.true_centers = np.array( [ normalize( np.mean(normalize(self.points)[0:4, :], axis=0, keepdims=True))[0], normalize( np.mean(normalize(self.points)[4:, :], axis=0, keepdims=True))[0] ], dtype=np.float32) self.true_assignments = np.array([0] * 4 + [1] * 4) self.true_score = len(self.points) - np.tensordot( normalize(self.points), self.true_centers[self.true_assignments]) self.num_centers = 2 self.kmeans = kmeans_lib.KMeansClustering( self.num_centers, initial_clusters=kmeans_lib.KMeansClustering.RANDOM_INIT, distance_metric=kmeans_lib.KMeansClustering.COSINE_DISTANCE, use_mini_batch=self.use_mini_batch, mini_batch_steps_per_iteration=self.mini_batch_steps_per_iteration, config=self.config(3)) def test_fit(self): max_steps = 10 * self.num_points // self.batch_size self.kmeans.train(input_fn=self.input_fn(), max_steps=max_steps) centers = normalize(self.kmeans.cluster_centers()) centers = centers[centers[:, 0].argsort()] true_centers = self.true_centers[self.true_centers[:, 0].argsort()] self.assertAllClose(centers, true_centers, atol=0.04) def test_transform(self): self.kmeans.train(input_fn=self.input_fn(), steps=10) centers = normalize(self.kmeans.cluster_centers()) true_transform = 1 - cosine_similarity(self.points, centers) transform = list( self.kmeans.transform( input_fn=self.input_fn(batch_size=self.num_points, num_epochs=1))) self.assertAllClose(transform, true_transform, atol=1e-3) def test_predict(self): max_steps = 10 * self.num_points // self.batch_size self.kmeans.train(input_fn=self.input_fn(), max_steps=max_steps) centers = normalize(self.kmeans.cluster_centers()) assignments = list( self.kmeans.predict_cluster_index( input_fn=self.input_fn(num_epochs=1, batch_size=self.num_points))) self.assertAllClose( centers[assignments], self.true_centers[self.true_assignments], atol=1e-2) centers = centers[centers[:, 0].argsort()] true_centers = self.true_centers[self.true_centers[:, 0].argsort()] self.assertAllClose(centers, true_centers, atol=0.04) score = self.kmeans.score( input_fn=self.input_fn(batch_size=self.num_points)) self.assertAllClose(score, self.true_score, atol=1e-2) def test_predict_kmeans_plus_plus(self): # Most points are concetrated near one center. KMeans++ is likely to find # the less populated centers. points = np.array( [[2.5, 3.5], [2.5, 3.5], [-2, 3], [-2, 3], [-3, -3], [-3.1, -3.2], [-2.8, -3.], [-2.9, -3.1], [-3., -3.1], [-3., -3.1], [-3.2, -3.], [-3., -3.]], dtype=np.float32) true_centers = np.array( [ normalize( np.mean(normalize(points)[0:2, :], axis=0, keepdims=True))[0], normalize( np.mean(normalize(points)[2:4, :], axis=0, keepdims=True))[0], normalize(np.mean(normalize(points)[4:, :], axis=0, keepdims=True))[0] ], dtype=np.float32) true_assignments = [0] * 2 + [1] * 2 + [2] * 8 true_score = len(points) - np.tensordot( normalize(points), true_centers[true_assignments]) kmeans = kmeans_lib.KMeansClustering( 3, initial_clusters=self.initial_clusters, distance_metric=kmeans_lib.KMeansClustering.COSINE_DISTANCE, use_mini_batch=self.use_mini_batch, mini_batch_steps_per_iteration=self.mini_batch_steps_per_iteration, config=self.config(3)) kmeans.train( input_fn=lambda: (constant_op.constant(points), None), steps=30) centers = normalize(kmeans.cluster_centers()) self.assertAllClose( sorted(centers.tolist()), sorted(true_centers.tolist()), atol=1e-2) def _input_fn(): return (input_lib.limit_epochs( constant_op.constant(points), num_epochs=1), None) assignments = list(kmeans.predict_cluster_index(input_fn=_input_fn)) self.assertAllClose( centers[assignments], true_centers[true_assignments], atol=1e-2) score = kmeans.score(input_fn=lambda: (constant_op.constant(points), None)) self.assertAllClose(score, true_score, atol=1e-2) class MiniBatchKMeansCosineTest(KMeansCosineDistanceTest): @property def batch_size(self): return 2 @property def use_mini_batch(self): return True class FullBatchAsyncKMeansCosineTest(KMeansCosineDistanceTest): @property def batch_size(self): return 2 @property def use_mini_batch(self): return True @property def mini_batch_steps_per_iteration(self): return self.num_points // self.batch_size class KMeansBenchmark(benchmark.Benchmark): """Base class for benchmarks.""" def SetUp(self, dimension=50, num_clusters=50, points_per_cluster=10000, center_norm=500, cluster_width=20): np.random.seed(123456) self.num_clusters = num_clusters self.num_points = num_clusters * points_per_cluster self.centers = make_random_centers( self.num_clusters, dimension, center_norm=center_norm) self.points, _, scores = make_random_points( self.centers, self.num_points, max_offset=cluster_width) self.score = float(np.sum(scores)) def _report(self, num_iters, start, end, scores): print(scores) self.report_benchmark( iters=num_iters, wall_time=(end - start) / num_iters, extras={'true_sum_squared_distances': self.score, 'fit_scores': scores}) def _fit(self, num_iters=10): pass def benchmark_01_2dim_5center_500point(self): self.SetUp(dimension=2, num_clusters=5, points_per_cluster=100) self._fit() def benchmark_02_20dim_20center_10kpoint(self): self.SetUp(dimension=20, num_clusters=20, points_per_cluster=500) self._fit() def benchmark_03_100dim_50center_50kpoint(self): self.SetUp(dimension=100, num_clusters=50, points_per_cluster=1000) self._fit() def benchmark_03_100dim_50center_50kpoint_unseparated(self): self.SetUp( dimension=100, num_clusters=50, points_per_cluster=1000, cluster_width=250) self._fit() def benchmark_04_100dim_500center_500kpoint(self): self.SetUp(dimension=100, num_clusters=500, points_per_cluster=1000) self._fit(num_iters=4) def benchmark_05_100dim_500center_500kpoint_unseparated(self): self.SetUp( dimension=100, num_clusters=500, points_per_cluster=1000, cluster_width=250) self._fit(num_iters=4) class TensorflowKMeansBenchmark(KMeansBenchmark): def _fit(self, num_iters=10): scores = [] start = time.time() for i in range(num_iters): print('Starting tensorflow KMeans: %d' % i) tf_kmeans = kmeans_lib.KMeansClustering( self.num_clusters, initial_clusters=kmeans_lib.KMeansClustering.KMEANS_PLUS_PLUS_INIT, kmeans_plus_plus_num_retries=int(math.log(self.num_clusters) + 2), random_seed=i * 42, relative_tolerance=1e-6, config=self.config(3)) tf_kmeans.train( input_fn=lambda: (constant_op.constant(self.points), None), steps=50) _ = tf_kmeans.cluster_centers() scores.append( tf_kmeans.score( input_fn=lambda: (constant_op.constant(self.points), None))) self._report(num_iters, start, time.time(), scores) class SklearnKMeansBenchmark(KMeansBenchmark): def _fit(self, num_iters=10): scores = [] start = time.time() for i in range(num_iters): print('Starting sklearn KMeans: %d' % i) sklearn_kmeans = SklearnKMeans( n_clusters=self.num_clusters, init='k-means++', max_iter=50, n_init=1, tol=1e-4, random_state=i * 42) sklearn_kmeans.train(self.points) scores.append(sklearn_kmeans.inertia_) self._report(num_iters, start, time.time(), scores) class KMeansTestQueues(test.TestCase): def input_fn(self): def _fn(): queue = data_flow_ops.FIFOQueue( capacity=10, dtypes=dtypes.float32, shapes=[10, 3]) enqueue_op = queue.enqueue(array_ops.zeros([10, 3], dtype=dtypes.float32)) queue_runner.add_queue_runner( queue_runner.QueueRunner(queue, [enqueue_op])) return queue.dequeue(), None return _fn # This test makes sure that there are no deadlocks when using a QueueRunner. # Note that since cluster initialization is dependendent on inputs, if input # is generated using a QueueRunner, one has to make sure that these runners # are started before the initialization. def test_queues(self): kmeans = kmeans_lib.KMeansClustering(5) kmeans.train(input_fn=self.input_fn(), steps=1) if __name__ == '__main__': test.main()
apache-2.0
ClearCorp-dev/odoo-clearcorp
TODO-8.0/sale_max_discount/account_invoice.py
3
3250
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Addons modules by CLEARCORP S.A. # Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv, fields from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp class Invoice(osv.Model): _inherit = 'account.invoice' def invoice_validate(self, cr, uid, ids, context=None): # Check if user is in group 'group_account_invoice_limit_discount' if not self.pool.get('res.users').has_group(cr, uid, 'sale_max_discount.group_sale_max_discount'): for invoice in self.browse(cr, uid, ids, context=context): if invoice.type == 'out_invoice' or invoice.type == 'out_refund': pricelist = invoice.pricelist_id if pricelist and pricelist.discount_active: max_discount = [pricelist.max_discount] else: max_discount = [] for line in invoice.invoice_line: line_discount = max_discount if line.product_id: if line.product_id.categ_id.discount_active: line_discount.append(line.product_id.categ_id.max_discount) if line_discount: lower_discount = min(line_discount) if line.discount and line.discount > lower_discount: raise osv.except_osv(_('Discount Error'), _('The maximum discount for %s is %s.') %(line.name,lower_discount)) else: #Get company for user currently logged company = self.pool.get('res.users').browse(cr, uid, uid).company_id if company.limit_discount_active: max_company_discount = company.limit_discount_max_discount if line.discount > max_company_discount: raise osv.except_osv(_('Discount Error'), _('The discount for %s exceeds the' ' company\'s discount limit.') % line.name) return super(Invoice, self).invoice_validate(cr, uid, ids, context=context)
agpl-3.0
indeedops/dd-agent
checks.d/linux_proc_extras.py
7
3201
# (C) Cory Watson <cory@stripe.com> 2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # project from checks import AgentCheck from utils.subprocess_output import get_subprocess_output from collections import defaultdict PROCESS_STATES = { 'D': 'uninterruptible', 'R': 'runnable', 'S': 'sleeping', 'T': 'stopped', 'W': 'paging', 'X': 'dead', 'Z': 'zombie', } PROCESS_PRIOS = { '<': 'high', 'N': 'low', 'L': 'locked' } class MoreUnixCheck(AgentCheck): def check(self, instance): tags = instance.get('tags', []) state_counts = defaultdict(int) prio_counts = defaultdict(int) proc_location = self.agentConfig.get('procfs_path', '/proc').rstrip('/') proc_path_map = { "inode_info": "sys/fs/inode-nr", "stat_info": "stat", "entropy_info": "sys/kernel/random/entropy_avail", } for key, path in proc_path_map.iteritems(): proc_path_map[key] = "{procfs}/{path}".format(procfs=proc_location, path=path) with open(proc_path_map['inode_info'], 'r') as inode_info: inode_stats = inode_info.readline().split() self.gauge('system.inodes.total', float(inode_stats[0]), tags=tags) self.gauge('system.inodes.used', float(inode_stats[1]), tags=tags) with open(proc_path_map['stat_info'], 'r') as stat_info: lines = [line.strip() for line in stat_info.readlines()] for line in lines: if line.startswith('ctxt'): ctxt_count = float(line.split(' ')[1]) self.monotonic_count('system.linux.context_switches', ctxt_count, tags=tags) elif line.startswith('processes'): process_count = int(line.split(' ')[1]) self.monotonic_count('system.linux.processes_created', process_count, tags=tags) elif line.startswith('intr'): interrupts = int(line.split(' ')[1]) self.monotonic_count('system.linux.interrupts', interrupts, tags=tags) with open(proc_path_map['entropy_info'], 'r') as entropy_info: entropy = entropy_info.readline() self.gauge('system.entropy.available', float(entropy), tags=tags) ps = get_subprocess_output(['ps', '--no-header', '-eo', 'stat'], self.log) for state in ps[0]: # Each process state is a flag in a list of characters. See ps(1) for details. for flag in list(state): if state in PROCESS_STATES: state_counts[PROCESS_STATES[state]] += 1 elif state in PROCESS_PRIOS: prio_counts[PROCESS_PRIOS[state]] += 1 for state in state_counts: state_tags = list(tags) state_tags.append("state:" + state) self.gauge('system.processes.states', float(state_counts[state]), state_tags) for prio in prio_counts: prio_tags = list(tags) prio_tags.append("priority:" + prio) self.gauge('system.processes.priorities', float(prio_counts[prio]), prio_tags)
bsd-3-clause
mateor/pants
src/python/pants/backend/jvm/tasks/reports/junit_html_report.py
9
6018
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import glob import os import xml.etree.ElementTree as ET from functools import total_ordering from pants.base.mustache import MustacheRenderer from pants.util.dirutil import safe_mkdir from pants.util.meta import AbstractClass from pants.util.strutil import ensure_binary @total_ordering class ReportTestSuite(object): """Data object for a JUnit test suite""" def __init__(self, name, tests, errors, failures, skipped, time, testcases): self.name = name self.tests = int(tests) self.errors = int(errors) self.failures = int(failures) self.skipped = int(skipped) self.time = float(time) self.testcases = testcases def __lt__(self, other): if (self.errors, self.failures) > (other.errors, other.failures): return True elif (self.errors, self.failures) < (other.errors, other.failures): return False else: return self.name.lower() < other.name.lower() @staticmethod def success_rate(test_count, error_count, failure_count, skipped_count): if test_count: return '{:.2f}%'.format((test_count - (error_count + failure_count + skipped_count)) * 100.0 / test_count) return '0.00%' @staticmethod def icon_class(test_count, error_count, failure_count, skipped_count): icon_class = 'test-passed' if test_count == skipped_count: icon_class = 'test-skipped' elif error_count > 0: icon_class = 'test-error' elif failure_count > 0: icon_class = 'test-failure' return icon_class def as_dict(self): d = self.__dict__ d['success'] = ReportTestSuite.success_rate(self.tests, self.errors, self.failures, self.skipped) d['icon_class'] = ReportTestSuite.icon_class(self.tests, self.errors, self.failures, self.skipped) d['testcases'] = map(lambda tc: tc.as_dict(), self.testcases) return d class ReportTestCase(object): """Data object for a JUnit test case""" def __init__(self, name, time, failure, error, skipped): self.name = name self.time = float(time) self.failure = failure self.error = error self.skipped = skipped def icon_class(self): icon_class = 'test-passed' if self.skipped: icon_class = 'test-skipped' elif self.error: icon_class = 'test-error' elif self.failure: icon_class = 'test-failure' return icon_class def as_dict(self): d = {} d['name'] = self.name d['time'] = self.time d['icon_class'] = self.icon_class() if self.error: d['message'] = self.error['message'] elif self.failure: d['message'] = self.failure['message'] return d class JUnitHtmlReport(AbstractClass): """Generates an HTML report from JUnit TEST-*.xml files""" def report(self, xml_dir, report_dir): testsuites = self.parse_xml_files(xml_dir) safe_mkdir(report_dir) report_file_path = os.path.join(report_dir, 'junit-report.html') with open(report_file_path, 'w') as fp: fp.write(ensure_binary(self.generate_html(testsuites))) return report_file_path def parse_xml_files(self, xml_dir): testsuites = [] for xml_file in glob.glob(os.path.join(xml_dir, 'TEST-*.xml')): testsuites += self.parse_xml_file(xml_file) testsuites.sort() return testsuites def parse_xml_file(self, xml_file): testsuites = [] root = ET.parse(xml_file).getroot() testcases = [] for testcase in root.iter('testcase'): failure = None for f in testcase.iter('failure'): failure = { 'type': f.attrib['type'], 'message': f.text } error = None for e in testcase.iter('error'): error = { 'type': e.attrib['type'], 'message': e.text } skipped = False for _s in testcase.iter('skipped'): skipped = True testcases.append(ReportTestCase( testcase.attrib['name'], testcase.attrib.get('time', 0), failure, error, skipped )) for testsuite in root.iter('testsuite'): testsuites.append(ReportTestSuite( testsuite.attrib['name'], testsuite.attrib['tests'], testsuite.attrib['errors'], testsuite.attrib['failures'], testsuite.attrib.get('skipped', 0), testsuite.attrib['time'], testcases )) return testsuites def generate_html(self, testsuites): values = { 'total_tests': 0, 'total_errors': 0, 'total_failures': 0, 'total_skipped': 0, 'total_time': 0.0 } for testsuite in testsuites: values['total_tests'] += testsuite.tests values['total_errors'] += testsuite.errors values['total_failures'] += testsuite.failures values['total_skipped'] += testsuite.skipped values['total_time'] += testsuite.time values['total_success'] = ReportTestSuite.success_rate(values['total_tests'], values['total_errors'], values['total_failures'], values['total_skipped']) values['summary_icon_class'] = ReportTestSuite.icon_class(values['total_tests'], values['total_errors'], values['total_failures'], values['total_skipped']) values['testsuites'] = map(lambda ts: ts.as_dict(), testsuites) package_name, _, _ = __name__.rpartition('.') renderer = MustacheRenderer(package_name=package_name) html = renderer.render_name('junit_report.html', values) return html
apache-2.0
srager13/ns3_qoi_symptotics
src/tap-bridge/bindings/modulegen__gcc_LP64.py
12
261246
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.tap_bridge', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## data-rate.h (module 'network'): ns3::DataRate [class] module.add_class('DataRate', import_from_module='ns.network') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper [class] module.add_class('TapBridgeHelper') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::FdReader', 'ns3::empty', 'ns3::DefaultDeleter<ns3::FdReader>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::SystemThread', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SystemThread>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## system-thread.h (module 'core'): ns3::SystemThread [class] module.add_class('SystemThread', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## data-rate.h (module 'network'): ns3::DataRateChecker [class] module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## data-rate.h (module 'network'): ns3::DataRateValue [class] module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## unix-fd-reader.h (module 'core'): ns3::FdReader [class] module.add_class('FdReader', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge [class] module.add_class('TapBridge', parent=root_module['ns3::NetDevice']) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::Mode [enumeration] module.add_enum('Mode', ['ILLEGAL', 'CONFIGURE_LOCAL', 'USE_LOCAL', 'USE_BRIDGE'], outer_class=root_module['ns3::TapBridge']) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridgeFdReader [class] module.add_class('TapBridgeFdReader', parent=root_module['ns3::FdReader']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TapBridgeHelper_methods(root_module, root_module['ns3::TapBridgeHelper']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3FdReader_Ns3Empty_Ns3DefaultDeleter__lt__ns3FdReader__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3SystemThread_Ns3Empty_Ns3DefaultDeleter__lt__ns3SystemThread__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3SystemThread_methods(root_module, root_module['ns3::SystemThread']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker']) register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3FdReader_methods(root_module, root_module['ns3::FdReader']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3TapBridge_methods(root_module, root_module['ns3::TapBridge']) register_Ns3TapBridgeFdReader_methods(root_module, root_module['ns3::TapBridgeFdReader']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3DataRate_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('>=') ## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRate const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor] cls.add_constructor([param('uint64_t', 'bps')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor] cls.add_constructor([param('std::string', 'rate')]) ## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateTxTime', 'double', [param('uint32_t', 'bytes')], is_const=True) ## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function] cls.add_method('GetBitRate', 'uint64_t', [], is_const=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TapBridgeHelper_methods(root_module, cls): ## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper::TapBridgeHelper(ns3::TapBridgeHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::TapBridgeHelper const &', 'arg0')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper::TapBridgeHelper() [constructor] cls.add_constructor([]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper::TapBridgeHelper(ns3::Ipv4Address gateway) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'gateway')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::NetDevice> nd) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::NetDevice >', 'nd')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(std::string nodeName, ns3::Ptr<ns3::NetDevice> nd) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('std::string', 'nodeName'), param('ns3::Ptr< ns3::NetDevice >', 'nd')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(ns3::Ptr<ns3::Node> node, std::string ndName) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('ns3::Ptr< ns3::Node >', 'node'), param('std::string', 'ndName')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(std::string nodeName, std::string ndName) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('std::string', 'nodeName'), param('std::string', 'ndName')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::NetDevice> nd, ns3::AttributeValue const & bridgeType) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('ns3::AttributeValue const &', 'bridgeType')]) ## tap-bridge-helper.h (module 'tap-bridge'): void ns3::TapBridgeHelper::SetAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3FdReader_Ns3Empty_Ns3DefaultDeleter__lt__ns3FdReader__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::SimpleRefCount(ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter< ns3::FdReader > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3SystemThread_Ns3Empty_Ns3DefaultDeleter__lt__ns3SystemThread__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter< ns3::SystemThread > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SystemThread_methods(root_module, cls): ## system-thread.h (module 'core'): ns3::SystemThread::SystemThread(ns3::SystemThread const & arg0) [copy constructor] cls.add_constructor([param('ns3::SystemThread const &', 'arg0')]) ## system-thread.h (module 'core'): ns3::SystemThread::SystemThread(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [constructor] cls.add_constructor([param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## system-thread.h (module 'core'): static bool ns3::SystemThread::Equals(pthread_t id) [member function] cls.add_method('Equals', 'bool', [param('pthread_t', 'id')], is_static=True) ## system-thread.h (module 'core'): void ns3::SystemThread::Join() [member function] cls.add_method('Join', 'void', []) ## system-thread.h (module 'core'): static pthread_t ns3::SystemThread::Self() [member function] cls.add_method('Self', 'pthread_t', [], is_static=True) ## system-thread.h (module 'core'): void ns3::SystemThread::Start() [member function] cls.add_method('Start', 'void', []) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3DataRateChecker_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')]) return def register_Ns3DataRateValue_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor] cls.add_constructor([param('ns3::DataRate const &', 'value')]) ## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): bool ns3::DataRateValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function] cls.add_method('Get', 'ns3::DataRate', [], is_const=True) ## data-rate.h (module 'network'): std::string ns3::DataRateValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function] cls.add_method('Set', 'void', [param('ns3::DataRate const &', 'value')]) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3FdReader_methods(root_module, cls): ## unix-fd-reader.h (module 'core'): ns3::FdReader::FdReader(ns3::FdReader const & arg0) [copy constructor] cls.add_constructor([param('ns3::FdReader const &', 'arg0')]) ## unix-fd-reader.h (module 'core'): ns3::FdReader::FdReader() [constructor] cls.add_constructor([]) ## unix-fd-reader.h (module 'core'): void ns3::FdReader::Start(int fd, ns3::Callback<void, unsigned char*, long, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> readCallback) [member function] cls.add_method('Start', 'void', [param('int', 'fd'), param('ns3::Callback< void, unsigned char *, long, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'readCallback')]) ## unix-fd-reader.h (module 'core'): void ns3::FdReader::Stop() [member function] cls.add_method('Stop', 'void', []) ## unix-fd-reader.h (module 'core'): ns3::FdReader::Data ns3::FdReader::DoRead() [member function] cls.add_method('DoRead', 'ns3::FdReader::Data', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<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> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< 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 >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<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> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< 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 >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<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> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< 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 >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<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> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< 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 >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) return def register_Ns3TapBridge_methods(root_module, cls): ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::TapBridge(ns3::TapBridge const & arg0) [copy constructor] cls.add_constructor([param('ns3::TapBridge const &', 'arg0')]) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::TapBridge() [constructor] cls.add_constructor([]) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridge::GetBridgedNetDevice() [member function] cls.add_method('GetBridgedNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Ptr<ns3::Channel> ns3::TapBridge::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): uint32_t ns3::TapBridge::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::Mode ns3::TapBridge::GetMode() [member function] cls.add_method('GetMode', 'ns3::TapBridge::Mode', []) ## tap-bridge.h (module 'tap-bridge'): uint16_t ns3::TapBridge::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Ptr<ns3::Node> ns3::TapBridge::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): static ns3::TypeId ns3::TapBridge::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetBridgedNetDevice(ns3::Ptr<ns3::NetDevice> bridgedDevice) [member function] cls.add_method('SetBridgedNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'bridgedDevice')]) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetMode(ns3::TapBridge::Mode mode) [member function] cls.add_method('SetMode', 'void', [param('ns3::TapBridge::Mode', 'mode')]) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetPromiscReceiveCallback(ns3::Callback<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> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< 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 >', 'cb')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetReceiveCallback(ns3::Callback<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> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< 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 >', 'cb')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::Start(ns3::Time tStart) [member function] cls.add_method('Start', 'void', [param('ns3::Time', 'tStart')]) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::Stop(ns3::Time tStop) [member function] cls.add_method('Stop', 'void', [param('ns3::Time', 'tStop')]) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::DiscardFromBridgedDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Address const & src) [member function] cls.add_method('DiscardFromBridgedDevice', 'bool', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'src')], visibility='protected') ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::ReceiveFromBridgedDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Address const & src, ns3::Address const & dst, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('ReceiveFromBridgedDevice', 'bool', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'src'), param('ns3::Address const &', 'dst'), param('ns3::NetDevice::PacketType', 'packetType')], visibility='protected') return def register_Ns3TapBridgeFdReader_methods(root_module, cls): ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridgeFdReader::TapBridgeFdReader() [constructor] cls.add_constructor([]) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridgeFdReader::TapBridgeFdReader(ns3::TapBridgeFdReader const & arg0) [copy constructor] cls.add_constructor([param('ns3::TapBridgeFdReader const &', 'arg0')]) ## tap-bridge.h (module 'tap-bridge'): ns3::FdReader::Data ns3::TapBridgeFdReader::DoRead() [member function] cls.add_method('DoRead', 'ns3::FdReader::Data', [], visibility='private', is_virtual=True) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
gpl-2.0
tedlaz/pyted
misthodosia/m13/utils/apd.py
1
10147
# -*- coding: utf-8 -*- ''' Created on 18 Νοε 2012 @author: tedlaz ''' import textlines_data as td import utils.dbutils as adb import utils.tedutils as tu def lApd(): l0 = td.egrRow(td.ROWSUM) l0.addCol(td.egrCol(u'1.Τύπος εγγραφής',1,td.INT,1))#Πάντα 01 l0.addCol(td.egrCol(u'2.Πλήθος μέσων που προσκομίζονται',2,td.TEXT,'01')) #Πάντα 01 l0.addCol(td.egrCol(u'3.ΑΑ μέσου',2,td.TEXT,'01')) #Πάντα 01 l0.addCol(td.egrCol(u'4.Όνομα Αρχείου',8,td.TEXT,'CSL01')) l0.addCol(td.egrCol(u'5.Έκδοση',2,td.TEXT,'01')) l0.addCol(td.egrCol(u'6.Τύπος Δ΄΄ηλωσης',2,td.TEXT,'01')) # 01: Κανονική 02:Έκτακτη 03:επανυποβολή 04:Συμπληρωματική l0.addCol(td.egrCol(u'7.Υποκατάστημα ΙΚΑ Υποβολής',3,td.INT)) l0.addCol(td.egrCol(u'8.Ονομασία Υποκαταστήματος ΙΚΑ',50,td.TEXT)) l0.addCol(td.egrCol(u'9.Επωνυμία / Επώνυμο',80,td.TEXT)) l0.addCol(td.egrCol(u'10.Όνομα',30,td.TEXT)) l0.addCol(td.egrCol(u'11.Όνομα Πατρός',30,td.TEXT)) l0.addCol(td.egrCol(u'12.Α.Μ.Ε.',10,td.INT)) l0.addCol(td.egrCol(u'13.Α.Φ.Μ.',9, td.INT)) l0.addCol(td.egrCol(u'14.Οδός',50,td.TEXT)) l0.addCol(td.egrCol(u'15.Αριθμός',10,td.TEXT)) l0.addCol(td.egrCol(u'16.Ταχυδρομικός Κωδικός',5,td.INT)) l0.addCol(td.egrCol(u'17.Πόλη',30,td.TEXT)) l0.addCol(td.egrCol(u'18.Από μήνα',2,td.TEXT)) l0.addCol(td.egrCol(u'19.Από έτος',4,td.TEXT)) l0.addCol(td.egrCol(u'20.Έως μήνα',2,td.TEXT)) l0.addCol(td.egrCol(u'21.έως έτος',4,td.TEXT)) l0.addCol(td.egrCol(u'22.Σύνολο Ημερών Ασφάλισης',8,td.INT,'',2,14)) l0.addCol(td.egrCol(u'23.Σύνολο Αποδοχών',12,td.DEC,'',2,16)) l0.addCol(td.egrCol(u'24.Σύνολο Καταβλητέων Εισφορών',12,td.DEC,'',2,23)) l0.addCol(td.egrCol(u'25.Ημερομηνία υποβολής',8,td.TEXT)) l0.addCol(td.egrCol(u'26.Ημερομηνία παύσης εργασιών',8,td.TEXT)) l0.addCol(td.egrCol(u'27.Κενά',30,td.TEXT,'')) l1 = td.egrRow() l1.addCol(td.egrCol(u'28.Τύπος εγγραφής',1,td.INT,'2')) l1.addCol(td.egrCol(u'29.Αριθμός Μητρώου Ασφαλισμένου',9,td.INT)) l1.addCol(td.egrCol(u'30.Α.Μ.Κ.Α.',11,td.INT)) l1.addCol(td.egrCol(u'31.Επώνυμο Ασφαλισμένου',50,td.TEXT)) l1.addCol(td.egrCol(u'32.Όνομα Ασφαλισμένου',30,td.TEXT)) l1.addCol(td.egrCol(u'33.Όνομα Πατρός Ασφαλισμένου',30,td.TEXT)) l1.addCol(td.egrCol(u'34.Όνομα Μητρός Ασφαλισμένου',30,td.TEXT)) l1.addCol(td.egrCol(u'35.Ημερομηνία Γέννησης',8,td.TEXT)) l1.addCol(td.egrCol(u'36.Α.Φ.Μ.',9,td.INT)) l2 = td.egrRow() l2.addCol(td.egrCol(u'37.Τύπος Εγγραφής',1,td.INT,'3')) l2.addCol(td.egrCol(u'38.Αριθμός Παραρτήματος',4,td.INT,'1')) l2.addCol(td.egrCol(u'39.Κ.Α.Δ.',4,td.TEXT)) l2.addCol(td.egrCol(u'40.Πλήρες Ωράριο',1,td.INT,'0')) l2.addCol(td.egrCol(u'41.Όλες εργάσιμες',1,td.INT,'0')) l2.addCol(td.egrCol(u'42.Κυριακές',1,td.INT)) l2.addCol(td.egrCol(u'43.Κωδικός Ειδικότητας',6,td.INT)) l2.addCol(td.egrCol(u'44.Ειδικές περιπτώσεις ασφάλισης',2,td.INT,'')) l2.addCol(td.egrCol(u'45.Πακέτο Κάλυψης',4,td.INT)) l2.addCol(td.egrCol(u'46.Μισθολογική περίοδος - μήνας',2,td.INT)) l2.addCol(td.egrCol(u'47.Μισθολογική περίοδος - έτος',4,td.INT)) l2.addCol(td.egrCol(u'48.Από Ημερομηνία απασχόλησης',8,td.TEXT,'')) l2.addCol(td.egrCol(u'49.Έως Ημερομηνία απασχόλησης',8,td.TEXT,'')) l2.addCol(td.egrCol(u'50.Τύπος αποδοχών',2,td.INT)) l2.addCol(td.egrCol(u'51.Ημέρες ασφάλισης',3,td.INT)) l2.addCol(td.egrCol(u'52.Ημερομίσθιο',10,td.DEC)) l2.addCol(td.egrCol(u'53.Αποδοχές',10,td.DEC)) l2.addCol(td.egrCol(u'54.Εισφορές ασφαλισμένου',10,td.DEC)) l2.addCol(td.egrCol(u'55.Εισφορές εργοδότη',10,td.DEC)) l2.addCol(td.egrCol(u'56.Συνολικές Εισφορές',11,td.DEC)) l2.addCol(td.egrCol(u'57.Επιδότηση ασφαλισμένου (ποσό)',10,td.DEC,'')) l2.addCol(td.egrCol(u'58.Επιδότηση εργοδότη (%%)',5,td.DEC,'')) l2.addCol(td.egrCol(u'59.Επιδότηση εργοδότη (ποσό)',10,td.DEC,'')) l2.addCol(td.egrCol(u'60.Καταβλητέες εισφορές',11,td.DEC)) l3 = td.egrRow() l3.addCol(td.egrCol(u'61.Τέλος αρχείου',3,td.TEXT,'EOF')) return l0, l1,l2,l3 sql0= ''' SELECT ikac,ikap,cop,ono,pat,ame,afm,odo,num,tk,pol,perapo,xrisi,pereos FROM m12_co,m12_xrisi,m12_trimino WHERE m12_xrisi.id=%s AND m12_trimino.id=%s ''' sql0Minas =''' SELECT ikac,ikap,cop,ono,pat,ame,afm,odo,num,tk,pol,perapo,xrisi,pereos FROM m12_co,m12_xrisi,m12_apdp WHERE m12_xrisi.id=%s AND m12_apdp.id=%s ''' sql1 = ''' SELECT m12_mis.id, m12_period.trimino_id, m12_misd.pro_id, m12_fpr.aika, m12_fpr.amka, m12_fpr.epon, m12_fpr.onom,m12_fpr.patr,m12_fpr.mitr,m12_fpr.igen,m12_fpr.afm, m12_coy.kad,m12_eid.kad, sum( case when mtyp_id=110 then val end) as imeres, sum( case when mtyp_id=100 then val end) as imeromisthio, sum( case when mtyp_id=200 then val end) as apodoxes, sum( case when mtyp_id=500 then val end) as ikaEnos, sum( case when mtyp_id=501 then val end) as ikaEtis, sum( case when mtyp_id=502 then val end) as ika, sum( case when mtyp_id=503 then val end) as aptyp, sum( case when mtyp_id=504 then val end) as kpk, m12_period.period, m12_xrisi.xrisi FROM m12_misd INNER JOIN m12_mis on m12_mis.id = m12_misd.mis_id INNER JOIN m12_period on m12_period.id=m12_mis.period_id INNER JOIN m12_pro on m12_pro.id=m12_misd.pro_id INNER JOIN m12_fpr on m12_fpr.id=m12_pro.fpr_id INNER JOIN m12_coy on m12_coy.id=m12_pro.coy_id INNER JOIN m12_eid on m12_eid.id=m12_pro.eid_id INNER JOIN m12_xrisi on m12_xrisi.id=m12_mis.xrisi_id WHERE m12_mis.xrisi_id=%s AND m12_period.trimino_id=%s group by mis_id,pro_id order by pro_id ''' sql1Minas = ''' SELECT m12_mis.id, m12_period.id, m12_misd.pro_id, m12_fpr.aika, m12_fpr.amka, m12_fpr.epon, m12_fpr.onom,m12_fpr.patr,m12_fpr.mitr,m12_fpr.igen,m12_fpr.afm, m12_coy.kad,m12_eid.keid, sum( case when mtyp_id=110 then val end) as imeres, sum( case when mtyp_id=100 then val end) as imeromisthio, sum( case when mtyp_id=200 then val end) as apodoxes, sum( case when mtyp_id=500 then val end) as ikaEnos, sum( case when mtyp_id=501 then val end) as ikaEtis, sum( case when mtyp_id=502 then val end) as ika, sum( case when mtyp_id=503 then val end) as aptyp, sum( case when mtyp_id=504 then val end) as kpk, m12_period.period, m12_xrisi.xrisi, sum( case when mtyp_id=111 then val end) as kyriakes FROM m12_misd INNER JOIN m12_mis on m12_mis.id = m12_misd.mis_id INNER JOIN m12_period on m12_period.id=m12_mis.period_id INNER JOIN m12_pro on m12_pro.id=m12_misd.pro_id INNER JOIN m12_fpr on m12_fpr.id=m12_pro.fpr_id INNER JOIN m12_coy on m12_coy.id=m12_pro.coy_id INNER JOIN m12_eid on m12_eid.id=m12_pro.eid_id INNER JOIN m12_xrisi on m12_xrisi.id=m12_mis.xrisi_id WHERE m12_mis.xrisi_id=%s AND m12_period.id=%s group by mis_id,pro_id order by pro_id ''' def makeApd(xrisi,trimino,db): ''' 1. Συγκέντρωση στοιχείων εταιρείας 2. Συγκέντρωση στοιχείων εργαζομένων 3. Συγκέντρωση στοιχείων μισθοδοσιών ''' xrid = adb.getDbSingleVal("SELECT id FROM m12_xrisi WHERE xrisi='%s'" % xrisi, db) h = adb.getDbOneRow(sql0Minas % (xrid,trimino), db) arr = adb.getDbRows(sql1Minas % (xrid,trimino), db) if not h: return 'Error' if not arr: return 'Error' l0, l1, l2, l3 = lApd() doc = td.egrDoc([l0, l1,l2,l3]) doc.addLine(0, [u'',u'',u'',u'',u'',u'',h[0],tu.caps(h[1]),tu.caps(h[2]),tu.caps(h[3]),tu.caps(h[4]),h[5],h[6],tu.caps(h[7]),tu.caps(h[8]),h[9],tu.caps(h[10]),h[11],h[12],h[13],h[12],u'',u'',u'',tu.nowToStr(),u'',u'']) ergno=0 for lin in arr: if ergno == int(lin[2]): pass else: ergno = int(lin[2]) if lin[23] == None : l23 = 0 else: l23 = lin[23] doc.addLine(1, [u'',lin[3],lin[4],tu.caps(lin[5]),tu.caps(lin[6]),tu.caps(lin[7]),tu.caps(lin[8]),tu.dateTostr(lin[9]),lin[10]]) doc.addLine(2,[u'',u'',lin[11],u'',u'',l23,lin[12],u'',lin[20],lin[21],lin[22],u'',u'',lin[19],lin[13],lin[14],lin[15],lin[16],lin[17],lin[18],u'',u'',u'',lin[18]]) doc.addLine(3,[u'',]) return doc.__str__() def readAPD(fname='CSL01.txt'): f = open(fname) for line in f: if line[:1] == '1': print 'main' elif line[:1] == '2': print 'erg' elif line[:1] == '3': print 'mis' else: print 'final' def makeAPDfile(fname,xrisi,trimino,db): f = open(fname,'w') f.write(makeApd(xrisi,trimino,db).encode('CP1253')) f.close() if __name__ == '__main__': #print caps('κωνσταντίνος και καλά κρασιά για όλα τα καλά παιδιά ali baba and fourty thieves') #f = open('CSL01.txt','w') #f.write(makeAPD().encode('ISO8859-7')) #f.close() #readAPD() d = makeApd('2013',12,'e:/tmp/mistst.m13')#.encode('ISO8859-7') print d #print d.makeSums(0) #makeAPDfile("csl12")
gpl-3.0
avsm/xen-unstable
tools/python/xen/sv/DomInfo.py
46
9486
from xen.xend.XendClient import server from xen.xend import PrettyPrint from xen.sv.HTMLBase import HTMLBase from xen.sv.util import * from xen.sv.GenTabbed import * from xen.sv.Wizard import * DEBUG=1 class DomInfo( GenTabbed ): def __init__( self, urlWriter ): self.dom = 0; GenTabbed.__init__( self, "Domain Info", urlWriter, [ 'General', 'SXP', 'Devices', 'Migrate', 'Save' ], [ DomGeneralTab, DomSXPTab, DomDeviceTab, DomMigrateTab, DomSaveTab ] ) def write_BODY( self, request ): try: dom = int( getVar( 'dom', request ) ) except: request.write( "<p>Please Select a Domain</p>" ) return None GenTabbed.write_BODY( self, request ) def write_MENU( self, request ): domains = [] try: domains = server.xend_domains() domains.sort() except: pass request.write( "\n<table style='border:0px solid white' cellspacing='0' cellpadding='0' border='0' width='100%'>\n" ) request.write( "<tr class='domainInfoHead'>" ) request.write( "<td class='domainInfoHead' align='center'>Domain</td>\n" ) request.write( "<td class='domainInfoHead' align='center'>Name</td>\n" ) request.write( "<td class='domainInfoHead' align='center'>State</td>\n" ) request.write( "<td class='domainInfoHead' align='center'></td>\n" ) request.write( "</tr>" ) odd = True if not domains is None: for domain in domains: odd = not odd; if odd: request.write( "<tr class='domainInfoOdd'>\n" ) else: request.write( "<tr class='domainInfoEven'>\n" ) domInfo = getDomInfo( domain ) request.write( "<td class='domainInfo' align='center'>%(id)s</td>\n" % domInfo ) url = self.urlWriter( "&dom=%(id)s" % domInfo ) request.write( "<td class='domainInfo' align='center'><a href='%s'>%s</a></td>\n" % ( url, domInfo['name'] ) ) request.write( "<td class='domainInfo' align='center'>%(state)5s</td>\n" % domInfo ) if domInfo[ 'id' ] != "0": request.write( "<td class='domainInfo' align='center'>" ) if domInfo[ 'state' ][ 2 ] == "-": request.write( "<img src='images/small-pause.png' onclick='doOp2( \"pause\", \"%(dom)-4s\" )'>" % domInfo ) else: request.write( "<img src='images/small-unpause.png' onclick='doOp2( \"unpause\", \"%(dom)-4s\" )'>" % domInfo ) request.write( "<img src='images/small-destroy.png' onclick='doOp2( \"destroy\", \"%(dom)-4s\" )'></td>" % domInfo ) else: request.write( "<td>&nbsp;</td>" ) request.write( "</tr>\n" ) else: request.write( "<tr colspan='10'><p class='small'>Error getting domain list<br/>Perhaps XenD not running?</p></tr>") request.write( "</table>" ) class DomGeneralTab( CompositeTab ): def __init__( self, urlWriter ): CompositeTab.__init__( self, [ DomGenTab, DomActionTab ], urlWriter ) class DomGenTab( GeneralTab ): def __init__( self, _ ): titles = {} titles[ 'ID' ] = 'dom' titles[ 'Name' ] = 'name' titles[ 'CPU' ] = 'cpu' titles[ 'Memory' ] = ( 'mem', memoryFormatter ) titles[ 'State' ] = ( 'state', stateFormatter ) titles[ 'Total CPU' ] = ( 'cpu_time', smallTimeFormatter ) titles[ 'Up Time' ] = ( 'up_time', bigTimeFormatter ) GeneralTab.__init__( self, {}, titles ) def write_BODY( self, request ): self.dom = getVar('dom', request) if self.dom is None: request.write( "<p>Please Select a Domain</p>" ) return None self.dict = getDomInfo( self.dom ) GeneralTab.write_BODY( self, request ) class DomSXPTab( PreTab ): def __init__( self, _ ): self.dom = 0 PreTab.__init__( self, "" ) def write_BODY( self, request ): self.dom = getVar('dom', request) if self.dom is None: request.write( "<p>Please Select a Domain</p>" ) return None try: domInfo = server.xend_domain( self.dom ) except: domInfo = [["Error getting domain details."]] self.source = sxp2prettystring( domInfo ) PreTab.write_BODY( self, request ) class DomActionTab( ActionTab ): def __init__( self, _ ): actions = { "shutdown" : "Shutdown", "reboot" : "Reboot", "pause" : "Pause", "unpause" : "Unpause", "destroy" : "Destroy" } ActionTab.__init__( self, actions ) def op_shutdown( self, request ): dom = getVar( 'dom', request ) if not dom is None and dom != '0': if DEBUG: print ">DomShutDown %s" % dom try: server.xend_domain_shutdown( int( dom ), "poweroff" ) except: pass def op_reboot( self, request ): dom = getVar( 'dom', request ) if not dom is None and dom != '0': if DEBUG: print ">DomReboot %s" % dom try: server.xend_domain_shutdown( int( dom ), "reboot" ) except: pass def op_pause( self, request ): dom = getVar( 'dom', request ) if not dom is None and dom != '0': if DEBUG: print ">DomPause %s" % dom try: server.xend_domain_pause( int( dom ) ) except: pass def op_unpause( self, request ): dom = getVar( 'dom', request ) if not dom is None and dom != '0': if DEBUG: print ">DomUnpause %s" % dom try: server.xend_domain_unpause( int( dom ) ) except: pass def op_destroy( self, request ): dom = getVar( 'dom', request ) if not dom is None and dom != '0': if DEBUG: print ">DomDestroy %s" % dom try: server.xend_domain_destroy(int( dom )) except: pass class DomDeviceTab( CompositeTab ): def __init__( self, urlWriter ): CompositeTab.__init__( self, [ DomDeviceListTab, DomDeviceOptionsTab, DomDeviceActionTab ], urlWriter ) class DomDeviceListTab( NullTab ): title = "Device List" def __init__( self, _ ): pass class DomDeviceOptionsTab( NullTab ): title = "Device Options" def __init__( self, _ ): pass class DomDeviceActionTab( ActionTab ): def __init__( self, _ ): ActionTab.__init__( self, { "addvcpu" : "Add VCPU", "addvbd" : "Add VBD", "addvif" : "Add VIF" } ) class DomMigrateTab( CompositeTab ): def __init__( self, urlWriter ): CompositeTab.__init__( self, [ DomMigrateExtraTab, DomMigrateActionTab ], urlWriter ) class DomMigrateExtraTab( Sheet ): def __init__( self, urlWriter ): Sheet.__init__( self, urlWriter, "Configure Migration", 0) self.addControl( TickControl('live', 'True', 'Live migrate:') ) self.addControl( InputControl('rate', '0', 'Rate limit:') ) self.addControl( InputControl( 'dest', 'host.domain', 'Name or IP address:', ".*") ) class DomMigrateActionTab( ActionTab ): def __init__( self, _ ): actions = { "migrate" : "Migrate" } ActionTab.__init__( self, actions ) def op_migrate( self, request ): try: domid = int( getVar( 'dom', request ) ) live = getVar( 'live', request ) rate = getVar( 'rate', request ) dest = getVar( 'dest', request ) dom_sxp = server.xend_domain_migrate( domid, dest, live == 'True', rate ) success = "Your domain was successfully Migrated.\n" except Exception, e: success = "There was an error migrating your domain\n" dom_sxp = str(e) class DomSaveTab( CompositeTab ): def __init__( self, urlWriter ): CompositeTab.__init__( self, [ DomSaveExtraTab, DomSaveActionTab ], urlWriter ) class DomSaveExtraTab( Sheet ): title = "Save location" def __init__( self, urlWriter ): Sheet.__init__( self, urlWriter, "Save Domain to file", 0 ) self.addControl( InputControl( 'file', '', 'Suspend file name:', ".*") ) class DomSaveActionTab( ActionTab ): def __init__( self, _ ): actions = { "save" : "Save" } ActionTab.__init__( self, actions ) def op_save( self, request ): try: dom_sxp = server.xend_domain_save( config['domid'], config['file'] ) success = "Your domain was successfully saved.\n" except Exception, e: success = "There was an error saving your domain\n" dom_sxp = str(e) try: dom = int( getVar( 'dom', request ) ) except: pass
gpl-2.0
jumping/Diamond
src/collectors/drbd/drbd.py
28
2737
# coding=utf-8 """ DRBD metric collector Read and publish metrics from all available resources in /proc/drbd """ import diamond.collector import re class DRBDCollector(diamond.collector.Collector): """ DRBD Simple metric collector """ def get_default_config_help(self): config_help = super(DRBDCollector, self).get_default_config_help() config_help.update({ }) return config_help def get_default_config(self): """ Returns the default collector settings """ config = super(DRBDCollector, self).get_default_config() config.update({ 'path': 'drbd' }) return config def collect(self): """ Overrides the Collector.collect method """ performance_indicators = { 'ns': 'network_send', 'nr': 'network_receive', 'dw': 'disk_write', 'dr': 'disk_read', 'al': 'activity_log', 'bm': 'bit_map', 'lo': 'local_count', 'pe': 'pending', 'ua': 'unacknowledged', 'ap': 'application_pending', 'ep': 'epochs', 'wo': 'write_order', 'oos': 'out_of_sync', 'cs': 'connection_state', 'ro': 'roles', 'ds': 'disk_states' } results = dict() try: statusfile = open('/proc/drbd', 'r') current_resource = '' for line in statusfile: if re.search('version', line) is None: if re.search(r' \d: cs', line): matches = re.match(r' (\d): (cs:\w+) (ro:\w+/\w+) ' '(ds:\w+/\w+) (\w{1}) .*', line) current_resource = matches.group(1) results[current_resource] = dict() elif re.search(r'\sns:', line): metrics = line.strip().split(" ") for metric in metrics: item, value = metric.split(":") results[current_resource][ performance_indicators[item]] = value else: continue statusfile.close() except IOError, errormsg: self.log.error("Can't read DRBD status file: {0}".format(errormsg)) return for resource in results.keys(): for metric_name, metric_value in results[resource].items(): if metric_value.isdigit(): self.publish(resource + "." + metric_name, metric_value) else: continue
mit
iansf/engine
sky/tools/webkitpy/common/system/executive_unittest.py
11
10436
# Copyright (C) 2010 Google Inc. All rights reserved. # Copyright (C) 2009 Daniel Bates (dbates@intudata.com). 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 os import errno import signal import subprocess import sys import time import unittest # Since we execute this script directly as part of the unit tests, we need to ensure # that tools and tools/thirdparty are in sys.path for the next imports to work correctly. script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) if script_dir not in sys.path: sys.path.append(script_dir) third_party_py = os.path.join(script_dir, "webkitpy", "thirdparty") if third_party_py not in sys.path: sys.path.append(third_party_py) from webkitpy.common.system.executive import Executive, ScriptError from webkitpy.common.system.filesystem_mock import MockFileSystem class ScriptErrorTest(unittest.TestCase): def test_message_with_output(self): error = ScriptError('My custom message!', '', -1) self.assertEqual(error.message_with_output(), 'My custom message!') error = ScriptError('My custom message!', '', -1, 'My output.') self.assertEqual(error.message_with_output(), 'My custom message!\n\noutput: My output.') error = ScriptError('', 'my_command!', -1, 'My output.', '/Users/username/blah') self.assertEqual(error.message_with_output(), 'Failed to run "\'my_command!\'" exit_code: -1 cwd: /Users/username/blah\n\noutput: My output.') error = ScriptError('', 'my_command!', -1, 'ab' + '1' * 499) self.assertEqual(error.message_with_output(), 'Failed to run "\'my_command!\'" exit_code: -1\n\noutput: Last 500 characters of output:\nb' + '1' * 499) def test_message_with_tuple(self): error = ScriptError('', ('my', 'command'), -1, 'My output.', '/Users/username/blah') self.assertEqual(error.message_with_output(), 'Failed to run "(\'my\', \'command\')" exit_code: -1 cwd: /Users/username/blah\n\noutput: My output.') def never_ending_command(): """Arguments for a command that will never end (useful for testing process killing). It should be a process that is unlikely to already be running because all instances will be killed.""" if sys.platform == 'win32': return ['wmic'] return ['yes'] def command_line(cmd, *args): return [sys.executable, __file__, '--' + cmd] + list(args) class ExecutiveTest(unittest.TestCase): def assert_interpreter_for_content(self, intepreter, content): fs = MockFileSystem() tempfile, temp_name = fs.open_binary_tempfile('') tempfile.write(content) tempfile.close() file_interpreter = Executive.interpreter_for_script(temp_name, fs) self.assertEqual(file_interpreter, intepreter) def test_interpreter_for_script(self): self.assert_interpreter_for_content(None, '') self.assert_interpreter_for_content(None, 'abcd\nefgh\nijklm') self.assert_interpreter_for_content(None, '##/usr/bin/perl') self.assert_interpreter_for_content('perl', '#!/usr/bin/env perl') self.assert_interpreter_for_content('perl', '#!/usr/bin/env perl\nfirst\nsecond') self.assert_interpreter_for_content('perl', '#!/usr/bin/perl') self.assert_interpreter_for_content('perl', '#!/usr/bin/perl -w') self.assert_interpreter_for_content(sys.executable, '#!/usr/bin/env python') self.assert_interpreter_for_content(sys.executable, '#!/usr/bin/env python\nfirst\nsecond') self.assert_interpreter_for_content(sys.executable, '#!/usr/bin/python') self.assert_interpreter_for_content('ruby', '#!/usr/bin/env ruby') self.assert_interpreter_for_content('ruby', '#!/usr/bin/env ruby\nfirst\nsecond') self.assert_interpreter_for_content('ruby', '#!/usr/bin/ruby') def test_run_command_with_bad_command(self): def run_bad_command(): Executive().run_command(["foo_bar_command_blah"], error_handler=Executive.ignore_error, return_exit_code=True) self.assertRaises(OSError, run_bad_command) def test_run_command_args_type(self): executive = Executive() self.assertRaises(AssertionError, executive.run_command, "echo") self.assertRaises(AssertionError, executive.run_command, u"echo") executive.run_command(command_line('echo', 'foo')) executive.run_command(tuple(command_line('echo', 'foo'))) def test_auto_stringify_args(self): executive = Executive() executive.run_command(command_line('echo', 1)) executive.popen(command_line('echo', 1), stdout=executive.PIPE).wait() self.assertEqual('echo 1', executive.command_for_printing(['echo', 1])) def test_popen_args(self): executive = Executive() # Explicitly naming the 'args' argument should not thow an exception. executive.popen(args=command_line('echo', 1), stdout=executive.PIPE).wait() def test_run_command_with_unicode(self): """Validate that it is safe to pass unicode() objects to Executive.run* methods, and they will return unicode() objects by default unless decode_output=False""" unicode_tor_input = u"WebKit \u2661 Tor Arne Vestb\u00F8!" if sys.platform == 'win32': encoding = 'mbcs' else: encoding = 'utf-8' encoded_tor = unicode_tor_input.encode(encoding) # On Windows, we expect the unicode->mbcs->unicode roundtrip to be # lossy. On other platforms, we expect a lossless roundtrip. if sys.platform == 'win32': unicode_tor_output = encoded_tor.decode(encoding) else: unicode_tor_output = unicode_tor_input executive = Executive() output = executive.run_command(command_line('cat'), input=unicode_tor_input) self.assertEqual(output, unicode_tor_output) output = executive.run_command(command_line('echo', unicode_tor_input)) self.assertEqual(output, unicode_tor_output) output = executive.run_command(command_line('echo', unicode_tor_input), decode_output=False) self.assertEqual(output, encoded_tor) # Make sure that str() input also works. output = executive.run_command(command_line('cat'), input=encoded_tor, decode_output=False) self.assertEqual(output, encoded_tor) # FIXME: We should only have one run* method to test output = executive.run_and_throw_if_fail(command_line('echo', unicode_tor_input), quiet=True) self.assertEqual(output, unicode_tor_output) output = executive.run_and_throw_if_fail(command_line('echo', unicode_tor_input), quiet=True, decode_output=False) self.assertEqual(output, encoded_tor) def test_kill_process(self): executive = Executive() process = subprocess.Popen(never_ending_command(), stdout=subprocess.PIPE) self.assertEqual(process.poll(), None) # Process is running executive.kill_process(process.pid) # Killing again should fail silently. executive.kill_process(process.pid) def _assert_windows_image_name(self, name, expected_windows_name): executive = Executive() windows_name = executive._windows_image_name(name) self.assertEqual(windows_name, expected_windows_name) def test_windows_image_name(self): self._assert_windows_image_name("foo", "foo.exe") self._assert_windows_image_name("foo.exe", "foo.exe") self._assert_windows_image_name("foo.com", "foo.com") # If the name looks like an extension, even if it isn't # supposed to, we have no choice but to return the original name. self._assert_windows_image_name("foo.baz", "foo.baz") self._assert_windows_image_name("foo.baz.exe", "foo.baz.exe") def test_check_running_pid(self): executive = Executive() self.assertTrue(executive.check_running_pid(os.getpid())) # Maximum pid number on Linux is 32768 by default self.assertFalse(executive.check_running_pid(100000)) def test_running_pids(self): if sys.platform in ("win32", "cygwin"): return # This function isn't implemented on Windows yet. executive = Executive() pids = executive.running_pids() self.assertIn(os.getpid(), pids) def test_run_in_parallel_assert_nonempty(self): self.assertRaises(AssertionError, Executive().run_in_parallel, []) def main(platform, stdin, stdout, cmd, args): if platform == 'win32' and hasattr(stdout, 'fileno'): import msvcrt msvcrt.setmode(stdout.fileno(), os.O_BINARY) if cmd == '--cat': stdout.write(stdin.read()) elif cmd == '--echo': stdout.write(' '.join(args)) return 0 if __name__ == '__main__' and len(sys.argv) > 1 and sys.argv[1] in ('--cat', '--echo'): sys.exit(main(sys.platform, sys.stdin, sys.stdout, sys.argv[1], sys.argv[2:]))
bsd-3-clause
keedio/kafka-hue
kafka/setup.py
1
1242
# 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 setuptools import setup, find_packages setup( name = "kafka", version = "4.1.1", author = "KEEDIO", url = 'http://www.keedio.com', description = "Kafka-HUE is a HUE application to admin and manage a pool of Apache Kafka clusters.", packages = find_packages('src'), package_dir = {'': 'src'}, install_requires = ['setuptools', 'desktop'], entry_points = { 'desktop.sdk.application': 'kafka=kafka' }, )
apache-2.0
mbalasso/mynumpy
numpy/distutils/command/install.py
95
3008
import sys if 'setuptools' in sys.modules: import setuptools.command.install as old_install_mod have_setuptools = True else: import distutils.command.install as old_install_mod have_setuptools = False old_install = old_install_mod.install from distutils.file_util import write_file class install(old_install): # Always run install_clib - the command is cheap, so no need to bypass it; # but it's not run by setuptools -- so it's run again in install_data sub_commands = old_install.sub_commands + [ ('install_clib', lambda x: True) ] def finalize_options (self): old_install.finalize_options(self) self.install_lib = self.install_libbase def setuptools_run(self): """ The setuptools version of the .run() method. We must pull in the entire code so we can override the level used in the _getframe() call since we wrap this call by one more level. """ # Explicit request for old-style install? Just do it if self.old_and_unmanageable or self.single_version_externally_managed: return old_install_mod._install.run(self) # Attempt to detect whether we were called from setup() or by another # command. If we were called by setup(), our caller will be the # 'run_command' method in 'distutils.dist', and *its* caller will be # the 'run_commands' method. If we were called any other way, our # immediate caller *might* be 'run_command', but it won't have been # called by 'run_commands'. This is slightly kludgy, but seems to # work. # caller = sys._getframe(3) caller_module = caller.f_globals.get('__name__','') caller_name = caller.f_code.co_name if caller_module != 'distutils.dist' or caller_name!='run_commands': # We weren't called from the command line or setup(), so we # should run in backward-compatibility mode to support bdist_* # commands. old_install_mod._install.run(self) else: self.do_egg_install() def run(self): if not have_setuptools: r = old_install.run(self) else: r = self.setuptools_run() if self.record: # bdist_rpm fails when INSTALLED_FILES contains # paths with spaces. Such paths must be enclosed # with double-quotes. f = open(self.record,'r') lines = [] need_rewrite = False for l in f.readlines(): l = l.rstrip() if ' ' in l: need_rewrite = True l = '"%s"' % (l) lines.append(l) f.close() if need_rewrite: self.execute(write_file, (self.record, lines), "re-writing list of installed files to '%s'" % self.record) return r
bsd-3-clause
chenshuo/recipes
python/netcat.py
1
1626
#!/usr/bin/python import os import select import socket import sys def relay(sock): poll = select.poll() poll.register(sock, select.POLLIN) poll.register(sys.stdin, select.POLLIN) done = False while not done: events = poll.poll(10000) # 10 seconds for fileno, event in events: if event & select.POLLIN: if fileno == sock.fileno(): data = sock.recv(8192) if data: sys.stdout.write(data) else: done = True else: assert fileno == sys.stdin.fileno() data = os.read(fileno, 8192) if data: sock.sendall(data) else: sock.shutdown(socket.SHUT_WR) poll.unregister(sys.stdin) def main(argv): if len(argv) < 3: binary = argv[0] print "Usage:\n %s -l port\n %s host port" % (argv[0], argv[0]) return port = int(argv[2]) if argv[1] == "-l": # server server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', port)) server_socket.listen(5) (client_socket, client_address) = server_socket.accept() server_socket.close() relay(client_socket) else: # client sock = socket.create_connection((argv[1], port)) relay(sock) if __name__ == "__main__": main(sys.argv)
bsd-3-clause
orekyuu/intellij-community
python/helpers/pydev/interpreterInfo.py
45
7734
''' This module was created to get information available in the interpreter, such as libraries, paths, etc. what is what: sys.builtin_module_names: contains the builtin modules embeeded in python (rigth now, we specify all manually). sys.prefix: A string giving the site-specific directory prefix where the platform independent Python files are installed format is something as EXECUTABLE:python.exe|libs@compiled_dlls$builtin_mods all internal are separated by | ''' import sys try: import os.path def fullyNormalizePath(path): '''fixes the path so that the format of the path really reflects the directories in the system ''' return os.path.normpath(path) join = os.path.join except: # ImportError or AttributeError. # See: http://stackoverflow.com/questions/10254353/error-while-installing-jython-for-pydev def fullyNormalizePath(path): '''fixes the path so that the format of the path really reflects the directories in the system ''' return path def join(a, b): if a.endswith('/') or a.endswith('\\'): return a + b return a + '/' + b IS_PYTHON_3K = 0 try: if sys.version_info[0] == 3: IS_PYTHON_3K = 1 except: # That's OK, not all versions of python have sys.version_info pass try: # Just check if False and True are defined (depends on version, not whether it's jython/python) False True except: exec ('True, False = 1,0') # An exec is used so that python 3k does not give a syntax error if sys.platform == "cygwin": try: import ctypes # use from the system if available except ImportError: sys.path.append(join(sys.path[0], 'third_party/wrapped_for_pydev')) import ctypes def nativePath(path): MAX_PATH = 512 # On cygwin NT, its 260 lately, but just need BIG ENOUGH buffer '''Get the native form of the path, like c:\\Foo for /cygdrive/c/Foo''' retval = ctypes.create_string_buffer(MAX_PATH) path = fullyNormalizePath(path) CCP_POSIX_TO_WIN_A = 0 ctypes.cdll.cygwin1.cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, retval, MAX_PATH) return retval.value else: def nativePath(path): return fullyNormalizePath(path) def __getfilesystemencoding(): ''' Note: there's a copy of this method in _pydev_filesystem_encoding.py ''' try: ret = sys.getfilesystemencoding() if not ret: raise RuntimeError('Unable to get encoding.') return ret except: try: # Handle Jython from java.lang import System env = System.getProperty("os.name").lower() if env.find('win') != -1: return 'ISO-8859-1' # mbcs does not work on Jython, so, use a (hopefully) suitable replacement return 'utf-8' except: pass # Only available from 2.3 onwards. if sys.platform == 'win32': return 'mbcs' return 'utf-8' def getfilesystemencoding(): try: ret = __getfilesystemencoding() #Check if the encoding is actually there to be used! if hasattr('', 'encode'): ''.encode(ret) if hasattr('', 'decode'): ''.decode(ret) return ret except: return 'utf-8' file_system_encoding = getfilesystemencoding() def tounicode(s): if hasattr(s, 'decode'): # Depending on the platform variant we may have decode on string or not. return s.decode(file_system_encoding) return s def toutf8(s): if hasattr(s, 'encode'): return s.encode('utf-8') return s def toasciimxl(s): # output for xml without a declared encoding # As the output is xml, we have to encode chars (< and > are ok as they're not accepted in the filesystem name -- # if it was allowed, we'd have to do things more selectively so that < and > don't get wrongly replaced). s = s.replace("&", "&amp;") try: ret = s.encode('ascii', 'xmlcharrefreplace') except: # use workaround ret = '' for c in s: try: ret += c.encode('ascii') except: try: # Python 2: unicode is a valid identifier ret += unicode("&#%d;") % ord(c) except: # Python 3: a string is already unicode, so, just doing it directly should work. ret += "&#%d;" % ord(c) return ret if __name__ == '__main__': try: # just give some time to get the reading threads attached (just in case) import time time.sleep(0.1) except: pass try: executable = nativePath(sys.executable) except: executable = sys.executable if sys.platform == "cygwin" and not executable.endswith('.exe'): executable += '.exe' try: major = str(sys.version_info[0]) minor = str(sys.version_info[1]) except AttributeError: # older versions of python don't have version_info import string s = string.split(sys.version, ' ')[0] s = string.split(s, '.') major = s[0] minor = s[1] s = tounicode('%s.%s') % (tounicode(major), tounicode(minor)) contents = [tounicode('<xml>')] contents.append(tounicode('<version>%s</version>') % (tounicode(s),)) contents.append(tounicode('<executable>%s</executable>') % tounicode(executable)) # this is the new implementation to get the system folders # (still need to check if it works in linux) # (previously, we were getting the executable dir, but that is not always correct...) prefix = tounicode(nativePath(sys.prefix)) # print_ 'prefix is', prefix result = [] path_used = sys.path try: path_used = path_used[1:] # Use a copy (and don't include the directory of this script as a path.) except: pass # just ignore it... for p in path_used: p = tounicode(nativePath(p)) try: import string # to be compatible with older versions if string.find(p, prefix) == 0: # was startswith result.append((p, True)) else: result.append((p, False)) except (ImportError, AttributeError): # python 3k also does not have it # jython may not have it (depending on how are things configured) if p.startswith(prefix): # was startswith result.append((p, True)) else: result.append((p, False)) for p, b in result: if b: contents.append(tounicode('<lib path="ins">%s</lib>') % (p,)) else: contents.append(tounicode('<lib path="out">%s</lib>') % (p,)) # no compiled libs # nor forced libs for builtinMod in sys.builtin_module_names: contents.append(tounicode('<forced_lib>%s</forced_lib>') % tounicode(builtinMod)) contents.append(tounicode('</xml>')) unic = tounicode('\n').join(contents) inasciixml = toasciimxl(unic) if IS_PYTHON_3K: # This is the 'official' way of writing binary output in Py3K (see: http://bugs.python.org/issue4571) sys.stdout.buffer.write(inasciixml) else: sys.stdout.write(inasciixml) try: sys.stdout.flush() sys.stderr.flush() # and give some time to let it read things (just in case) import time time.sleep(0.1) except: pass raise RuntimeError('Ok, this is so that it shows the output (ugly hack for some platforms, so that it releases the output).')
apache-2.0
SiccarPoint/numpy
numpy/linalg/tests/test_regression.py
18
5286
""" Test functions for linalg module """ from __future__ import division, absolute_import, print_function import numpy as np from numpy import linalg, arange, float64, array, dot, transpose from numpy.testing import ( TestCase, run_module_suite, assert_equal, assert_array_equal, assert_array_almost_equal, assert_array_less ) rlevel = 1 class TestRegression(TestCase): def test_eig_build(self, level=rlevel): # Ticket #652 rva = array([1.03221168e+02 + 0.j, -1.91843603e+01 + 0.j, -6.04004526e-01 + 15.84422474j, -6.04004526e-01 - 15.84422474j, -1.13692929e+01 + 0.j, -6.57612485e-01 + 10.41755503j, -6.57612485e-01 - 10.41755503j, 1.82126812e+01 + 0.j, 1.06011014e+01 + 0.j, 7.80732773e+00 + 0.j, -7.65390898e-01 + 0.j, 1.51971555e-15 + 0.j, -1.51308713e-15 + 0.j]) a = arange(13 * 13, dtype=float64) a.shape = (13, 13) a = a % 17 va, ve = linalg.eig(a) va.sort() rva.sort() assert_array_almost_equal(va, rva) def test_eigh_build(self, level=rlevel): # Ticket 662. rvals = [68.60568999, 89.57756725, 106.67185574] cov = array([[77.70273908, 3.51489954, 15.64602427], [3.51489954, 88.97013878, -1.07431931], [15.64602427, -1.07431931, 98.18223512]]) vals, vecs = linalg.eigh(cov) assert_array_almost_equal(vals, rvals) def test_svd_build(self, level=rlevel): # Ticket 627. a = array([[0., 1.], [1., 1.], [2., 1.], [3., 1.]]) m, n = a.shape u, s, vh = linalg.svd(a) b = dot(transpose(u[:, n:]), a) assert_array_almost_equal(b, np.zeros((2, 2))) def test_norm_vector_badarg(self): # Regression for #786: Froebenius norm for vectors raises # TypeError. self.assertRaises(ValueError, linalg.norm, array([1., 2., 3.]), 'fro') def test_lapack_endian(self): # For bug #1482 a = array([[5.7998084, -2.1825367], [-2.1825367, 9.85910595]], dtype='>f8') b = array(a, dtype='<f8') ap = linalg.cholesky(a) bp = linalg.cholesky(b) assert_array_equal(ap, bp) def test_large_svd_32bit(self): # See gh-4442, 64bit would require very large/slow matrices. x = np.eye(1000, 66) np.linalg.svd(x) def test_svd_no_uv(self): # gh-4733 for shape in (3, 4), (4, 4), (4, 3): for t in float, complex: a = np.ones(shape, dtype=t) w = linalg.svd(a, compute_uv=False) c = np.count_nonzero(np.absolute(w) > 0.5) assert_equal(c, 1) assert_equal(np.linalg.matrix_rank(a), 1) assert_array_less(1, np.linalg.norm(a, ord=2)) def test_norm_object_array(self): # gh-7575 testvector = np.array([np.array([0, 1]), 0, 0], dtype=object) norm = linalg.norm(testvector) assert_array_equal(norm, [0, 1]) self.assertEqual(norm.dtype, np.dtype('float64')) norm = linalg.norm(testvector, ord=1) assert_array_equal(norm, [0, 1]) self.assertNotEqual(norm.dtype, np.dtype('float64')) norm = linalg.norm(testvector, ord=2) assert_array_equal(norm, [0, 1]) self.assertEqual(norm.dtype, np.dtype('float64')) self.assertRaises(ValueError, linalg.norm, testvector, ord='fro') self.assertRaises(ValueError, linalg.norm, testvector, ord='nuc') self.assertRaises(ValueError, linalg.norm, testvector, ord=np.inf) self.assertRaises(ValueError, linalg.norm, testvector, ord=-np.inf) self.assertRaises((AttributeError, DeprecationWarning), linalg.norm, testvector, ord=0) self.assertRaises(ValueError, linalg.norm, testvector, ord=-1) self.assertRaises(ValueError, linalg.norm, testvector, ord=-2) testmatrix = np.array([[np.array([0, 1]), 0, 0], [0, 0, 0]], dtype=object) norm = linalg.norm(testmatrix) assert_array_equal(norm, [0, 1]) self.assertEqual(norm.dtype, np.dtype('float64')) norm = linalg.norm(testmatrix, ord='fro') assert_array_equal(norm, [0, 1]) self.assertEqual(norm.dtype, np.dtype('float64')) self.assertRaises(TypeError, linalg.norm, testmatrix, ord='nuc') self.assertRaises(ValueError, linalg.norm, testmatrix, ord=np.inf) self.assertRaises(ValueError, linalg.norm, testmatrix, ord=-np.inf) self.assertRaises(ValueError, linalg.norm, testmatrix, ord=0) self.assertRaises(ValueError, linalg.norm, testmatrix, ord=1) self.assertRaises(ValueError, linalg.norm, testmatrix, ord=-1) self.assertRaises(TypeError, linalg.norm, testmatrix, ord=2) self.assertRaises(TypeError, linalg.norm, testmatrix, ord=-2) self.assertRaises(ValueError, linalg.norm, testmatrix, ord=3) if __name__ == '__main__': run_module_suite()
bsd-3-clause
anthgur/servo
tests/wpt/web-platform-tests/beacon/resources/beacon.py
34
5636
import json def build_stash_key(session_id, test_num): return "%s_%s" % (session_id, test_num) def main(request, response): """Helper handler for Beacon tests. It handles two forms of requests: STORE: A URL with a query string of the form 'cmd=store&sid=<token>&tidx=<test_index>&tid=<test_name>'. Stores the receipt of a sendBeacon() request along with its validation result, returning HTTP 200 OK. Parameters: tidx - the integer index of the test. tid - a friendly identifier or name for the test, used when returning results. STAT: A URL with a query string of the form 'cmd=stat&sid=<token>&tidx_min=<min_test_index>&tidx_max=<max_test_index>'. Retrieves the results of test with indices [min_test_index, max_test_index] and returns them as a JSON array and HTTP 200 OK status code. Due to the eventual read-once nature of the stash, results for a given test are only guaranteed to be returned once, though they may be returned multiple times. Parameters: tidx_min - the lower-bounding integer test index. tidx_max - the upper-bounding integer test index. Example response body: [{"id": "Test1", error: null}, {"id": "Test2", error: "some validation details"}] Common parameters: cmd - the command, 'store' or 'stat'. sid - session id used to provide isolation to a test run comprising multiple sendBeacon() tests. """ session_id = request.GET.first("sid"); command = request.GET.first("cmd").lower(); # Workaround to circumvent the limitation that cache keys # can only be UUID's. def wrap_key(key, path): return (str(path), str(key)) request.server.stash._wrap_key = wrap_key # Append CORS headers if needed. if "origin" in request.GET: response.headers.set("Access-Control-Allow-Origin", request.GET.first("origin")) if "credentials" in request.GET: response.headers.set("Access-Control-Allow-Credentials", request.GET.first("credentials")) # Handle the 'store' and 'stat' commands. if command == "store": # The test id is just used to make the results more human-readable. test_id = request.GET.first("tid") # The test index is used to build a predictable stash key, together # with the unique session id, in order to retrieve a range of results # later knowing the index range. test_idx = request.GET.first("tidx") test_data = { "id": test_id, "error": None } # Only store the actual POST requests, not any preflight/OPTIONS requests we may get. if request.method == "POST": test_data_key = build_stash_key(session_id, test_idx) payload = "" if "Content-Type" in request.headers and \ "form-data" in request.headers["Content-Type"]: if "payload" in request.POST: # The payload was sent as a FormData. payload = request.POST.first("payload") else: # A FormData was sent with an empty payload. pass else: # The payload was sent as either a string, Blob, or BufferSource. payload = request.body payload_parts = filter(None, payload.split(":")) if len(payload_parts) > 0: payload_size = int(payload_parts[0]) # Confirm the payload size sent matches with the number of characters sent. if payload_size != len(payload_parts[1]): test_data["error"] = "expected %d characters but got %d" % (payload_size, len(payload_parts[1])) else: # Confirm the payload contains the correct characters. for i in range(0, payload_size): if payload_parts[1][i] != "*": test_data["error"] = "expected '*' at index %d but got '%s''" % (i, payload_parts[1][i]) break # Store the result in the stash so that it can be retrieved # later with a 'stat' command. request.server.stash.put(test_data_key, test_data) elif request.method == "OPTIONS": # If we expect a preflight, then add the cors headers we expect, otherwise log an error as we shouldn't # send a preflight for all requests. if "preflightExpected" in request.GET: response.headers.set("Access-Control-Allow-Headers", "content-type") response.headers.set("Access-Control-Allow-Methods", "POST") else: test_data_key = build_stash_key(session_id, test_idx) test_data["error"] = "Preflight not expected." request.server.stash.put(test_data_key, test_data) elif command == "stat": test_idx_min = int(request.GET.first("tidx_min")) test_idx_max = int(request.GET.first("tidx_max")) # For each result that has come in, append it to the response. results = [] for test_idx in range(test_idx_min, test_idx_max+1): # +1 because end is exclusive test_data_key = build_stash_key(session_id, test_idx) test_data = request.server.stash.take(test_data_key) if test_data: results.append(test_data) response.headers.set("Content-Type", "text/plain") response.content = json.dumps(results) else: response.status = 400 # BadRequest
mpl-2.0
alanschiemenz/specfem_FWI_workflow
models/create_xyz_starting.py
1
1804
from numpy import zeros import numpy as np # create file d = open("tomography_model_starting.xyz", "w") # origin points ORIG_X=0. ORIG_Y=0. ORIG_Z=0. # end points END_X=1000. END_Y=1000. END_Z=-1000. # depth in negative z-direction # mid point of domain, used to define perturbation xmid=0.5*(END_X-ORIG_X) ymid=0.5*(END_Y-ORIG_Y) zmid=0.5*(END_Z-ORIG_Z) d.write(str(ORIG_X) + " " + str(ORIG_Y) + " " + str(ORIG_Z) + " " + str(END_X) + " " + str(END_Y) + " " + str(END_Z) + "\n") dx = 25. dy = 25. dz = -25. d.write(str(dx) + " " + str(dy) + " " + str(dz) + "\n") # number of interfaces NX=int((END_X-ORIG_X)/dx)+1 NY=int((END_Y-ORIG_Y)/dy)+1 NZ=int((END_Z-ORIG_Y)/dz)+1 d.write(str(NX) + " " + str(NY) + " " + str(NZ) + "\n") VP_MIN = 1000.0 VP_MAX = 4000.0 # constant-density, acoustic VS_MIN = 0.0 VS_MAX = 0.0 RHO_MIN= 2000.0 RHO_MAX= 2000.0 d.write(str(VP_MIN) + " " + str(VP_MAX) + " " + str(VS_MIN) + " " + str(VS_MAX) + " " + str(RHO_MIN) + " " + str(RHO_MAX) + "\n") for i in range(NZ): for j in range(NY): for k in range(NX): x = ORIG_X+k*dx y = ORIG_Y+j*dy z = ORIG_Z+i*dz if ((-200 > z > -400)): vp = 1480.0 -0.2*z - 0.0 * np.exp(-2.0e-5*((x-xmid)**2+(y-ymid)**2)) else: vp = 1480.0-0.2*z # for vs, rho approximations we could Muyzert (2007), Geophysics, eqs 3 and 4 #vs = 0.0 #0.8621*vp - 1172.4 #rho = 310*(vp**0.25) # constant-density, acoustic vs = 0.0 rho = 2000.0 d.write(str(x) + " " + str(y) + " " + str(z) + " " + str(vp) + " " + str(vs) + " " + str(rho) + "\n") d.close()
gpl-3.0
mKeRix/home-assistant
homeassistant/components/guardian/util.py
3
1446
"""Define Guardian-specific utilities.""" import asyncio from datetime import timedelta from typing import Awaitable, Callable from aioguardian import Client from aioguardian.errors import GuardianError from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import LOGGER DEFAULT_UPDATE_INTERVAL = timedelta(seconds=30) class GuardianDataUpdateCoordinator(DataUpdateCoordinator): """Define an extended DataUpdateCoordinator with some Guardian goodies.""" def __init__( self, hass: HomeAssistant, *, client: Client, api_name: str, api_coro: Callable[..., Awaitable], api_lock: asyncio.Lock, valve_controller_uid: str, ): """Initialize.""" super().__init__( hass, LOGGER, name=f"{valve_controller_uid}_{api_name}", update_interval=DEFAULT_UPDATE_INTERVAL, ) self._api_coro = api_coro self._api_lock = api_lock self._client = client async def _async_update_data(self) -> dict: """Execute a "locked" API request against the valve controller.""" async with self._api_lock, self._client: try: resp = await self._api_coro() except GuardianError as err: raise UpdateFailed(err) return resp["data"]
mit
dwightgunning/django
django/contrib/admin/bin/compress.py
266
2282
#!/usr/bin/env python import argparse import os import subprocess import sys try: import closure except ImportError: closure_compiler = None else: closure_compiler = os.path.join(os.path.dirname(closure.__file__), 'closure.jar') js_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'admin', 'js') def main(): description = """With no file paths given this script will automatically compress all jQuery-based files of the admin app. Requires the Google Closure Compiler library and Java version 6 or later.""" parser = argparse.ArgumentParser(description=description) parser.add_argument('file', nargs='*') parser.add_argument("-c", dest="compiler", default="~/bin/compiler.jar", help="path to Closure Compiler jar file") parser.add_argument("-v", "--verbose", action="store_true", dest="verbose") parser.add_argument("-q", "--quiet", action="store_false", dest="verbose") options = parser.parse_args() compiler = closure_compiler if closure_compiler else os.path.expanduser(options.compiler) if not os.path.exists(compiler): sys.exit( "Google Closure compiler jar file %s not found. Please use the -c " "option to specify the path." % compiler ) if not options.file: if options.verbose: sys.stdout.write("No filenames given; defaulting to admin scripts\n") files = [os.path.join(js_path, f) for f in [ "actions.js", "collapse.js", "inlines.js", "prepopulate.js"]] else: files = options.file for file_name in files: if not file_name.endswith(".js"): file_name = file_name + ".js" to_compress = os.path.expanduser(file_name) if os.path.exists(to_compress): to_compress_min = "%s.min.js" % "".join(file_name.rsplit(".js")) cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min) if options.verbose: sys.stdout.write("Running: %s\n" % cmd) subprocess.call(cmd.split()) else: sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress) if __name__ == '__main__': main()
bsd-3-clause
herove/dotfiles
sublime/Packages/ConvertToUTF8/chardet/charsetprober.py
3127
1902
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from . import constants import re class CharSetProber: def __init__(self): pass def reset(self): self._mState = constants.eDetecting def get_charset_name(self): return None def feed(self, aBuf): pass def get_state(self): return self._mState def get_confidence(self): return 0.0 def filter_high_bit_only(self, aBuf): aBuf = re.sub(b'([\x00-\x7F])+', b' ', aBuf) return aBuf def filter_without_english_letters(self, aBuf): aBuf = re.sub(b'([A-Za-z])+', b' ', aBuf) return aBuf def filter_with_english_letters(self, aBuf): # TODO return aBuf
mit
yast/yast-python-bindings
examples/InputField-layout.py
1
1271
# encoding: utf-8 # Input field width under different layout constraints from yast import import_module import_module('UI') from yast import * class InputFieldLayoutClient: def main(self): UI.OpenDialog( VBox( InputField("Normal", "normal width"), InputField(Opt("shrinkable"), "Sml", "shrinkable"), VBox( MarginBox( 1, 0.2, Frame( "Useless Frame", VBox( Heading("Very Wide and Very Useless Heading"), InputField("Normal 1"), InputField("Normal 2"), InputField("Normal 3"), InputField("Unusually &wide field caption to make it wider"), InputField("Normal 4"), InputField(Opt("hstretch"), "Stretch", "stretchable"), InputField(Opt("shrinkable"), "Sml", "shrinkable"), Left(InputField("Left", "left aligned")), HSquash(InputField("HSquashed", "hquashed")) ) ) ) ), PushButton(Opt("default"), "&OK") ) ) UI.UserInput() UI.CloseDialog() InputFieldLayoutClient().main()
gpl-2.0
naritta/numpy
numpy/core/arrayprint.py
9
26098
"""Array printing function $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ """ from __future__ import division, absolute_import, print_function __all__ = ["array2string", "set_printoptions", "get_printoptions"] __docformat__ = 'restructuredtext' # # Written by Konrad Hinsen <hinsenk@ere.umontreal.ca> # last revision: 1996-3-13 # modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details) # and by Perry Greenfield 2000-4-1 for numarray # and by Travis Oliphant 2005-8-22 for numpy import sys from functools import reduce from . import numerictypes as _nt from .umath import maximum, minimum, absolute, not_equal, isnan, isinf from .multiarray import format_longfloat, datetime_as_string, datetime_data from .fromnumeric import ravel from .numeric import asarray if sys.version_info[0] >= 3: _MAXINT = sys.maxsize _MININT = -sys.maxsize - 1 else: _MAXINT = sys.maxint _MININT = -sys.maxint - 1 def product(x, y): return x*y _summaryEdgeItems = 3 # repr N leading and trailing items of each dimension _summaryThreshold = 1000 # total items > triggers array summarization _float_output_precision = 8 _float_output_suppress_small = False _line_width = 75 _nan_str = 'nan' _inf_str = 'inf' _formatter = None # formatting function for array elements def set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None): """ Set printing options. These options determine the way floating point numbers, arrays and other NumPy objects are displayed. Parameters ---------- precision : int, optional Number of digits of precision for floating point output (default 8). threshold : int, optional Total number of array elements which trigger summarization rather than full repr (default 1000). edgeitems : int, optional Number of array items in summary at beginning and end of each dimension (default 3). linewidth : int, optional The number of characters per line for the purpose of inserting line breaks (default 75). suppress : bool, optional Whether or not suppress printing of small floating point values using scientific notation (default False). nanstr : str, optional String representation of floating point not-a-number (default nan). infstr : str, optional String representation of floating point infinity (default inf). formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'numpy_str' : types `numpy.string_` and `numpy.unicode_` - 'str' : all other strings Other keys that can be used to set a group of types at once are:: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'str' and 'numpystr' See Also -------- get_printoptions, set_string_function, array2string Notes ----- `formatter` is always reset with a call to `set_printoptions`. Examples -------- Floating point precision can be set: >>> np.set_printoptions(precision=4) >>> print np.array([1.123456789]) [ 1.1235] Long arrays can be summarised: >>> np.set_printoptions(threshold=5) >>> print np.arange(10) [0 1 2 ..., 7 8 9] Small results can be suppressed: >>> eps = np.finfo(float).eps >>> x = np.arange(4.) >>> x**2 - (x + eps)**2 array([ -4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00]) >>> np.set_printoptions(suppress=True) >>> x**2 - (x + eps)**2 array([-0., -0., 0., 0.]) A custom formatter can be used to display array elements as desired: >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)}) >>> x = np.arange(3) >>> x array([int: 0, int: -1, int: -2]) >>> np.set_printoptions() # formatter gets reset >>> x array([0, 1, 2]) To put back the default options, you can use: >>> np.set_printoptions(edgeitems=3,infstr='inf', ... linewidth=75, nanstr='nan', precision=8, ... suppress=False, threshold=1000, formatter=None) """ global _summaryThreshold, _summaryEdgeItems, _float_output_precision, \ _line_width, _float_output_suppress_small, _nan_str, _inf_str, \ _formatter if linewidth is not None: _line_width = linewidth if threshold is not None: _summaryThreshold = threshold if edgeitems is not None: _summaryEdgeItems = edgeitems if precision is not None: _float_output_precision = precision if suppress is not None: _float_output_suppress_small = not not suppress if nanstr is not None: _nan_str = nanstr if infstr is not None: _inf_str = infstr _formatter = formatter def get_printoptions(): """ Return the current print options. Returns ------- print_opts : dict Dictionary of current print options with keys - precision : int - threshold : int - edgeitems : int - linewidth : int - suppress : bool - nanstr : str - infstr : str - formatter : dict of callables For a full description of these options, see `set_printoptions`. See Also -------- set_printoptions, set_string_function """ d = dict(precision=_float_output_precision, threshold=_summaryThreshold, edgeitems=_summaryEdgeItems, linewidth=_line_width, suppress=_float_output_suppress_small, nanstr=_nan_str, infstr=_inf_str, formatter=_formatter) return d def _leading_trailing(a): from . import numeric as _nc if a.ndim == 1: if len(a) > 2*_summaryEdgeItems: b = _nc.concatenate((a[:_summaryEdgeItems], a[-_summaryEdgeItems:])) else: b = a else: if len(a) > 2*_summaryEdgeItems: l = [_leading_trailing(a[i]) for i in range( min(len(a), _summaryEdgeItems))] l.extend([_leading_trailing(a[-i]) for i in range( min(len(a), _summaryEdgeItems), 0, -1)]) else: l = [_leading_trailing(a[i]) for i in range(0, len(a))] b = _nc.concatenate(tuple(l)) return b def _boolFormatter(x): if x: return ' True' else: return 'False' def repr_format(x): return repr(x) def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix="", formatter=None): if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if formatter is None: formatter = _formatter if a.size > _summaryThreshold: summary_insert = "..., " data = _leading_trailing(a) else: summary_insert = "" data = ravel(asarray(a)) formatdict = {'bool' : _boolFormatter, 'int' : IntegerFormat(data), 'float' : FloatFormat(data, precision, suppress_small), 'longfloat' : LongFloatFormat(precision), 'complexfloat' : ComplexFormat(data, precision, suppress_small), 'longcomplexfloat' : LongComplexFormat(precision), 'datetime' : DatetimeFormat(data), 'timedelta' : TimedeltaFormat(data), 'numpystr' : repr_format, 'str' : str} if formatter is not None: fkeys = [k for k in formatter.keys() if formatter[k] is not None] if 'all' in fkeys: for key in formatdict.keys(): formatdict[key] = formatter['all'] if 'int_kind' in fkeys: for key in ['int']: formatdict[key] = formatter['int_kind'] if 'float_kind' in fkeys: for key in ['float', 'longfloat']: formatdict[key] = formatter['float_kind'] if 'complex_kind' in fkeys: for key in ['complexfloat', 'longcomplexfloat']: formatdict[key] = formatter['complex_kind'] if 'str_kind' in fkeys: for key in ['numpystr', 'str']: formatdict[key] = formatter['str_kind'] for key in formatdict.keys(): if key in fkeys: formatdict[key] = formatter[key] try: format_function = a._format msg = "The `_format` attribute is deprecated in Numpy 2.0 and " \ "will be removed in 2.1. Use the `formatter` kw instead." import warnings warnings.warn(msg, DeprecationWarning) except AttributeError: # find the right formatting function for the array dtypeobj = a.dtype.type if issubclass(dtypeobj, _nt.bool_): format_function = formatdict['bool'] elif issubclass(dtypeobj, _nt.integer): if issubclass(dtypeobj, _nt.timedelta64): format_function = formatdict['timedelta'] else: format_function = formatdict['int'] elif issubclass(dtypeobj, _nt.floating): if issubclass(dtypeobj, _nt.longfloat): format_function = formatdict['longfloat'] else: format_function = formatdict['float'] elif issubclass(dtypeobj, _nt.complexfloating): if issubclass(dtypeobj, _nt.clongfloat): format_function = formatdict['longcomplexfloat'] else: format_function = formatdict['complexfloat'] elif issubclass(dtypeobj, (_nt.unicode_, _nt.string_)): format_function = formatdict['numpystr'] elif issubclass(dtypeobj, _nt.datetime64): format_function = formatdict['datetime'] else: format_function = formatdict['numpystr'] # skip over "[" next_line_prefix = " " # skip over array( next_line_prefix += " "*len(prefix) lst = _formatArray(a, format_function, len(a.shape), max_line_width, next_line_prefix, separator, _summaryEdgeItems, summary_insert)[:-1] return lst def _convert_arrays(obj): from . import numeric as _nc newtup = [] for k in obj: if isinstance(k, _nc.ndarray): k = k.tolist() elif isinstance(k, tuple): k = _convert_arrays(k) newtup.append(k) return tuple(newtup) def array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix="", style=repr, formatter=None): """ Return a string representation of an array. Parameters ---------- a : ndarray Input array. max_line_width : int, optional The maximum number of columns the string should span. Newline characters splits the string appropriately after array elements. precision : int, optional Floating point precision. Default is the current printing precision (usually 8), which can be altered using `set_printoptions`. suppress_small : bool, optional Represent very small numbers as zero. A number is "very small" if it is smaller than the current printing precision. separator : str, optional Inserted between elements. prefix : str, optional An array is typically printed as:: 'prefix(' + array2string(a) + ')' The length of the prefix string is used to align the output correctly. style : function, optional A function that accepts an ndarray and returns a string. Used only when the shape of `a` is equal to ``()``, i.e. for 0-D arrays. formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'numpy_str' : types `numpy.string_` and `numpy.unicode_` - 'str' : all other strings Other keys that can be used to set a group of types at once are:: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'str' and 'numpystr' Returns ------- array_str : str String representation of the array. Raises ------ TypeError if a callable in `formatter` does not return a string. See Also -------- array_str, array_repr, set_printoptions, get_printoptions Notes ----- If a formatter is specified for a certain type, the `precision` keyword is ignored for that type. This is a very flexible function; `array_repr` and `array_str` are using `array2string` internally so keywords with the same name should work identically in all three functions. Examples -------- >>> x = np.array([1e-16,1,2,3]) >>> print np.array2string(x, precision=2, separator=',', ... suppress_small=True) [ 0., 1., 2., 3.] >>> x = np.arange(3.) >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) '[0.00 1.00 2.00]' >>> x = np.arange(3) >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) '[0x0L 0x1L 0x2L]' """ if a.shape == (): x = a.item() try: lst = a._format(x) msg = "The `_format` attribute is deprecated in Numpy " \ "2.0 and will be removed in 2.1. Use the " \ "`formatter` kw instead." import warnings warnings.warn(msg, DeprecationWarning) except AttributeError: if isinstance(x, tuple): x = _convert_arrays(x) lst = style(x) elif reduce(product, a.shape) == 0: # treat as a null array if any of shape elements == 0 lst = "[]" else: lst = _array2string(a, max_line_width, precision, suppress_small, separator, prefix, formatter=formatter) return lst def _extendLine(s, line, word, max_line_len, next_line_prefix): if len(line.rstrip()) + len(word.rstrip()) >= max_line_len: s += line.rstrip() + "\n" line = next_line_prefix line += word return s, line def _formatArray(a, format_function, rank, max_line_len, next_line_prefix, separator, edge_items, summary_insert): """formatArray is designed for two modes of operation: 1. Full output 2. Summarized output """ if rank == 0: obj = a.item() if isinstance(obj, tuple): obj = _convert_arrays(obj) return str(obj) if summary_insert and 2*edge_items < len(a): leading_items, trailing_items, summary_insert1 = \ edge_items, edge_items, summary_insert else: leading_items, trailing_items, summary_insert1 = 0, len(a), "" if rank == 1: s = "" line = next_line_prefix for i in range(leading_items): word = format_function(a[i]) + separator s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) if summary_insert1: s, line = _extendLine(s, line, summary_insert1, max_line_len, next_line_prefix) for i in range(trailing_items, 1, -1): word = format_function(a[-i]) + separator s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) word = format_function(a[-1]) s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) s += line + "]\n" s = '[' + s[len(next_line_prefix):] else: s = '[' sep = separator.rstrip() for i in range(leading_items): if i > 0: s += next_line_prefix s += _formatArray(a[i], format_function, rank-1, max_line_len, " " + next_line_prefix, separator, edge_items, summary_insert) s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1) if summary_insert1: s += next_line_prefix + summary_insert1 + "\n" for i in range(trailing_items, 1, -1): if leading_items or i != trailing_items: s += next_line_prefix s += _formatArray(a[-i], format_function, rank-1, max_line_len, " " + next_line_prefix, separator, edge_items, summary_insert) s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1) if leading_items or trailing_items > 1: s += next_line_prefix s += _formatArray(a[-1], format_function, rank-1, max_line_len, " " + next_line_prefix, separator, edge_items, summary_insert).rstrip()+']\n' return s class FloatFormat(object): def __init__(self, data, precision, suppress_small, sign=False): self.precision = precision self.suppress_small = suppress_small self.sign = sign self.exp_format = False self.large_exponent = False self.max_str_len = 0 try: self.fillFormat(data) except (TypeError, NotImplementedError): # if reduce(data) fails, this instance will not be called, just # instantiated in formatdict. pass def fillFormat(self, data): from . import numeric as _nc with _nc.errstate(all='ignore'): special = isnan(data) | isinf(data) valid = not_equal(data, 0) & ~special non_zero = absolute(data.compress(valid)) if len(non_zero) == 0: max_val = 0. min_val = 0. else: max_val = maximum.reduce(non_zero) min_val = minimum.reduce(non_zero) if max_val >= 1.e8: self.exp_format = True if not self.suppress_small and (min_val < 0.0001 or max_val/min_val > 1000.): self.exp_format = True if self.exp_format: self.large_exponent = 0 < min_val < 1e-99 or max_val >= 1e100 self.max_str_len = 8 + self.precision if self.large_exponent: self.max_str_len += 1 if self.sign: format = '%+' else: format = '%' format = format + '%d.%de' % (self.max_str_len, self.precision) else: format = '%%.%df' % (self.precision,) if len(non_zero): precision = max([_digits(x, self.precision, format) for x in non_zero]) else: precision = 0 precision = min(self.precision, precision) self.max_str_len = len(str(int(max_val))) + precision + 2 if _nc.any(special): self.max_str_len = max(self.max_str_len, len(_nan_str), len(_inf_str)+1) if self.sign: format = '%#+' else: format = '%#' format = format + '%d.%df' % (self.max_str_len, precision) self.special_fmt = '%%%ds' % (self.max_str_len,) self.format = format def __call__(self, x, strip_zeros=True): from . import numeric as _nc with _nc.errstate(invalid='ignore'): if isnan(x): if self.sign: return self.special_fmt % ('+' + _nan_str,) else: return self.special_fmt % (_nan_str,) elif isinf(x): if x > 0: if self.sign: return self.special_fmt % ('+' + _inf_str,) else: return self.special_fmt % (_inf_str,) else: return self.special_fmt % ('-' + _inf_str,) s = self.format % x if self.large_exponent: # 3-digit exponent expsign = s[-3] if expsign == '+' or expsign == '-': s = s[1:-2] + '0' + s[-2:] elif self.exp_format: # 2-digit exponent if s[-3] == '0': s = ' ' + s[:-3] + s[-2:] elif strip_zeros: z = s.rstrip('0') s = z + ' '*(len(s)-len(z)) return s def _digits(x, precision, format): s = format % x z = s.rstrip('0') return precision - len(s) + len(z) class IntegerFormat(object): def __init__(self, data): try: max_str_len = max(len(str(maximum.reduce(data))), len(str(minimum.reduce(data)))) self.format = '%' + str(max_str_len) + 'd' except (TypeError, NotImplementedError): # if reduce(data) fails, this instance will not be called, just # instantiated in formatdict. pass except ValueError: # this occurs when everything is NA pass def __call__(self, x): if _MININT < x < _MAXINT: return self.format % x else: return "%s" % x class LongFloatFormat(object): # XXX Have to add something to determine the width to use a la FloatFormat # Right now, things won't line up properly def __init__(self, precision, sign=False): self.precision = precision self.sign = sign def __call__(self, x): if isnan(x): if self.sign: return '+' + _nan_str else: return ' ' + _nan_str elif isinf(x): if x > 0: if self.sign: return '+' + _inf_str else: return ' ' + _inf_str else: return '-' + _inf_str elif x >= 0: if self.sign: return '+' + format_longfloat(x, self.precision) else: return ' ' + format_longfloat(x, self.precision) else: return format_longfloat(x, self.precision) class LongComplexFormat(object): def __init__(self, precision): self.real_format = LongFloatFormat(precision) self.imag_format = LongFloatFormat(precision, sign=True) def __call__(self, x): r = self.real_format(x.real) i = self.imag_format(x.imag) return r + i + 'j' class ComplexFormat(object): def __init__(self, x, precision, suppress_small): self.real_format = FloatFormat(x.real, precision, suppress_small) self.imag_format = FloatFormat(x.imag, precision, suppress_small, sign=True) def __call__(self, x): r = self.real_format(x.real, strip_zeros=False) i = self.imag_format(x.imag, strip_zeros=False) if not self.imag_format.exp_format: z = i.rstrip('0') i = z + 'j' + ' '*(len(i)-len(z)) else: i = i + 'j' return r + i class DatetimeFormat(object): def __init__(self, x, unit=None, timezone=None, casting='same_kind'): # Get the unit from the dtype if unit is None: if x.dtype.kind == 'M': unit = datetime_data(x.dtype)[0] else: unit = 's' # If timezone is default, make it 'local' or 'UTC' based on the unit if timezone is None: # Date units -> UTC, time units -> local if unit in ('Y', 'M', 'W', 'D'): self.timezone = 'UTC' else: self.timezone = 'local' else: self.timezone = timezone self.unit = unit self.casting = casting def __call__(self, x): return "'%s'" % datetime_as_string(x, unit=self.unit, timezone=self.timezone, casting=self.casting) class TimedeltaFormat(object): def __init__(self, data): if data.dtype.kind == 'm': v = data.view('i8') max_str_len = max(len(str(maximum.reduce(v))), len(str(minimum.reduce(v)))) self.format = '%' + str(max_str_len) + 'd' def __call__(self, x): return self.format % x.astype('i8')
bsd-3-clause
wyc/django
tests/forms_tests/tests/test_widgets.py
112
10410
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.core.urlresolvers import reverse from django.forms import ( CheckboxSelectMultiple, ClearableFileInput, RadioSelect, TextInput, ) from django.forms.widgets import ( ChoiceFieldRenderer, ChoiceInput, RadioFieldRenderer, ) from django.test import SimpleTestCase, override_settings from django.utils import six from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.safestring import SafeData from ..models import Article class FormsWidgetTests(SimpleTestCase): def test_radiofieldrenderer(self): # RadioSelect uses a RadioFieldRenderer to render the individual radio inputs. # You can manipulate that object directly to customize the way the RadioSelect # is rendered. w = RadioSelect() r = w.get_renderer('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) inp_set1 = [] inp_set2 = [] inp_set3 = [] inp_set4 = [] for inp in r: inp_set1.append(str(inp)) inp_set2.append('%s<br />' % inp) inp_set3.append('<p>%s %s</p>' % (inp.tag(), inp.choice_label)) inp_set4.append( '%s %s %s %s %s' % ( inp.name, inp.value, inp.choice_value, inp.choice_label, inp.is_checked(), ) ) self.assertHTMLEqual('\n'.join(inp_set1), """<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label> <label><input type="radio" name="beatle" value="P" /> Paul</label> <label><input type="radio" name="beatle" value="G" /> George</label> <label><input type="radio" name="beatle" value="R" /> Ringo</label>""") self.assertHTMLEqual('\n'.join(inp_set2), """<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label><br /> <label><input type="radio" name="beatle" value="P" /> Paul</label><br /> <label><input type="radio" name="beatle" value="G" /> George</label><br /> <label><input type="radio" name="beatle" value="R" /> Ringo</label><br />""") self.assertHTMLEqual('\n'.join(inp_set3), """<p><input checked="checked" type="radio" name="beatle" value="J" /> John</p> <p><input type="radio" name="beatle" value="P" /> Paul</p> <p><input type="radio" name="beatle" value="G" /> George</p> <p><input type="radio" name="beatle" value="R" /> Ringo</p>""") self.assertHTMLEqual('\n'.join(inp_set4), """beatle J J John True beatle J P Paul False beatle J G George False beatle J R Ringo False""") # A RadioFieldRenderer object also allows index access to individual RadioChoiceInput w = RadioSelect() r = w.get_renderer('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) self.assertHTMLEqual(str(r[1]), '<label><input type="radio" name="beatle" value="P" /> Paul</label>') self.assertHTMLEqual( str(r[0]), '<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label>' ) self.assertTrue(r[0].is_checked()) self.assertFalse(r[1].is_checked()) self.assertEqual((r[1].name, r[1].value, r[1].choice_value, r[1].choice_label), ('beatle', 'J', 'P', 'Paul')) # These individual widgets can accept extra attributes if manually rendered. self.assertHTMLEqual( r[1].render(attrs={'extra': 'value'}), '<label><input type="radio" extra="value" name="beatle" value="P" /> Paul</label>' ) with self.assertRaises(IndexError): r[10] # You can create your own custom renderers for RadioSelect to use. class MyRenderer(RadioFieldRenderer): def render(self): return '<br />\n'.join(six.text_type(choice) for choice in self) w = RadioSelect(renderer=MyRenderer) self.assertHTMLEqual( w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<label><input type="radio" name="beatle" value="J" /> John</label><br /> <label><input type="radio" name="beatle" value="P" /> Paul</label><br /> <label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br /> <label><input type="radio" name="beatle" value="R" /> Ringo</label>""" ) # Or you can use custom RadioSelect fields that use your custom renderer. class CustomRadioSelect(RadioSelect): renderer = MyRenderer w = CustomRadioSelect() self.assertHTMLEqual( w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<label><input type="radio" name="beatle" value="J" /> John</label><br /> <label><input type="radio" name="beatle" value="P" /> Paul</label><br /> <label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br /> <label><input type="radio" name="beatle" value="R" /> Ringo</label>""" ) # You can customize rendering with outer_html/inner_html renderer variables (#22950) class MyRenderer(RadioFieldRenderer): # str is just to test some Python 2 issue with bytestrings outer_html = str('<div{id_attr}>{content}</div>') inner_html = '<p>{choice_value}{sub_widgets}</p>' w = RadioSelect(renderer=MyRenderer) output = w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')), attrs={'id': 'bar'}) self.assertIsInstance(output, SafeData) self.assertHTMLEqual( output, """<div id="bar"> <p><label for="bar_0"><input checked="checked" type="radio" id="bar_0" value="J" name="beatle" /> John</label></p> <p><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle" /> Paul</label></p> <p><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle" /> George</label></p> <p><label for="bar_3"><input type="radio" id="bar_3" value="R" name="beatle" /> Ringo</label></p> </div>""") def test_subwidget(self): # Each subwidget tag gets a separate ID when the widget has an ID specified self.assertHTMLEqual("\n".join(c.tag() for c in CheckboxSelectMultiple(attrs={'id': 'abc'}).subwidgets('letters', list('ac'), choices=zip(list('abc'), list('ABC')))), """<input checked="checked" type="checkbox" name="letters" value="a" id="abc_0" /> <input type="checkbox" name="letters" value="b" id="abc_1" /> <input checked="checked" type="checkbox" name="letters" value="c" id="abc_2" />""") # Each subwidget tag does not get an ID if the widget does not have an ID specified self.assertHTMLEqual("\n".join(c.tag() for c in CheckboxSelectMultiple().subwidgets('letters', list('ac'), choices=zip(list('abc'), list('ABC')))), """<input checked="checked" type="checkbox" name="letters" value="a" /> <input type="checkbox" name="letters" value="b" /> <input checked="checked" type="checkbox" name="letters" value="c" />""") # The id_for_label property of the subwidget should return the ID that is used on the subwidget's tag self.assertHTMLEqual("\n".join('<input type="checkbox" name="letters" value="%s" id="%s" />' % (c.choice_value, c.id_for_label) for c in CheckboxSelectMultiple(attrs={'id': 'abc'}).subwidgets('letters', [], choices=zip(list('abc'), list('ABC')))), """<input type="checkbox" name="letters" value="a" id="abc_0" /> <input type="checkbox" name="letters" value="b" id="abc_1" /> <input type="checkbox" name="letters" value="c" id="abc_2" />""") def test_sub_widget_html_safe(self): widget = TextInput() subwidget = next(widget.subwidgets('username', 'John Doe')) self.assertTrue(hasattr(subwidget, '__html__')) self.assertEqual(force_text(subwidget), subwidget.__html__()) def test_choice_input_html_safe(self): widget = ChoiceInput('choices', 'CHOICE1', {}, ('CHOICE1', 'first choice'), 0) self.assertTrue(hasattr(ChoiceInput, '__html__')) self.assertEqual(force_text(widget), widget.__html__()) def test_choice_field_renderer_html_safe(self): renderer = ChoiceFieldRenderer('choices', 'CHOICE1', {}, [('CHOICE1', 'first_choice')]) renderer.choice_input_class = lambda *args: args self.assertTrue(hasattr(ChoiceFieldRenderer, '__html__')) self.assertEqual(force_text(renderer), renderer.__html__()) @override_settings(ROOT_URLCONF='forms_tests.urls') class LiveWidgetTests(AdminSeleniumWebDriverTestCase): available_apps = ['forms_tests'] + AdminSeleniumWebDriverTestCase.available_apps def test_textarea_trailing_newlines(self): """ Test that a roundtrip on a ModelForm doesn't alter the TextField value """ article = Article.objects.create(content="\nTst\n") self.selenium.get('%s%s' % (self.live_server_url, reverse('article_form', args=[article.pk]))) self.selenium.find_element_by_id('submit').submit() article = Article.objects.get(pk=article.pk) # Should be "\nTst\n" after #19251 is fixed self.assertEqual(article.content, "\r\nTst\r\n") @python_2_unicode_compatible class FakeFieldFile(object): """ Quacks like a FieldFile (has a .url and unicode representation), but doesn't require us to care about storages etc. """ url = 'something' def __str__(self): return self.url class ClearableFileInputTests(SimpleTestCase): def test_render_custom_template(self): widget = ClearableFileInput() widget.template_with_initial = ( '%(initial_text)s: <img src="%(initial_url)s" alt="%(initial)s" /> ' '%(clear_template)s<br />%(input_text)s: %(input)s' ) self.assertHTMLEqual( widget.render('myfile', FakeFieldFile()), 'Currently: <img src="something" alt="something" /> ' '<input type="checkbox" name="myfile-clear" id="myfile-clear_id" /> ' '<label for="myfile-clear_id">Clear</label><br />Change: <input type="file" name="myfile" />' )
bsd-3-clause
maelstromio/maelstrom-py
maelstrom/row.py
2
2413
from datetime import datetime import db_utils as db class Row(object): _get_row_by_id = staticmethod(db.get_row_by_id) _get_row_spec_prop = staticmethod(db.get_row_spec_prop) _get_rows_by_id = staticmethod(db.get_rows_by_id) _set_row = staticmethod(db.insert_row_data) _set_rows = staticmethod(db.set_rows_data) _build = staticmethod(db.create_column_family) _drop = staticmethod(db.drop_column_family) _delete = staticmethod(db.delete_row) _multi_delete = staticmethod(db.delete_rows) id = '' __tablename__ = '' defaults = {} def __init__(self, unique_id, *args, **kwargs): for k in kwargs: if k == 'id':continue if type(self.defaults[k]) != type(kwargs[k]): if type(kwargs[k]) == datetime: kwargs[k] = db.to_epoch(kwargs[k]) continue kwargs[k] = type(self.defaults[k])(kwargs[k]) self.__dict__.update(kwargs) self.id = unique_id def __getattr__(self, name): print name object.__getattr__(self, name) def __setattr__(self, name, value): object.__setattr__(self, name, value) def __repr__(self): s = '<'+str(self.__class__.__name__)+' ' for k in sorted(self.__dict__.iterkeys()): if type(self.__dict__[k]) == datetime: continue s += str(k)+': '+str(self.__dict__[k])+', ' return s[:-2]+'>' def __eq__(self, other): return self.__dict__ == other.__dict__ ''' @classmethod def _query(cls, row_type, *rules, **kwargs): return Query(row_type, *rules, **kwargs) ''' @classmethod def _multi_commit(cls, list_of_rows): ids = [] kwargs = [] for row in list_of_rows: ids.append(row.id) kwargs.append(row.__dict__) cls._set_rows(cls.__tablename__, ids, kwargs) @classmethod def build(cls): cls._build(cls.__tablename__, **cls.defaults) @classmethod def drop(cls): cls._drop(cls.__tablename__) @classmethod def rebuild(cls): try: cls.drop() except Exception as e: pass cls.build() def _update(self, **kwargs): self.__dict__.update(kwargs) def _commit(self): self._set_row(self.__tablename__, self.id, **self.__dict__)
mit
tmthydvnprt/compfipy
compfipy/asset.py
1
74951
# pylint: disable=too-many-public-methods """ asset.py Define the an asset class to contain price data and various calculations, measures, and processed versions of data. """ import datetime import collections import tabulate import scipy.stats import pandas as pd import numpy as np import matplotlib.pyplot as plt from compfipy.util import RISK_FREE_RATE, MONTHS_IN_YEAR, DAYS_IN_YEAR, DAYS_IN_TRADING_YEAR from compfipy.util import FIBONACCI_SEQUENCE, FIBONACCI_DECIMAL, RANK_PERCENTS, RANK_DAYS_IN_TRADING_YEAR from compfipy.util import calc_returns, calc_cagr, fmtp, fmtn, fmttn, sma, ema # Helper Functions for Fibonacci Code # ------------------------------------------------------------------------------------------------------------------------------ def fibonacci_retracement(price=0.0, lastprice=0.0): """ Fibonacci_retracement """ return price + FIBONACCI_DECIMAL * (lastprice - price) def fibonacci_arc(price=0.0, lastprice=0.0, days_since_last_price=0, n_days=0): """ Fibonacci_arc """ fib_radius = FIBONACCI_DECIMAL * np.sqrt(np.power(lastprice - price, 2) + np.power(days_since_last_price, 2)) return price - np.sqrt(np.power(fib_radius, 2) - np.power(n_days, 2)) def fibonacci_time(date=datetime.date.today()): """ Fibonacci_time """ return [date + datetime.timedelta(days=d) for d in FIBONACCI_SEQUENCE] # General Utility Functions # ------------------------------------------------------------------------------------------------------------------------------ def plot(x, figsize=(16, 4), title=None, logy=False, **kwargs): """ Plot helper, assumes a pd.Series or pd.DataFrame. """ title = title if title else 'Price Series' x.plot(figsize=figsize, title=title, logy=logy, **kwargs) def scatter_matrix(x, figsize=(16, 4), title=None, logy=False, **kwargs): """ Plot helper, assumes a pd.Series or pd.DataFrame. """ title = title if title else 'Price Scatter Matrix' x.scatter_matrix(figsize=figsize, title=title, logy=logy, **kwargs) def hist(x, figsize=(16, 4), title=None, logy=False, **kwargs): """ Plot helper, assumes a pd.Series or pd.DataFrame. """ title = title if title else 'Return Histogram' x.hist(figsize=figsize, title=title, logy=logy, **kwargs) # General Asse Class # ------------------------------------------------------------------------------------------------------------------------------ class Asset(object): # pylint: disable=line-too-long """ Asset Class for storing OCHLV price data, and calculating overlays and indicators from price data. Overlays -------- [x] Bollinger Bands - A chart overlay that shows the upper and lower limits of 'normal' price movements based on the Standard Deviation of prices. [x] Chandelier Exit - A indicator that can be used to set trailing stop-losses for both long and short position. [x] Ichimoku Clouds - A comprehensive indicator that defines support and resistance, identifies trend direction, gauges momentum and provides trading signals. [x] Keltner Channels - A chart overlay that shows upper and lower limits for price movements based on the Average True Range of prices. [x] Moving Averages - Simple and Exponential - Chart overlays that show the 'average' value over time. Both Simple Moving Averages (SMAs) and Exponential Moving Averages (EMAs) are explained. [x] Moving Average Envelopes - A chart overlay consisting of a channel formed from simple moving averages. [x] Parabolic SAR - A chart overlay that shows reversal points below prices in an uptrend and above prices in a downtrend. [x] Pivot Points - A chart overlay that shows reversal points below prices in an uptrend and above prices in a downtrend. [x] Price Channels - A chart overlay that shows a channel made from the highest high and lowest low for a given period of time. [x] Volume by Price - A chart overlay with a horizontal histogram showing the amount of activity at various price levels. [x] Volume-weighted Average Price (VWAP) - An intraday indicator based on total dollar value of all trades for the current day divided by the total trading volume for the current day. [x] ZigZag - A chart overlay that shows filtered price movements that are greater than a given percentage. Indicators ---------- [x] Accumulation Distribution Line - Combines price and volume to show how money may be flowing into or out of a stock. [x] Aroon - Uses Aroon Up and Aroon Down to determine whether a stock is trending or not. [x] Aroon Oscillator - Measures the difference between Aroon Up and Aroon Down. [x] Average Directional Index (ADX) - Shows whether a stock is trending or oscillating. [x] Average True Range (ATR) - Measures a stock's volatility. [x] BandWidth - Shows the percentage difference between the upper and lower Bollinger Band. [x] %B Indicator - Shows the relationship between price and standard deviation bands. [x] Commodity Channel Index (CCI) - Shows a stock's variation from its 'typical' price. [x] Coppock Curve - An oscillator that uses rate-of-change and a weighted moving average to measure momentum. [x] Chaikin Money Flow - Combines price and volume to show how money may be flowing into or out of a stock. Alternative to Accumulation/Distribution Line. [x] Chaikin Oscillator - Combines price and volume to show how money may be flowing into or out of a stock. Based on Accumulation/Distribution Line. [x] Price Momentum Oscillator - An advanced momentum indicator that tracks a stock's rate of change. [x] Detrended Price Oscillator (DPO) - A price oscillator that uses a displaced moving average to identify cycles. [x] Ease of Movement (EMV) - An indicator that compares volume and price to identify significant moves. [x] Force Index - A simple price-and-volume oscillator. [x] Know Sure Thing (KST) - An indicator that measures momentum in a smooth fashion. [x] Mass Index - An indicator that identifies reversals when the price range widens. [x] MACD - A momentum oscillator based on the difference between two EMAs. [x] MACD-Histogram - A momentum oscillator that shows the difference between MACD and its signal line. [x] Money Flow Index (MFI) - A volume-weighted version of RSI that shows shifts is buying and selling pressure. [x] Negative Volume Index (NVI) - A cumulative volume-based indicator used to identify trend reversals. [x] On Balance Volume (OBV) - Combines price and volume in a very simple way to show how money may be flowing into or out of a stock. [x] Percentage Price Oscillator (PPO) - A percentage-based version of the MACD indicator. [x] Percentage Volume Oscillator - The PPO indicator applied to volume instead of price. [x] Rate of Change (ROC) - Shows the speed at which a stock's price is changing. [x] Relative Strength Index (RSI) - Shows how strongly a stock is moving in its current direction. [x] StockCharts Tech. Ranks (SCTRs) - Our relative ranking system based on a stock's technical strength. [ ] Slope - Measures the rise-over-run for a linear regression [x] Standard Deviation (Volatility) - A statistical measure of a stock's volatility. [x] Stochastic Oscillator - Shows how a stock's price is doing relative to past movements. Fast, Slow and Full Stochastics are explained. [x] StochRSI - Combines Stochastics with the RSI indicator. Helps you see RSI changes more clearly. [x] TRIX - A triple-smoothed moving average of price movements. [x] True Strength Index (TSI) - An indicator that measures trend direction and identifies overbought/oversold levels. [x] Ulcer Index - An indicator designed to measure market risk or volatility. [x] Ultimate Oscillator - Combines long-term, mid-term and short-term moving averages into one number. [x] Vortex Indicator - An indicator designed to identify the start of a new trend and define the current trend. [x] William %R - Uses Stochastics to determine overbought and oversold levels. Charts ------ [x] Gaps - An area of price change in which there were no trades. [ ] Classify Gaps - decide if a gap is [ ] common, [ ] breakaway, [ ] runaway, or [ ] exhaustion [ ] Double Top Reversal [ ] Double Bottom Reversal [ ] Head and Shoulders Top (Reversal) [ ] Head and Shoulders Bottom (Reversal) [ ] Falling Wedge (Reversal) [ ] Rising Wedge (Reversal) [ ] Rounding Bottom (Reversal) [ ] Triple Top Reversal [ ] Triple Bottom Reversal [ ] Bump and Run Reversal (Reversal) [ ] Flag, Pennant (Continuation) [ ] Symmetrical Triangle (Continuation) [ ] Ascending Triangle (Continuation) [ ] Descending Triangle (Continuation) [ ] Rectangle (Continuation) [ ] Price Channel (Continuation) [ ] Measured Move - Bullish (Continuation) [ ] Measured Move - Bearish (Continuation) [ ] Cup with Handle (Continuation) [ ] Introduction to Candlesticks - An overview of candlesticks, including history, formation, and key patterns. [ ] Candlesticks and Support - How candlestick chart patterns can mark support levels. [ ] Candlesticks and Resistance - How candlestick chart patterns can mark resistance levels. [ ] Candlestick Bullish Reversal Patterns - Detailed descriptions of bullish reversal candlestick patterns [ ] Candlestick Bearish Reversal Patterns - Detailed descriptions of common bearish reversal candlestick patterns. [ ] Candlestick Pattern Dictionary - A comprehensive list of common candlestick patterns. [ ] Arms CandleVolume - A price chart that merges candlesticks with EquiVolume boxes. [ ] CandleVolume - A price chart that merges candlesticks with volume. [ ] Elder Impulse System - A trading system that color codes the price bars to show signals. [ ] EquiVolume - Price boxes that incorporate volume. How to use and interpret EquiVolume boxes. [ ] Heikin-Ashi - A candlestick method that uses price data from two periods instead one one. [ ] Kagi Charts - How to use and interpret Kagi charts. [ ] Point and Figure Charts - How to use and interpret Point and Figure charts. [ ] Renko Charts - How to use and interpret Renko charts. [ ] Three Line Break Charts - How to use and interpret Three Line Break charts. [ ] Andrews' Pitchfork - Drawing, adjusting and interpreting this trend channel tool. [ ] Cycles - Steps to finding cycles and using the Cycle Lines Tool. [o] Fibonacci Retracements - Defines Fibonacci retracements and shows how to use them to identify reversal zones. [o] Fibonacci Arcs - Shows how Fibonacci Arcs can be used to find reversals. [ ] Fibonacci Fans - Explains what Fibonacci Fans are and how they can be used. [o] Fibonacci Time Zones - Describes Fibonacci Time Zones and how they can be used. [x] Quandrant Lines - Defines Quadrant Lines and shows how they can be used to find future support/resistance zones. [ ] Raff Regression Channel - A channel tool based on two equidistant trendlines on either side of a linear regression. [ ] Speed Resistance Lines - Shows how Speed Resistance Lines are used on charts. """ # pylint: enable=line-too-long def __init__(self, data=None, market_cap=1.0): """ Create an asset, with string symbol and pandas.Series of price data. """ self.symbol = data.index.name self.data = data self.market_cap = market_cap self.stats = {} def __str__(self): """ Return string representation. """ return str(self.data) # Summary stats # -------------------------------------------------------------------------------------------------------------------------- def calc_stats(self, yearly_risk_free_return=RISK_FREE_RATE): """ Calculate common statistics for this asset. """ # pylint: disable=too-many-statements monthly_risk_free_return = (np.power(1 + yearly_risk_free_return, 1.0 / MONTHS_IN_YEAR) - 1.0) * MONTHS_IN_YEAR daily_risk_free_return = (np.power(1 + yearly_risk_free_return, 1.0 / DAYS_IN_TRADING_YEAR) - 1.0) * DAYS_IN_TRADING_YEAR # Sample prices daily_price = self.close monthly_price = daily_price.resample('M').last() yearly_price = daily_price.resample('A').last() self.stats = { 'name' : self.symbol, 'start': daily_price.index[0], 'end': daily_price.index[-1], 'market_cap' : self.market_cap, 'yearly_risk_free_return': yearly_risk_free_return, 'daily_mean': np.nan, 'daily_vol': np.nan, 'daily_sharpe': np.nan, 'best_day': np.nan, 'worst_day': np.nan, 'total_return': np.nan, 'cagr': np.nan, 'incep': np.nan, 'max_drawdown': np.nan, 'avg_drawdown': np.nan, 'avg_drawdown_days': np.nan, 'daily_skew': np.nan, 'daily_kurt': np.nan, 'monthly_mean': np.nan, 'monthly_vol': np.nan, 'monthly_sharpe': np.nan, 'best_month': np.nan, 'worst_month': np.nan, 'mtd': np.nan, 'pos_month_perc': np.nan, 'avg_up_month': np.nan, 'avg_down_month': np.nan, 'three_month': np.nan, 'monthly_skew': np.nan, 'monthly_kurt': np.nan, 'six_month': np.nan, 'ytd': np.nan, 'one_year': np.nan, 'yearly_mean': np.nan, 'yearly_vol': np.nan, 'yearly_sharpe': np.nan, 'best_year': np.nan, 'worst_year': np.nan, 'three_year': np.nan, 'win_year_perc': np.nan, 'twelve_month_win_perc': np.nan, 'yearly_skew': np.nan, 'yearly_kurt': np.nan, 'five_year': np.nan, 'ten_year': np.nan, 'return_table': {} } if len(daily_price) is 1: return self # Stats with daily prices r = calc_returns(daily_price) if len(r) < 4: return self self.stats['daily_mean'] = DAYS_IN_TRADING_YEAR * r.mean() self.stats['daily_vol'] = np.sqrt(DAYS_IN_TRADING_YEAR) * r.std() self.stats['daily_sharpe'] = (self.stats['daily_mean'] - daily_risk_free_return) / self.stats['daily_vol'] self.stats['best_day'] = r.ix[r.idxmax():r.idxmax()] self.stats['worst_day'] = r.ix[r.idxmin():r.idxmin()] self.stats['total_return'] = (daily_price[-1] / daily_price[0]) - 1.0 self.stats['ytd'] = self.stats['total_return'] self.stats['cagr'] = calc_cagr(daily_price) self.stats['incep'] = self.stats['cagr'] drawdown_info = self.drawdown_info() self.stats['max_drawdown'] = drawdown_info['drawdown'].min() self.stats['avg_drawdown'] = drawdown_info['drawdown'].mean() self.stats['avg_drawdown_days'] = drawdown_info['days'].mean() self.stats['daily_skew'] = r.skew() self.stats['daily_kurt'] = r.kurt() if len(r[(~np.isnan(r)) & (r != 0)]) > 0 else np.nan # Stats with monthly prices mr = calc_returns(monthly_price) if len(mr) < 2: return self self.stats['monthly_mean'] = MONTHS_IN_YEAR * mr.mean() self.stats['monthly_vol'] = np.sqrt(MONTHS_IN_YEAR) * mr.std() self.stats['monthly_sharpe'] = (self.stats['monthly_mean'] - monthly_risk_free_return) / self.stats['monthly_vol'] self.stats['best_month'] = mr.ix[mr.idxmax():mr.idxmax()] self.stats['worst_month'] = mr.ix[mr.idxmin():mr.idxmin()] self.stats['mtd'] = (daily_price[-1] / monthly_price[-2]) - 1.0 # -2 because monthly[1] = daily[-1] self.stats['pos_month_perc'] = len(mr[mr > 0]) / float(len(mr) - 1.0) # -1 to ignore first NaN self.stats['avg_up_month'] = mr[mr > 0].mean() self.stats['avg_down_month'] = mr[mr <= 0].mean() # Table for lookback periods self.stats['return_table'] = collections.defaultdict(dict) for mi in mr.index: self.stats['return_table'][mi.year][mi.month] = mr[mi] fidx = mr.index[0] try: self.stats['return_table'][fidx.year][fidx.month] = (float(monthly_price[0]) / daily_price[0]) - 1 except ZeroDivisionError: self.stats['return_table'][fidx.year][fidx.month] = 0.0 # Calculate YTD for year, months in self.stats['return_table'].items(): self.stats['return_table'][year][13] = np.prod(np.array(months.values()) + 1) - 1.0 if len(mr) < 3: return self denominator = daily_price[:daily_price.index[-1] - pd.DateOffset(months=3)] self.stats['three_month'] = (daily_price[-1] / denominator[-1]) - 1 if len(denominator) > 0 else np.nan if len(mr) < 4: return self self.stats['monthly_skew'] = mr.skew() self.stats['monthly_kurt'] = mr.kurt() if len(mr[(~np.isnan(mr)) & (mr != 0)]) > 0 else np.nan denominator = daily_price[:daily_price.index[-1] - pd.DateOffset(months=6)] self.stats['six_month'] = (daily_price[-1] / denominator[-1]) - 1 if len(denominator) > 0 else np.nan # Stats with yearly prices yr = calc_returns(yearly_price) if len(yr) < 2: return self self.stats['ytd'] = (daily_price[-1] / yearly_price[-2]) - 1.0 denominator = daily_price[:daily_price.index[-1] - pd.DateOffset(years=1)] self.stats['one_year'] = (daily_price[-1] / denominator[-1]) - 1 if len(denominator) > 0 else np.nan self.stats['yearly_mean'] = yr.mean() self.stats['yearly_vol'] = yr.std() self.stats['yearly_sharpe'] = (self.stats['yearly_mean'] - yearly_risk_free_return) / self.stats['yearly_vol'] self.stats['best_year'] = yr.ix[yr.idxmax():yr.idxmax()] self.stats['worst_year'] = yr.ix[yr.idxmin():yr.idxmin()] # Annualize stat for over 1 year self.stats['three_year'] = calc_cagr(daily_price[daily_price.index[-1] - pd.DateOffset(years=3):]) self.stats['win_year_perc'] = len(yr[yr > 0]) / float(len(yr) - 1.0) self.stats['twelve_month_win_perc'] = (monthly_price.pct_change(11) > 0).sum() / float(len(monthly_price) - (MONTHS_IN_YEAR - 1.0)) if len(yr) < 4: return self self.stats['yearly_skew'] = yr.skew() self.stats['yearly_kurt'] = yr.kurt() if len(yr[(~np.isnan(yr)) & (yr != 0)]) > 0 else np.nan self.stats['five_year'] = calc_cagr(daily_price[daily_price.index[-1] - pd.DateOffset(years=5):]) self.stats['ten_year'] = calc_cagr(daily_price[daily_price.index[-1] - pd.DateOffset(years=10):]) return self # pylint: enable=too-many-statements def display_stats(self): """ Display talbe of stats. """ stats = [ ('start', 'Start', 'dt'), ('end', 'End', 'dt'), ('yearly_risk_free_return', 'Risk-free rate', 'p'), (None, None, None), ('total_return', 'Total Return', 'p'), ('daily_sharpe', 'Daily Sharpe', 'n'), ('cagr', 'CAGR', 'p'), ('max_drawdown', 'Max Drawdown', 'p'), ('market_cap', 'Market Cap', 't'), (None, None, None), ('mtd', 'MTD', 'p'), ('three_month', '3m', 'p'), ('six_month', '6m', 'p'), ('ytd', 'YTD', 'p'), ('one_year', '1Y', 'p'), ('three_year', '3Y (ann.)', 'p'), ('five_year', '5Y (ann.)', 'p'), ('ten_year', '10Y (ann.)', 'p'), ('incep', 'Since Incep. (ann.)', 'p'), (None, None, None), ('daily_sharpe', 'Daily Sharpe', 'n'), ('daily_mean', 'Daily Mean (ann.)', 'p'), ('daily_vol', 'Daily Vol (ann.)', 'p'), ('daily_skew', 'Daily Skew', 'n'), ('daily_kurt', 'Daily Kurt', 'n'), ('best_day', 'Best Day', 'pp'), ('worst_day', 'Worst Day', 'pp'), (None, None, None), ('monthly_sharpe', 'Monthly Sharpe', 'n'), ('monthly_mean', 'Monthly Mean (ann.)', 'p'), ('monthly_vol', 'Monthly Vol (ann.)', 'p'), ('monthly_skew', 'Monthly Skew', 'n'), ('monthly_kurt', 'Monthly Kurt', 'n'), ('best_month', 'Best Month', 'pp'), ('worst_month', 'Worst Month', 'pp'), (None, None, None), ('yearly_sharpe', 'Yearly Sharpe', 'n'), ('yearly_mean', 'Yearly Mean', 'p'), ('yearly_vol', 'Yearly Vol', 'p'), ('yearly_skew', 'Yearly Skew', 'n'), ('yearly_kurt', 'Yearly Kurt', 'n'), ('best_year', 'Best Year', 'pp'), ('worst_year', 'Worst Year', 'pp'), (None, None, None), ('avg_drawdown', 'Avg. Drawdown', 'p'), ('avg_drawdown_days', 'Avg. Drawdown Days', 'n'), ('avg_up_month', 'Avg. Up Month', 'p'), ('avg_down_month', 'Avg. Down Month', 'p'), ('win_year_perc', 'Win Year %', 'p'), ('twelve_month_win_perc', 'Win 12m %', 'p') ] data = [] first_row = ['Stat'] first_row.extend([self.stats['name']]) data.append(first_row) for k, n, f in stats: # Blank row if k is None: row = [''] * len(data[0]) data.append(row) continue row = [n] raw = self.stats[k] if f is None: row.append(raw) elif f == 'p': row.append(fmtp(raw)) elif f == 'n': row.append(fmtn(raw)) elif f == 't': row.append(fmttn(raw)) elif f == 'pp': row.append(fmtp(raw[0])) elif f == 'dt': row.append(raw.strftime('%Y-%m-%d')) else: print 'bad' data.append(row) print tabulate.tabulate(data, headers='firstrow') return self def summary(self): """ Displays summary of Asset. """ print 'Summary of %s from %s to %s' % (self.stats['name'], self.stats['start'], self.stats['end']) print 'Annual risk-free rate considered: %s' %(fmtp(self.stats['yearly_risk_free_return'])) print '\nSummary:' data = [[fmtp(self.stats['total_return']), fmtn(self.stats['daily_sharpe']), fmtp(self.stats['cagr']), fmtp(self.stats['max_drawdown']), fmttn(self.stats['market_cap'])]] print tabulate.tabulate(data, headers=['Total Return', 'Sharpe', 'CAGR', 'Max Drawdown', 'Market Cap']) print '\nAnnualized Returns:' data = [[fmtp(self.stats['mtd']), fmtp(self.stats['three_month']), fmtp(self.stats['six_month']), fmtp(self.stats['ytd']), fmtp(self.stats['one_year']), fmtp(self.stats['three_year']), fmtp(self.stats['five_year']), fmtp(self.stats['ten_year']), fmtp(self.stats['incep'])]] print tabulate.tabulate(data, headers=['MTD', '3M', '6M', 'YTD', '1Y', '3Y', '5Y', '10Y', 'Incep.']) print '\nPeriodic Returns:' data = [ ['sharpe', fmtn(self.stats['daily_sharpe']), fmtn(self.stats['monthly_sharpe']), fmtn(self.stats['yearly_sharpe'])], ['mean', fmtp(self.stats['daily_mean']), fmtp(self.stats['monthly_mean']), fmtp(self.stats['yearly_mean'])], ['vol', fmtp(self.stats['daily_vol']), fmtp(self.stats['monthly_vol']), fmtp(self.stats['yearly_vol'])], ['skew', fmtn(self.stats['daily_skew']), fmtn(self.stats['monthly_skew']), fmtn(self.stats['yearly_skew'])], ['kurt', fmtn(self.stats['daily_kurt']), fmtn(self.stats['monthly_kurt']), fmtn(self.stats['yearly_kurt'])], ['best price', fmtp(self.stats['best_day'][0]), fmtp(self.stats['best_month'][0]), fmtp(self.stats['best_year'][0])], ['best time', self.stats['best_day'].index[0].strftime('%Y-%m-%d'), self.stats['best_month'].index[0].strftime('%Y-%m-%d'), \ self.stats['best_year'].index[0].strftime('%Y-%m-%d')], ['worst price', fmtp(self.stats['worst_day'][0]), fmtp(self.stats['worst_month'][0]), fmtp(self.stats['worst_year'][0])], ['worst time', self.stats['worst_day'].index[0].strftime('%Y-%m-%d'), self.stats['worst_month'].index[0].strftime('%Y-%m-%d'), \ self.stats['worst_year'].index[0].strftime('%Y-%m-%d')] ] print tabulate.tabulate(data, headers=['daily', 'monthly', 'yearly']) print '\nDrawdowns:' data = [ [fmtp(self.stats['max_drawdown']), fmtp(self.stats['avg_drawdown']), fmtn(self.stats['avg_drawdown_days'])]] print tabulate.tabulate(data, headers=['max', 'avg', '# days']) print '\nMisc:' data = [['avg. up month', fmtp(self.stats['avg_up_month'])], ['avg. down month', fmtp(self.stats['avg_down_month'])], ['up year %', fmtp(self.stats['win_year_perc'])], ['12m up %', fmtp(self.stats['twelve_month_win_perc'])]] print tabulate.tabulate(data) return self # Class Helper Functions # -------------------------------------------------------------------------------------------------------------------------- def describe(self): """ Wrapper for pandas describe(). """ self.data.describe() def time_range(self, start=None, end=datetime.date.today(), freq='B'): """ Return a specific time range of the Asset. """ if isinstance(start, datetime.date) and isinstance(end, datetime.date): date_range = pd.date_range(start, end, freq=freq) else: date_range = pd.date_range(end - datetime.timedelta(days=start), periods=start, freq=freq) return Asset(self.symbol, self.data.loc[date_range]) def plot(self): """ Wrapper for pandas plot(). """ plt.figure() self.data[['Open', 'Close', 'High', 'Low']].plot(figsize=(16, 4), title='{} OCHL Price'.format(self.symbol.upper())) plt.figure() self.data[['Volume']].plot(figsize=(16, 4), title='{} Volume'.format(self.symbol.upper())) plt.figure() ax3 = (100.0 * self.returns()).hist(figsize=(16, 4), bins=100, normed=1) (100.0 * self.returns()).plot(kind='kde', ax=ax3) ax3.set_title('{} Daily Return Distribution'.format(self.symbol.upper())) plt.figure() ax4 = (100.0 * self.returns(freq='M')).hist(figsize=(16, 4), bins=100, normed=1) (100.0 * self.returns(freq='M')).plot(kind='kde', ax=ax4) ax4.set_title('{} Monthly Return Distribution'.format(self.symbol.upper())) # Bring underlying data to class properties # -------------------------------------------------------------------------------------------------------------------------- @property def number_of_days(self): """ Return total number of days in price data. """ return len(self.close) @property def close(self): """ Return closing price of asset. """ return self.data['Close'] @property def c(self): """ Return closing price of asset. """ return self.close @property def adj_close(self): """ Return adjusted closing price of asset. """ return self.data['Adj_Close'] @property def ac(self): """ Return adjusted closing price of asset. """ return self.adj_close @property def open(self): """ Return opening price of asset. """ return self.data['Open'] @property def o(self): """ Return opening price of asset. """ return self.open @property def high(self): """ Return high price of asset. """ return self.data['High'] @property def h(self): """ Return high price of asset. """ return self.high @property def low(self): """ Return low price of asset. """ return self.data['Low'] @property def l(self): """ Return low price of asset. """ return self.low @property def volume(self): """ Return volume of asset. """ return self.data['Volume'] @property def v(self): """ Return volume of asset. """ return self.volume # Common Price Transformations # -------------------------------------------------------------------------------------------------------------------------- def money_flow(self): """ Calculate money flow. (close - low) - (high - close) money flow = ------------------------------ (high - low) """ return ((self.close - self.low) - (self.high - self.close)) / (self.high - self.low) def money_flow_volume(self): """ Calculate money flow volume. money flow volume = money flow * volume """ return self.money_flow() * self.volume def typical_price(self): """ Calculate typical price. (high + low + close) typical price = -------------------- 3 """ return (self.high + self.low + self.close) / 3.0 def close_to_open_range(self): """ Calculate close to open range. close to open range = open - last close """ return self.open - self.close.shift(1) def quadrant_range(self): """ Calculate quandrant range. l_i = i * (high - low) / 4, for i = [1, 4] """ size = self.high_low_spread() / 4.0 l1 = self.low l2 = l1 + size l3 = l2 + size l4 = l3 + size l5 = l4 + size return pd.DataFrame({'1': l1, '2': l2, '3': l3, '4': l4, '5': l5}) def true_range(self): """ Calculate true range. true range = high - last low """ return self.high - self.low.shift(1) def high_low_spread(self): """ Calculate high low spread. high low spread = high - low """ return self.high - self.low def rate_of_change(self, n=20): """ Calculate rate of change. close - last close rate of change = 100 * ------------------ last close """ return 100.0 * (self.close - self.close.shift(n)) / self.close.shift(n) def roc(self, n=20): """ Calculate rate of change. close - last close rate of change = 100 * ------------------ last close """ return self.rate_of_change(n) def drawdown(self): """ Calucate the drawdown from the highest high. """ # Don't change original data draw_down = self.close.copy() # Fill missing data draw_down = draw_down.ffill() # Ignore initial NaNs draw_down[np.isnan(draw_down)] = -np.Inf # Get highest high highest_high = draw_down.expanding().max() draw_down = (draw_down / highest_high) - 1.0 return draw_down def drawdown_info(self): """ Return table of drawdown data. """ drawdown = self.drawdown() is_zero = drawdown == 0 # Find start and end time start = ~is_zero & is_zero.shift(1) start = list(start[start].index) end = is_zero & (~is_zero).shift(1) end = list(end[end].index) # Handle no ending if len(end) is 0: end.append(drawdown.index[-1]) # Handle startingin drawdown if start[0] > end[0]: start.insert(0, drawdown.index[0]) # Handle finishing with drawdown if start[-1] > end[-1]: end.append(drawdown.index[-1]) info = pd.DataFrame({ 'start': start, 'end' : end, 'days' : [(e - s).days for s, e in zip(start, end)], 'drawdown':[drawdown[s:e].min() for s, e in zip(start, end)] }) return info # Overlays # -------------------------------------------------------------------------------------------------------------------------- def bollinger_bands(self, n=20, k=2): """ Calculate Bollinger Bands. """ ma = pd.rolling_mean(self.close, n) ub = ma + k * pd.rolling_std(self.close, n) lb = ma - k * pd.rolling_std(self.close, n) return pd.DataFrame({'ub': ub, 'mb': ma, 'lb': lb}) def chandelier_exit(self, n=22, k=3): """ Calculate Chandelier Exit. """ atr = self.atr(n) n_day_high = pd.rolling_max(self.high, n) n_day_low = pd.rolling_min(self.low, n) chdlr_exit_long = n_day_high - k * atr chdlr_exit_short = n_day_low - k * atr return pd.DataFrame({'long': chdlr_exit_long, 'short': chdlr_exit_short}) def ichimoku_clouds(self, n1=9, n2=26, n3=52): """ Calculate Ichimoku Clouds. """ high = self.high low = self.low conversion = (pd.rolling_max(high, n1) + pd.rolling_min(low, n1)) / 2.0 base = (pd.rolling_max(high, n2) + pd.rolling_min(low, n2)) / 2.0 leading_a = (conversion + base) / 2.0 leading_b = (pd.rolling_max(high, n3) + pd.rolling_min(low, n3)) / 2.0 lagging = self.close.shift(-n2) return pd.DataFrame({'conversion' : conversion, 'base': base, 'leadA': leading_a, 'leadB': leading_b, 'lag': lagging}) def keltner_channels(self, n=20, natr=10): """ Calculate Keltner Channels. """ atr = self.atr(natr) ml = ema(self.close, n) ul = ml + 2.0 * atr ll = ml - 2.0 * atr return pd.DataFrame({'ul': ul, 'ml': ml, 'll': ll}) def moving_average_envelopes(self, n=20, k=0.025): """ Calculate Moving Average Envelopes. """ close = self.close ma = sma(close, n) uma = ma + (k * ma) lma = ma - (k * ma) return pd.DataFrame({'uma': uma, 'ma': ma, 'lma': lma}) def parabolic_sar(self, step_r=0.02, step_f=0.02, max_af_r=0.2, max_af_f=0.2): """ Calculate Parabolic SAR. """ high = self.high low = self.low r_sar = pd.TimeSeries(np.zeros(len(high)), index=high.index) f_sar = pd.TimeSeries(np.zeros(len(high)), index=high.index) ep = high[0] af = step_r sar = low[0] up = True for i in range(1, len(high)): if up: # Rising SAR ep = np.max([ep, high[i]]) af = np.min([af + step_r if (ep == high[i]) else af, max_af_r]) sar = sar + af * (ep - sar) r_sar[i] = sar else: # Falling SAR ep = np.min([ep, low[i]]) af = np.min([af + step_f if (ep == low[i]) else af, max_af_f]) sar = sar + af * (ep - sar) f_sar[i] = sar # Trend switch if up and (sar > low[i] or sar > high[i]): up = False sar = ep af = step_f elif not up and (sar < low[i] or sar < high[i]): up = True sar = ep af = step_r return pd.DataFrame({'rising' : r_sar, 'falling': f_sar}) def pivot_point(self): """ Calculate pivot point """ p = self.typical_price() hl = self.high_low_spread() s1 = (2.0 * p) - self.high s2 = p - hl r1 = (2.0 * p) - self.low r2 = p + hl return pd.DataFrame({'p': p, 's1': s1, 's2': s2, 'r1': r1, 'r2': r2}) def fibonacci_pivot_point(self): """ Calculate Fibonacci Pivot Point. """ p = self.typical_price() hl = self.high_low_spread() s1 = p - 0.382 * hl s2 = p - 0.618 * hl s3 = p - 1.0 * hl r1 = p + 0.382 * hl r2 = p + 0.618 * hl r3 = p + 1.0 * hl return pd.DataFrame({'p': p, 's1': s1, 's2': s2, 's3': s3, 'r1': r1, 'r2': r2, 'r3': r3}) def demark_pivot_point(self): """ Calculate Demark Pivot Point. """ h_l_c = self.close < self.open h_lc = self.close > self.open hl_c = self.close == self.open p = np.zeros(len(self.close)) p[h_l_c] = self.high[h_l_c] + 2.0 * self.low[h_l_c] + self.close[h_l_c] p[h_lc] = 2.0 * self.high[h_lc] + self.low[h_lc] + self.close[h_lc] p[hl_c] = self.high[hl_c] + self.low[hl_c] + 2.0 * self.close[hl_c] s1 = p / 2.0 - self.high r1 = p / 2.0 - self.low p = p / 4.0 return pd.DataFrame({'p': p, 's1': s1, 'r1': r1}) def price_channel(self, n=20): """ Calculate Price Channel. """ n_day_high = pd.rolling_max(self.high, n) n_day_low = pd.rolling_min(self.low, n) center = (n_day_high + n_day_low) / 2.0 return pd.DataFrame({'high': n_day_high, 'low': n_day_low, 'center': center}) def volume_by_price(self, n=14, block_num=12): """ Calculate Volume by Price. """ close = self.close volume = self.volume nday_closing_high = pd.rolling_max(close, n).bfill() nday_closing_low = pd.rolling_min(close, n).bfill() # Compute price blocks: rolling high low range in block number steps price_blocks = pd.SpareSeries() for low, high, in zip(nday_closing_low, nday_closing_high): price_blocks = price_blocks.append(pd.DataFrame(np.linspace(low, high, block_num)).T) price_blocks = price_blocks.set_index(close.index) # Find correct block for each price, then tally that days volume volume_by_price = pd.DataFrame(np.zeros((close.shape[0], block_num))) for j in range(n-1, close.shape[0]): for i, c in enumerate(close[j-(n-1):j+1]): block = (price_blocks.iloc[i, :] <= c).sum() - 1.0 block = 0 if block < 0 else block volume_by_price.iloc[j, block] = volume[i] + volume_by_price.iloc[j, block] volume_by_price = volume_by_price.set_index(close.index) return volume_by_price def volume_weighted_average_price(self): """ Calculate Volume Weighted Average Price (VWAP).""" tp = self.typical_price() return (tp * self.volume).cumsum() / self.volume.cumsum() def vwap(self): """Alias for volume_weighted_average_price().""" return self.volume_weighted_average_price() def zigzag(self, percent=7.0): """ Calculate Zigzag. """ x = self.close zigzag = pd.TimeSeries(np.zeros(self.number_of_days), index=x.index) lastzig = x[0] zigzag[0] = x[0] for i in range(1, self.number_of_days): if np.abs((lastzig - x[i]) / x[i]) > percent / 100.0: zigzag[i] = x[i] lastzig = x[i] else: zigzag[i] = None return pd.Series.interpolate(zigzag) # Indicators # -------------------------------------------------------------------------------------------------------------------------- def accumulation_distribution_line(self): """ Calculate Aaccumulation Distribution Line (ADL). """ return self.money_flow_volume().cumsum() def adl(self): """ Alias for accumulation_distribution_line(). """ return self.accumulation_distribution_line() def aroon(self, n=25): """ Calculate aroon. """ high = self.high n_day_high = pd.rolling_max(high, n, 0) highs = high[high == n_day_high] time_since_last_max = (highs.index.values[1:] - highs.index.values[0:-1]).astype('timedelta64[D]').astype(int) day_b4_high = (high == n_day_high).shift(-1).fillna(False) days_since_high = pd.TimeSeries(np.nan + np.ones(len(high)), index=high.index) days_since_high[day_b4_high] = time_since_last_max days_since_high[high == n_day_high] = 0.0 days_since_high = days_since_high.interpolate('time').astype(int).clip_upper(n) low = self.low n_day_low = pd.rolling_min(low, n, 0) lows = low[low == n_day_low] time_since_last_min = (lows.index.values[1:] - lows.index.values[0:-1]).astype('timedelta64[D]').astype(int) day_b4_low = (low == n_day_low).shift(-1).fillna(False) days_since_low = pd.TimeSeries(np.nan + np.ones(len(low)), index=low.index) days_since_low[day_b4_low] = time_since_last_min days_since_low[low == n_day_low] = 0.0 days_since_low = days_since_low.interpolate('time').astype(int).clip_upper(n) aroon_up = 100.0 * ((n - days_since_high) / n) aroon_dn = 100.0 * ((n - days_since_low) / n) aroon_osc = aroon_up - aroon_dn return pd.DataFrame({'up': aroon_up, 'down': aroon_dn, 'oscillator': aroon_osc}) def average_directional_index(self, n=14): """ Calculate Average Directional Index (ADX). """ tr = self.true_range() pdm = pd.TimeSeries(np.zeros(len(tr)), index=tr.index) ndm = pd.TimeSeries(np.zeros(len(tr)), index=tr.index) pdm[(self.high - self.high.shift(1)) > (self.low.shift(1) - self.low)] = (self.high - self.high.shift(1)) ndm[(self.low.shift(1) - self.low) > (self.high - self.high.shift(1))] = (self.low.shift(1) - self.low) trn = ema(tr, n) pdmn = ema(pdm, n) ndmn = ema(ndm, n) pdin = pdmn / trn ndin = ndmn / trn dx = ((pdin - ndin) / (pdin + ndin)).abs() adx = ((n-1) * dx.shift(1) + dx) / n return adx def adx(self, n=14): """ Alias for average_directional_index(). """ return self.average_directional_index(n) def average_true_range(self, n=14): """ Calculate Average True Range. !!!!!this is not a 100% correct - redo!!!!! """ tr = self.true_range() return ((n-1) * tr.shift(1) + tr) / n def atr(self, n=14): """ Alias foraverage_true_range(). !!!!!this is not a 100% correct - redo!!!!! """ return self.average_true_range(n) def bandwidth(self, n=20, k=2): """ Calculate Bandwidth. """ bb = self.bollinger_bands(n, k) return (bb['ub'] - bb['lb']) / bb['mb'] def percent_b(self, n=20, k=2): """ Calculate Percent B. """ bb = self.bollinger_bands(n, k) return (self.close.shift(1) - bb['lb']) / (bb['ub'] - bb['lb']) def commodity_channel_index(self, n=20): """ Calculate Commodity Channel Index (CCI). """ tp = self.typical_price() return (tp - pd.rolling_mean(tp, n)) / (0.015 * pd.rolling_std(tp, n)) def cci(self, n=20): """ Alias for commodity_channel_index(). """ return self.commodity_channel_index(n) def coppock_curve(self, n1=10, n2=14, n3=11): """ Calculate Coppock Curve. !!!!!fix!!!!! """ window = range(n1) return pd.rolling_window(self.roc(n2), window) + self.roc(n3) def chaikin_money_flow(self, n=20): """ Calculate Chaikin Money Flow. """ return pd.rolling_sum((self.money_flow_volume()), n) / pd.rolling_sum(self.volume, n) def cmf(self, n=20): """Alias for chaikin_money_flow().""" return self.chaikin_money_flow(n) def chaikin_oscillator(self, n1=3, n2=10): """ Calculate Chaikin Oscillator. """ return ema(self.adl(), n1) - ema(self.adl(), n2) def price_momentum_oscillator(self, n1=20, n2=35, n3=10): """ Calculate Price Momentum Oscillator (PMO). """ pmo = ema(10 * ema((100 * (self.close / self.close.shift(1))) - 100.0, n2), n1) signal = ema(pmo, n3) return pd.DataFrame({'pmo': pmo, 'signal': signal}) def pmo(self, n1=20, n2=35, n3=10): """ Alias for price_momentum_oscillator(). """ return self.price_momentum_oscillator(n1, n2, n3) def detrended_price_oscillator(self, n=20): """ Calculate Detrended Price Oscillator (DPO). """ return self.close.shift(int(n / 2.0 + 1.0)) - sma(self.close, n) def dpo(self, n=20): """ Alias for detrended_price_oscillator(). """ return self.detrended_price_oscillator(n) def ease_of_movement(self, n=14): """ Calculate Ease Of Movement. """ high_low_avg = (self.high + self.low) / 2.0 distance_moved = high_low_avg - high_low_avg.shift(1) box_ratio = (self.volume / 100000000.0) / (self.high - self.low) emv = distance_moved / box_ratio return sma(emv, n) def force_index(self, n=13): """ Calculate Force Index. """ force_index = self.close - self.close.shift(1) * self.volume return ema(force_index, n) def know_sure_thing(self, n_sig=9): """ Calculate Know Sure Thing. """ rcma1 = sma(self.roc(10), 10) rcma2 = sma(self.roc(15), 10) rcma3 = sma(self.roc(20), 10) rcma4 = sma(self.roc(30), 15) kst = rcma1 + 2.0 * rcma2 + 3.0 * rcma3 + 4.0 * rcma4 kst_signal = sma(kst, n_sig) return pd.DataFrame({'kst': kst, 'signal': kst_signal}) def kst(self, n_sig=9): """ Alias for know_sure_thing(). """ return self.know_sure_thing(n_sig) def mass_index(self, n1=9, n2=25): """ Calculate Mass Index. """ ema1 = ema(self.high_low_spread(), n1) ema2 = ema(ema1, n1) ema_ratio = ema1 / ema2 return pd.rolling_sum(ema_ratio, n2) def moving_avg_converge_diverge(self, sn=26, fn=12, n_sig=9): """ Calculate moving avgerage convergence divergence (MACD). """ macd = ema(self.close, fn) - ema(self.close, sn) macd_signal = ema(macd, n_sig) macd_hist = macd - macd_signal return pd.DataFrame({'macd': macd, 'signal': macd_signal, 'hist': macd_hist}) def macd(self, sn=26, fn=12, n_sig=9): """ Alias for moving_avg_converge_diverge(). """ return self.moving_avg_converge_diverge(sn, fn, n_sig) def money_flow_index(self, n=14): """ Calculate Money Flow Index. """ tp = self.typical_price() rmf = tp * self.volume pmf = rmf.copy() nmf = rmf.copy() pmf[pmf < 0] = 0.0 nmf[nmf > 0] = 0.0 mfr = pd.rolling_sum(pmf, n) / pd.rolling_sum(nmf, n) return 100.0 - (100.0 / (1.0 + mfr)) def negative_volume_index(self, n=255): """ Calculate Negative Volume Index. """ pct_change = self.returns().cumsum() # forward fill when volumes increase with last percent change of a volume decrease day pct_change[self.volume > self.volume.shift(1)] = None pct_change = pct_change.ffill() nvi = 1000.0 + pct_change nvi_signal = ema(nvi, n) return pd.DataFrame({'nvi': nvi, 'signal': nvi_signal}) def nvi(self, n=255): """ Alias for negative_volume_index(). """ return self.negative_volume_index(n) def on_balance_volume(self): """ Calculate On Balance Volume. """ p_obv = self.volume.astype(float) n_obv = (-1.0 * p_obv.copy()) p_obv[self.close < self.close.shift(1)] = 0.0 n_obv[self.close > self.close.shift(1)] = 0.0 p_obv[self.close == self.close.shift(1)] = None n_obv[self.close == self.close.shift(1)] = None obv = p_obv + n_obv return obv.ffill().cumsum() def obv(self): """ Alias for on_balance_volume(). """ return self.on_balance_volume def percentage_price_oscillator(self, n1=12, n2=26, n3=9): """ Calculate Percentage Price Oscillator. """ ppo = 100.0 * (ema(self.close, n1) - ema(self.close, n2)) / ema(self.close, n2) ppo_signal = ema(ppo, n3) ppo_hist = ppo - ppo_signal return pd.DataFrame({'ppo': ppo, 'signal': ppo_signal, 'hist': ppo_hist}) def ppo(self, n1=12, n2=26, n3=9): """ Alias for percentage_price_oscillator(). """ return self.percentage_price_oscillator(n1, n2, n3) def percentage_volume_oscillator(self, n1=12, n2=26, n3=9): """ Calculate Percentage Volume Oscillator. """ pvo = 100.0 * (ema(self.volume, n1) - ema(self.volume, n2)) / ema(self.volume, n2) pvo_signal = ema(pvo, n3) pvo_hist = pvo - pvo_signal return pd.DataFrame({'pvo': pvo, 'signal': pvo_signal, 'hist': pvo_hist}) def pvo(self, n1=12, n2=26, n3=9): """ Alias percentage_volume_oscillator(). """ return self.percentage_volume_oscillator(n1, n2, n3) def relative_strength_index(self, n=14): """ Calculate Relative Strength Index. """ change = self.close - self.close.shift(1) gain = change.copy() loss = change.copy() gain[gain < 0] = 0.0 loss[loss > 0] = 0.0 loss = -1.0 * loss avg_gain = pd.TimeSeries(np.zeros(len(gain)), index=change.index) avg_loss = pd.TimeSeries(np.zeros(len(loss)), index=change.index) avg_gain[n] = gain[0:n].sum() / n avg_loss[n] = loss[0:n].sum() / n for i in range(n+1, len(gain)): avg_gain[i] = (n-1) * (avg_gain[i-1] / n) + (gain[i] / n) avg_loss[i] = (n-1) * (avg_loss[i-1] / n) + (loss[i] / n) rs = avg_gain / avg_loss return 100.0 - (100.0 / (1.0 + rs)) def rsi(self, n=14): """ Alias for relative_strength_index(). """ return self.relative_strength_index(n) def stock_charts_tech_ranks(self, n=None, w=None): """ Calculate Stock Charts Tech Ranks/ """ n = n if n else RANK_DAYS_IN_TRADING_YEAR w = w if w else RANK_PERCENTS close = self.close long_ma = 100.0 * (1 - close / ema(close, n[0])) long_roc = self.roc(n[1]) medium_ma = 100.0 * (1.0 - close / ema(close, n[2])) medium_roc = self.roc(n[3]) ppo = self.ppo() short_ppo_m = 100.0 * ((ppo['hist'] - ppo['hist'].shift(n[4])) / n[4]) / 2.0 short_rsi = self.rsi(n[5]) return w[0] * long_ma + w[1] * long_roc + w[2] * medium_ma + w[3] * medium_roc + w[4] * short_ppo_m + w[5] * short_rsi def sctr(self, n=None, w=None): """ Alias for stock_charts_tech_ranks(). """ return self.stock_charts_tech_ranks(n, w) def slope(self): """ Calculate slope. """ close = self.close return pd.TimeSeries(np.zeros(len(close)), index=close.index) def volatility(self, n=20): """ Calculate volatility. """ return pd.rolling_std(self.close, n) def stochastic_oscillator(self, n=20, n1=3): """ Calculate Stochastic Oscillator. """ n_day_high = pd.rolling_max(self.high, n) n_day_low = pd.rolling_min(self.low, n) percent_k = 100.0 * (self.close - n_day_low) / (n_day_high - n_day_low) percent_d = sma(percent_k, n1) return pd.DataFrame({'k': percent_k, 'd': percent_d}) def stochastic_rsi(self, n=20): """ Calculate Stochastic RSI. """ rsi = self.rsi(n) high_rsi = pd.rolling_max(rsi, n) low_rsi = pd.rolling_min(rsi, n) return (rsi - low_rsi) / (high_rsi - low_rsi) def trix(self, n=15): """ Calculate TRIX. """ ema1 = ema(self.close, n) ema2 = ema(ema1, n) ema3 = ema(ema2, n) return ema3.pct_change() def true_strength_index(self, n1=25, n2=13): """ Calculate True Strength Index. """ pc = self.close - self.close.shift(1) ema1 = ema(pc, n1) ema2 = ema(ema1, n2) abs_pc = (self.close - self.close.shift(1)).abs() abs_ema1 = ema(abs_pc, n1) abs_ema2 = ema(abs_ema1, n2) return 100.0 * ema2 / abs_ema2 def tsi(self, n1=25, n2=13): """ Alias for true_strength_index(). """ return self.true_strength_index(n1, n2) def ulcer_index(self, n=14): """ Calculate Ulcer Index. """ percent_draw_down = 100.0 * (self.close - pd.rolling_max(self.close, n)) / pd.rolling_max(self.close, n) return np.sqrt(pd.rolling_sum(percent_draw_down * percent_draw_down, n) / n) def ultimate_oscillator(self, n1=7, n2=14, n3=28): """ Calculate Ultimate Oscillator. """ bp = self.close - pd.DataFrame([self.low, self.close.shift(1)]).min() hc_max = pd.DataFrame({'a': self.high, 'b': self.close.shift(1)}, index=bp.index).max(1) lc_min = pd.DataFrame({'a': self.low, 'b': self.close.shift(1)}, index=bp.index).min(1) tr = hc_max - lc_min a1 = pd.rolling_sum(bp, n1) / pd.rolling_sum(tr, n1) a2 = pd.rolling_sum(bp, n2) / pd.rolling_sum(tr, n2) a3 = pd.rolling_sum(bp, n3) / pd.rolling_sum(tr, n3) return 100.0 * (4.0 * a1 + 2.0 * a2 + a3) / (4.0 + 2.0 + 1.0) def vortex(self, n=14): """ Calculate Vortex. """ pvm = self.high - self.low.shift(1) nvm = self.low - self.high.shift(1) pvm14 = pd.rolling_sum(pvm, n) nvm14 = pd.rolling_sum(nvm, n) hc_abs = (self.high - self.close.shift(1)).abs() lc_abs = (self.low - self.close.shift(1)).abs() tr = pd.DataFrame({'a': self.high_low_spread(), 'b': hc_abs, 'c': lc_abs}, index=pvm.index).max(1) tr14 = pd.rolling_sum(tr, n) pvi14 = pvm14 / tr14 nvi14 = nvm14 / tr14 return pd.DataFrame({'+': pvi14, '-': nvi14}) def william_percent_r(self, n=14): """ Calculate William Percent R. """ high_max = pd.rolling_max(self.high, n) low_min = pd.rolling_min(self.low, n) return -100.0 * (high_max - self.close) / (high_max - low_min) # Charting # -------------------------------------------------------------------------------------------------------------------------- def gaps(self): """ Calculate gaps. """ o = self.open c = self.close c2o = self.close_to_open_range() gap = pd.TimeSeries(np.zeros(len(c)), index=c.index) gap[o > c.shift()] = c2o gap[o < c.shift()] = c2o return gap def speedlines(self, n=20): """ Calculate Speedlines. """ high = self.high n_day_high = pd.rolling_max(high, n, 0) highs = high[high == n_day_high] time_since_last_max = (highs.index.values[1:] - highs.index.values[0:-1]).astype('timedelta64[D]').astype(int) day_b4_high = (high == n_day_high).shift(-1).fillna(False) days_since_high = pd.TimeSeries(np.nan + np.ones(len(high)), index=high.index) days_since_high[day_b4_high] = time_since_last_max days_since_high[high == n_day_high] = 0.0 days_since_high = days_since_high.interpolate('time').astype(int).clip_upper(n) low = self.low n_day_low = pd.rolling_min(low, n, 0) lows = low[low == n_day_low] time_since_last_min = (lows.index.values[1:] - lows.index.values[0:-1]).astype('timedelta64[D]').astype(int) day_b4_low = (low == n_day_low).shift(-1).fillna(False) days_since_low = pd.TimeSeries(np.nan + np.ones(len(low)), index=low.index) days_since_low[day_b4_low] = time_since_last_min days_since_low[low == n_day_low] = 0.0 days_since_low = days_since_low.interpolate('time').astype(int).clip_upper(n) trend_length = (days_since_high - days_since_low) trend = trend_length days_behind = pd.TimeSeries(np.zeros(len(low)), index=low.index) days_behind[trend > 0] = days_since_low days_behind[trend < 0] = days_since_high p = pd.TimeSeries(np.nan + np.zeros(len(low)), index=low.index) p2_3 = pd.TimeSeries(np.nan + np.zeros(len(low)), index=low.index) p1_3 = pd.TimeSeries(np.nan + np.zeros(len(low)), index=low.index) base = pd.TimeSeries(np.nan + np.zeros(len(low)), index=low.index) p[trend > 0] = n_day_low p[trend < 0] = n_day_high base[trend > 0] = n_day_high base[trend < 0] = n_day_low p2_3[trend > 0] = n_day_high - ((2.0 / 3.0) * (n_day_high - n_day_low)) p2_3[trend < 0] = n_day_low + ((2.0 / 3.0) * (n_day_high - n_day_low)) p1_3[trend > 0] = n_day_high - ((1.0 / 3.0) * (n_day_high - n_day_low)) p1_3[trend < 0] = n_day_low + ((1.0 / 3.0) * (n_day_high - n_day_low)) p = p.ffill() base = base.ffill() p2_3 = p2_3.ffill() p1_3 = p1_3.ffill() p_slope = pd.TimeSeries(np.nan + np.zeros(len(low)), index=low.index) p2_3_slope = pd.TimeSeries(np.nan + np.zeros(len(low)), index=low.index) p1_3_slope = pd.TimeSeries(np.nan + np.zeros(len(low)), index=low.index) p_slope[trend > 0] = ((base - p) / (n + trend_length)) p_slope[trend < 0] = ((base - p) / (n - trend_length)) p2_3_slope[trend > 0] = ((base - p2_3) / (n + trend_length)) p2_3_slope[trend < 0] = ((base - p2_3) / (n - trend_length)) p1_3_slope[trend > 0] = ((base - p1_3) / (n + trend_length)) p1_3_slope[trend < 0] = ((base - p1_3) / (n - trend_length)) p_slope = p_slope.ffill() p2_3_slope = p2_3_slope.ffill() p1_3_slope = p1_3_slope.ffill() p_now = p + (p_slope * days_behind) # p2_3_now = p2_3 + (p2_3_slope * days_behind) # p1_3_now = p1_3 + (p1_3_slope * days_behind) return pd.DataFrame({'p': p_now, 'p2/3': p2_3, 'p1/3': p1_3}) # Return Asset Performance # -------------------------------------------------------------------------------------------------------------------------- def returns(self, periods=1, freq=None): """ Calculate returns of asset over interval period and frequency offset freq string: B business day frequency C custom business day frequency (experimental) D calendar day frequency W weekly frequency M month end frequency BM business month end frequency MS month start frequency BMS business month start frequency Q quarter end frequency BQ business quarter endfrequency QS quarter start frequency BQS business quarter start frequency A year end frequency BA business year end frequency AS year start frequency BAS business year start frequency H hourly frequency T minutely frequency S secondly frequency L milliseonds U microseconds """ return self.close.pct_change(periods=periods, freq=freq) def price_returns(self, periods=1): """ Calculate price change over period. """ return (self.close - self.close.shift(periods)).fillna(0) def arithmetic_return(self, periods=1, freq=None): """ Calculate arithmetic return. """ returns = self.returns(periods=periods, freq=freq).fillna(0) return 100.0 * np.mean(returns) def geometric_return(self, periods=1, freq=None): """ Calculate geometric return. """ returns = self.returns(periods=periods, freq=freq).fillna(0) return 100.0 * (scipy.stats.gmean(1.0 + returns) - 1.0) def rate_of_return(self, periods=DAYS_IN_TRADING_YEAR, freq=None): """ Calculate rate of return over time period freq, default to yearly (DAYS_IN_TRADING_YEAR days). """ returns = self.returns(periods=periods, freq=freq).fillna(0) return returns / periods def price_delta(self, start=None, end=None): """ Calculate returns between dates, defaults to total return. """ end = end if end else -1 start = start if start else 0 return self.close[end] - self.close[start] def total_return(self, start=None, end=None): """ Calculate returns between dates, defaults to total return. """ start = start if start else 0 return 100.0 * self.price_delta(start=start, end=end) / self.close[start] def return_on_investment(self, periods=DAYS_IN_TRADING_YEAR, freq=None): """ Calculate Return on Investment (ROI). """ pass def roi(self, periods=DAYS_IN_TRADING_YEAR, freq=None): """ Alias for return_on_investment(). """ return self.return_on_investment(periods=periods, freq=freq) def compound_annual_growth_rate(self, start=None, end=None): """ Calculate Compound Annual Growth Rate (CAGR). """ end = end if end else -1 start = start if start else 0 enddate = self.close.index[end] startdate = self.close.index[start] years = (enddate - startdate).days / DAYS_IN_YEAR return np.power((self.close[end] / self.close[start]), (1.0 / years)) - 1.0 def cagr(self, start=None, end=None): """ Alias for compound_annual_growth_rate(). """ return self.compound_annual_growth_rate(start=start, end=end) # Risk Performance # -------------------------------------------------------------------------------------------------------------------------- def deviation_risk(self): """ Calculate Deviation Risk. """ return self.returns().std() # Risk Adjusted Performance # -------------------------------------------------------------------------------------------------------------------------- def risk_return_ratio(self): """ Calculate Sharpe Ratio w/o Risk-Free Rate. """ daily_ret = self.returns() return np.sqrt(DAYS_IN_TRADING_YEAR) * daily_ret.mean() / daily_ret.std() def information_ratio(self, benchmark): """ Caluculate the information ratio relative to a benchmark. """ return_delta = self.returns() - benchmark.returns() return return_delta.mean() / return_delta.std() # Market Comparisons # -------------------------------------------------------------------------------------------------------------------------- def sharpe_ratio(self, market): """ Calcualte Sharpe Ratio against benchmark. """ return_delta = self.returns() - market.returns() return return_delta.mean() / return_delta.std() def annualized_sharpe_ratio(self, market, N=DAYS_IN_TRADING_YEAR): """ Calculate Annualized Sharpe Ratio against benchmark. """ return np.sqrt(N) * self.sharpe_ratio(market) def equity_sharpe(self, market, risk_free_rate=RISK_FREE_RATE, N=DAYS_IN_TRADING_YEAR): """ Calculate the Equity sharpe against a benchmark and Risk-Free Rate. """ excess_returns = self.returns() - risk_free_rate / N return_delta = excess_returns - market.returns() return np.sqrt(N) * return_delta.mean() / return_delta.std() def beta(self, market): """ Calcualte the Beta to a benchmark. """ cov = np.cov(self.close.returns(), market.close.returns()) return cov[0, 1] / cov[1, 1] def alpha(self, market, risk_free_rate=RISK_FREE_RATE): """ Calculate the Alpha to a benchmark. """ return self.close.returns().mean() - risk_free_rate - self.beta(market) * (market.close.returns().mean() - risk_free_rate) def r_squared(self, market, risk_free_rate=RISK_FREE_RATE): """ Calculate R-squared. """ eps_i = 0.0 r_i = self.alpha(market) + self.beta(market) * (market.close.returns() - risk_free_rate) + eps_i + risk_free_rate cov = np.cov(self.close.returns(), market.close.returns()) ss_res = np.power(r_i - self.close.returns(), 2.0) ss_tot = cov[0, 0] * (len(self.close.returns()) - 1.0) return 1.0 - (ss_res / ss_tot) # Package it all up...idk, used mostly to test there are no errors # -------------------------------------------------------------------------------------------------------------------------- def all_indicators(self): """ Calculate all indicators for the asset. """ # Indicators that return multiple variables, seperated later quadrant_range = self.quadrant_range() bollinger_bands = self.bollinger_bands() chandelier_exit = self.chandelier_exit() ichimoku_clouds = self.ichimoku_clouds() keltner_channels = self.keltner_channels() moving_average_envelopes = self.moving_average_envelopes() parabolic_sar = self.parabolic_sar() pivot_point = self.pivot_point() fibonacci_pivot_point = self.fibonacci_pivot_point() demark_pivot_point = self.demark_pivot_point() price_channel = self.price_channel() aroon = self.aroon() price_momentum_oscillator = self.price_momentum_oscillator() know_sure_thing = self.know_sure_thing() macd = self.macd() negative_volume_index = self.negative_volume_index() percentage_price_oscillator = self.percentage_price_oscillator() percentage_volume_oscillator = self.percentage_volume_oscillator() stochastic_oscillator = self.stochastic_oscillator() vortex = self.vortex() # Return all indicators return pd.DataFrame({ 'return' : self.returns(), 'money_flow' : self.money_flow(), 'money_flow_volume' : self.money_flow_volume(), 'typical_price' : self.typical_price(), 'close_to_open_range' : self.close_to_open_range(), 'l1_quadrant_range' : quadrant_range['1'], 'l2_quadrant_range' : quadrant_range['2'], 'l3_quadrant_range' : quadrant_range['3'], 'l4_quadrant_range' : quadrant_range['4'], 'l5_quadrant_range' : quadrant_range['5'], 'true_range' : self.true_range(), 'high_low_spread' : self.high_low_spread(), 'roc' : self.rate_of_change(), 'upper_bollinger_band' : bollinger_bands['ub'], 'center_bollinger_band' : bollinger_bands['mb'], 'lower_bollinger_band' : bollinger_bands['lb'], 'long_chandelier_exit' : chandelier_exit['long'], 'short_chandelier_exit' : chandelier_exit['short'], 'conversion_ichimoku_cloud': ichimoku_clouds['conversion'], 'base_line_ichimoku_cloud' : ichimoku_clouds['base'], 'leadingA_ichimoku_cloud' : ichimoku_clouds['leadA'], 'leadingB_ichimoku_cloud' : ichimoku_clouds['leadB'], 'lagging_ichimoku_cloud' : ichimoku_clouds['lag'], 'upper_keltner_channel' : keltner_channels['ul'], 'center_keltner_channel' : keltner_channels['ml'], 'lower_keltner_channel' : keltner_channels['ll'], 'upper_ma_envelope' : moving_average_envelopes['uma'], 'center_ma_envelope' : moving_average_envelopes['ma'], 'lower_ma_envelope' : moving_average_envelopes['lma'], 'rising_parabolic_sar' : parabolic_sar['rising'], 'falling_parabolic_sar' : parabolic_sar['falling'], 'p_pivot_point' : pivot_point['p'], 's1_pivot_point' : pivot_point['s1'], 's2_pivot_point' : pivot_point['s2'], 'r1_pivot_point' : pivot_point['r1'], 'r2_pivot_point' : pivot_point['r2'], 'p_fibonacci_pivot_point' : fibonacci_pivot_point['p'], 's1_fibonacci_pivot_point' : fibonacci_pivot_point['s1'], 's2_fibonacci_pivot_point' : fibonacci_pivot_point['s2'], 's3_fibonacci_pivot_point' : fibonacci_pivot_point['s3'], 'r1_fibonacci_pivot_point' : fibonacci_pivot_point['r1'], 'r2_fibonacci_pivot_point' : fibonacci_pivot_point['r2'], 'r3_fibonacci_pivot_point' : fibonacci_pivot_point['r3'], 'p_demark_pivot_point' : demark_pivot_point['p'], 's1_demark_pivot_point' : demark_pivot_point['s1'], 'r1_demark_pivot_point' : demark_pivot_point['r1'], 'high_price_channel' : price_channel['high'], 'low_price_channel' : price_channel['low'], 'center_price_channel' : price_channel['center'], 'volume_by_price' : self.volume_by_price(), 'vwap' : self.volume_weighted_average_price(), 'zigzag' : self.zigzag(), 'adl' : self.accumulation_distribution_line(), 'aroon_up' : aroon['up'], 'aroon_down' : aroon['down'], 'aroon_oscillator' : aroon['oscillator'], 'adx' : self.average_directional_index(), 'atr' : self.average_true_range(), 'bandwidth' : self.bandwidth(), '%b' : self.percent_b(), 'cci' : self.commodity_channel_index(), 'coppock_curve' : self.coppock_curve(), 'chaikin_money_flow' : self.chaikin_money_flow, 'chaikin_oscillator' : self.chaikin_oscillator(), 'pmo' : price_momentum_oscillator['pmo'], 'pmo_signal' : price_momentum_oscillator['signal'], 'dpo' : self.detrended_price_oscillator(), 'ease_of_movement' : self.ease_of_movement(), 'force_index' : self.force_index(), 'kst' : know_sure_thing['kst'], 'kst_signal' : know_sure_thing['signal'], 'mass_index' : self.mass_index(), 'macd' : macd['macd'], 'macd_signal' : macd['signal'], 'macd_hist' : macd['hist'], 'money_flow_index' : self.money_flow_index(), 'nvi' : negative_volume_index['nvi'], 'nvi_signal' : negative_volume_index['signal'], 'obv' : self.on_balance_volume, 'ppo' : percentage_price_oscillator['ppo'], 'ppo_signal' : percentage_price_oscillator['signal'], 'ppo_hist' : percentage_price_oscillator['hist'], 'pvo' : percentage_volume_oscillator['pvo'], 'pvo_signal' : percentage_volume_oscillator['signal'], 'pvo_hist' : percentage_volume_oscillator['hist'], 'rsi' : self.relative_strength_index(), 'sctr' : self.stock_charts_tech_ranks(), 's' : self.slope(), 'volatility' : self.volatility(), '%k_stochastic_oscillator' : stochastic_oscillator['k'], '%d_stochastic_oscillator' : stochastic_oscillator['d'], 'stochastic_rsi' : self.stochastic_rsi(), 'trix' : self.trix(), 'tsi' : self.true_strength_index(), 'ulcer_index' : self.ulcer_index(), 'ultimate_oscillator' : self.ultimate_oscillator(), '+vortex' : vortex['+'], '-vortex' : vortex['-'], 'william_percent_r' : self.william_percent_r() })
mit
Changaco/oh-mainline
vendor/packages/docutils/docutils/utils/urischemes.py
154
6275
# $Id: urischemes.py 7464 2012-06-25 13:16:03Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ `schemes` is a dictionary with lowercase URI addressing schemes as keys and descriptions as values. It was compiled from the index at http://www.iana.org/assignments/uri-schemes (revised 2005-11-28) and an older list at http://www.w3.org/Addressing/schemes.html. """ # Many values are blank and should be filled in with useful descriptions. schemes = { 'about': 'provides information on Navigator', 'acap': 'Application Configuration Access Protocol; RFC 2244', 'addbook': "To add vCard entries to Communicator's Address Book", 'afp': 'Apple Filing Protocol', 'afs': 'Andrew File System global file names', 'aim': 'AOL Instant Messenger', 'callto': 'for NetMeeting links', 'castanet': 'Castanet Tuner URLs for Netcaster', 'chttp': 'cached HTTP supported by RealPlayer', 'cid': 'content identifier; RFC 2392', 'crid': 'TV-Anytime Content Reference Identifier; RFC 4078', 'data': ('allows inclusion of small data items as "immediate" data; ' 'RFC 2397'), 'dav': 'Distributed Authoring and Versioning Protocol; RFC 2518', 'dict': 'dictionary service protocol; RFC 2229', 'dns': 'Domain Name System resources', 'eid': ('External ID; non-URL data; general escape mechanism to allow ' 'access to information for applications that are too ' 'specialized to justify their own schemes'), 'fax': ('a connection to a terminal that can handle telefaxes ' '(facsimiles); RFC 2806'), 'feed' : 'NetNewsWire feed', 'file': 'Host-specific file names; RFC 1738', 'finger': '', 'freenet': '', 'ftp': 'File Transfer Protocol; RFC 1738', 'go': 'go; RFC 3368', 'gopher': 'The Gopher Protocol', 'gsm-sms': ('Global System for Mobile Communications Short Message ' 'Service'), 'h323': ('video (audiovisual) communication on local area networks; ' 'RFC 3508'), 'h324': ('video and audio communications over low bitrate connections ' 'such as POTS modem connections'), 'hdl': 'CNRI handle system', 'hnews': 'an HTTP-tunneling variant of the NNTP news protocol', 'http': 'Hypertext Transfer Protocol; RFC 2616', 'https': 'HTTP over SSL; RFC 2818', 'hydra': 'SubEthaEdit URI. See http://www.codingmonkeys.de/subethaedit.', 'iioploc': 'Internet Inter-ORB Protocol Location?', 'ilu': 'Inter-Language Unification', 'im': 'Instant Messaging; RFC 3860', 'imap': 'Internet Message Access Protocol; RFC 2192', 'info': 'Information Assets with Identifiers in Public Namespaces', 'ior': 'CORBA interoperable object reference', 'ipp': 'Internet Printing Protocol; RFC 3510', 'irc': 'Internet Relay Chat', 'iris.beep': 'iris.beep; RFC 3983', 'iseek' : 'See www.ambrosiasw.com; a little util for OS X.', 'jar': 'Java archive', 'javascript': ('JavaScript code; evaluates the expression after the ' 'colon'), 'jdbc': 'JDBC connection URI.', 'ldap': 'Lightweight Directory Access Protocol', 'lifn': '', 'livescript': '', 'lrq': '', 'mailbox': 'Mail folder access', 'mailserver': 'Access to data available from mail servers', 'mailto': 'Electronic mail address; RFC 2368', 'md5': '', 'mid': 'message identifier; RFC 2392', 'mocha': '', 'modem': ('a connection to a terminal that can handle incoming data ' 'calls; RFC 2806'), 'mtqp': 'Message Tracking Query Protocol; RFC 3887', 'mupdate': 'Mailbox Update (MUPDATE) Protocol; RFC 3656', 'news': 'USENET news; RFC 1738', 'nfs': 'Network File System protocol; RFC 2224', 'nntp': 'USENET news using NNTP access; RFC 1738', 'opaquelocktoken': 'RFC 2518', 'phone': '', 'pop': 'Post Office Protocol; RFC 2384', 'pop3': 'Post Office Protocol v3', 'pres': 'Presence; RFC 3859', 'printer': '', 'prospero': 'Prospero Directory Service; RFC 4157', 'rdar' : ('URLs found in Darwin source ' '(http://www.opensource.apple.com/darwinsource/).'), 'res': '', 'rtsp': 'real time streaming protocol; RFC 2326', 'rvp': '', 'rwhois': '', 'rx': 'Remote Execution', 'sdp': '', 'service': 'service location; RFC 2609', 'shttp': 'secure hypertext transfer protocol', 'sip': 'Session Initiation Protocol; RFC 3261', 'sips': 'secure session intitiaion protocol; RFC 3261', 'smb': 'SAMBA filesystems.', 'snews': 'For NNTP postings via SSL', 'snmp': 'Simple Network Management Protocol; RFC 4088', 'soap.beep': 'RFC 3288', 'soap.beeps': 'RFC 3288', 'ssh': 'Reference to interactive sessions via ssh.', 't120': 'real time data conferencing (audiographics)', 'tag': 'RFC 4151', 'tcp': '', 'tel': ('a connection to a terminal that handles normal voice ' 'telephone calls, a voice mailbox or another voice messaging ' 'system or a service that can be operated using DTMF tones; ' 'RFC 2806.'), 'telephone': 'telephone', 'telnet': 'Reference to interactive sessions; RFC 4248', 'tftp': 'Trivial File Transfer Protocol; RFC 3617', 'tip': 'Transaction Internet Protocol; RFC 2371', 'tn3270': 'Interactive 3270 emulation sessions', 'tv': '', 'urn': 'Uniform Resource Name; RFC 2141', 'uuid': '', 'vemmi': 'versatile multimedia interface; RFC 2122', 'videotex': '', 'view-source': 'displays HTML code that was generated with JavaScript', 'wais': 'Wide Area Information Servers; RFC 4156', 'whodp': '', 'whois++': 'Distributed directory service.', 'x-man-page': ('Opens man page in Terminal.app on OS X ' '(see macosxhints.com)'), 'xmlrpc.beep': 'RFC 3529', 'xmlrpc.beeps': 'RFC 3529', 'z39.50r': 'Z39.50 Retrieval; RFC 2056', 'z39.50s': 'Z39.50 Session; RFC 2056',}
agpl-3.0
rafaduran/python-mcollective
tests/unit/test_message.py
2
5495
'''Tests for messaging objects.''' import pytest from pymco import exc from pymco import message from pymco.test import ctxt @pytest.fixture def msg_no_filter(config): '''Creates a new :py:class:`pymco.message.Message` instance.''' return message.Message(body=ctxt.MSG['body'], agent=ctxt.MSG['agent'], config=config) def test_filter_add_cfclass(filter_): '''Tests :py:method:`pymco.message.Filter.add_class`.''' assert filter_['cf_class'] == [] filter_.add_cfclass('common::linux') assert filter_['cf_class'] == ['common::linux'] filter_.add_cfclass('apache') assert filter_['cf_class'] == ['common::linux', 'apache'] def test_filter_add_agent(filter_): '''Tests :py:method:`pymco.message.Filter.add_agent`.''' assert filter_['agent'] == [] filter_.add_agent('package') assert filter_['agent'] == ['package'] filter_.add_agent('registration') assert filter_['agent'] == ['package', 'registration'] def test_filter_add_fact(filter_): '''Tests :py:method:`pymco.message.Filter.add_fact` happy path.''' assert filter_['fact'] == [] filter_.add_fact(fact='country', value='/uk/') assert filter_['fact'] == [{':fact': "country", ':value': "/uk/"}] filter_.add_fact(fact='country', value='/uk/', operator='==') assert filter_['fact'] == [ {':fact': "country", ':value': "/uk/"}, {':fact': "country", ':value': "/uk/", ':operator': '=='}, ] def test_filter_add_fact_operators(filter_): '''Tests :py:method:`pymco.message.Filter.add_fact` accepts only MCollective supported operators.''' for operator in ('==', '<=', '>=', '>', '<', '!='): filter_.add_fact(fact='country', value='/uk/', operator=operator) with pytest.raises(exc.BadFilterFactOperator): filter_.add_fact(fact='country', value='/uk/', operator='bad') def test_filter_add_identity(filter_): '''Tests :py:method:`pymco.message.Filter.add_identity`.''' assert filter_['identity'] == [] filter_.add_identity('foo.bar.com') assert filter_['identity'] == ['foo.bar.com'] filter_.add_identity('spam.bar.com') assert filter_['identity'] == ['foo.bar.com', 'spam.bar.com'] def test_filter_method_chaining(filter_): '''Tests :py:class:`pymco.message.Filter` method chaining.''' assert dict(filter_) == {'cf_class': [], 'agent': [], 'fact': [], 'identity': [], 'compound': [], } filter_.add_agent('package').add_identity('foo.bar.com') assert dict(filter_) == {'cf_class': [], 'agent': ['package'], 'fact': [], 'identity': ['foo.bar.com'], 'compound': [], } def test_filter_length(filter_): '''Tests :py:meth:`pymco.message.Filter.__len__`.''' assert len(filter_) == 5 # cf_class, agent, fact, identity, compound filter_.add_agent('package') assert len(filter_) == 5 def test_message(msg, filter_): '''Tests :py:class:`pymco.message.Message` attribues.''' for name, value in ((':senderid', 'mco1'), (':msgtime', int(ctxt.MSG['msgtime'])), (':ttl', 60), (':requestid', ctxt.MSG['requestid']), (':body', ctxt.MSG['body']), (':agent', ctxt.MSG['agent']), (':collective', 'mcollective'), (':filter', dict(filter_)), ): assert msg[name] == value def test_message_length(msg): '''Tests :py:method:`pymco.message.Message.length`.''' assert len(msg) == len(msg._message) def test_message_iteration(msg): '''Tests :py:method:`pymco.message.Message.__iter__`.''' assert sorted(list(msg)) == sorted(list(msg._message.keys())) def test_message_raises_improperly_configured(config, filter_): '''Tests :py:class:`pymco.message.Message` raises :py:exc:`pymco.exc.ImproperlyConfigured` if configuration doesn't contain all required information.''' with pytest.raises(exc.ImproperlyConfigured): message.Message(body='ping', agent='discovery', config={}, filter_=dict(filter_)) def test_message_set_item(msg): '''Tests :py:meth:`pymco.message.Message.__setitem__`.''' msg[':test'] = 123 assert msg[':test'] == 123 def test_message_del_item(msg): '''Tests :py:meth:`pymco.message.Message.__delitem__`.''' msg[':test'] = 123 assert msg[':test'] == 123 del msg[':test'] with pytest.raises(KeyError): msg[':test'] def test_message_filter_update(msg): '''Tests :py:meth:`pymco.message.Message.__setitem__` maintains filter as a dict-like object.''' filter_ = message.Filter() msg[':filter'] = filter_ assert msg[':filter'] == dict(filter_) assert isinstance(msg[':filter'], dict) def test_message_no_filter(msg_no_filter): '''Tests :py:class:`pymco.message.Message` with no filter.''' assert dict(msg_no_filter[':filter']) == dict(message.Filter()) def test_msg_update_no_symbol(msg): """Test update msg with a non symbol raises ValueError""" with pytest.raises(ValueError): msg['foo'] = 'foo'
bsd-3-clause
bmanojlovic/ansible
lib/ansible/modules/network/nxos/nxos_nxapi.py
20
11050
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'core', 'version': '1.0'} DOCUMENTATION = """ --- module: nxos_nxapi version_added: "2.1" author: "Peter Sprygada (@privateip)" short_description: Manage NXAPI configuration on an NXOS device. description: - Configures the NXAPI feature on devices running Cisco NXOS. The NXAPI feature is absent from the configuration by default. Since this module manages the NXAPI feature it only supports the use of the C(Cli) transport. extends_documentation_fragment: nxos options: http_port: description: - Configure the port with which the HTTP server will listen on for requests. By default, NXAPI will bind the HTTP service to the standard HTTP port 80. This argument accepts valid port values in the range of 1 to 65535. required: false default: 80 http: description: - Controls the operating state of the HTTP protocol as one of the underlying transports for NXAPI. By default, NXAPI will enable the HTTP transport when the feature is first configured. To disable the use of the HTTP transport, set the value of this argument to False. required: false default: yes choices: ['yes', 'no'] aliases: ['enable_http'] https_port: description: - Configure the port with which the HTTPS server will listen on for requests. By default, NXAPI will bind the HTTPS service to the standard HTTPS port 443. This argument accepts valid port values in the range of 1 to 65535. required: false default: 443 https: description: - Controls the operating state of the HTTPS protocol as one of the underlying transports for NXAPI. By default, NXAPI will disable the HTTPS transport when the feature is first configured. To enable the use of the HTTPS transport, set the value of this argument to True. required: false default: no choices: ['yes', 'no'] aliases: ['enable_https'] sandbox: description: - The NXAPI feature provides a web base UI for developers for entering commands. This feature is initially disabled when the NXAPI feature is configured for the first time. When the C(sandbox) argument is set to True, the developer sandbox URL will accept requests and when the value is set to False, the sandbox URL is unavailable. required: false default: no choices: ['yes', 'no'] aliases: ['enable_sandbox'] config: description: - The C(config) argument provides an optional argument to specify the device running-config to used as the basis for configuring the remote system. The C(config) argument accepts a string value that represents the device configuration. required: false default: null version_added: "2.2" state: description: - The C(state) argument controls whether or not the NXAPI feature is configured on the remote device. When the value is C(present) the NXAPI feature configuration is present in the device running-config. When the values is C(absent) the feature configuration is removed from the running-config. choices: ['present', 'absent'] required: false default: present """ EXAMPLES = """ # Note: examples below use the following provider dict to handle # transport and authentication to the node. vars: cli: host: "{{ inventory_hostname }}" username: admin password: admin - name: Enable NXAPI access with default configuration nxos_nxapi: provider: "{{ cli }}" - name: Enable NXAPI with no HTTP, HTTPS at port 9443 and sandbox disabled nxos_nxapi: enable_http: false https_port: 9443 https: yes enable_sandbox: no provider: "{{ cli }}" - name: remove NXAPI configuration nxos_nxapi: state: absent provider: "{{ cli }}" """ RETURN = """ updates: description: - Returns the list of commands that need to be pushed into the remote device to satisfy the arguments returned: always type: list sample: ['no feature nxapi'] """ import re import time from ansible.module_utils.netcfg import NetworkConfig, dumps from ansible.module_utils.nxos import NetworkModule, NetworkError from ansible.module_utils.basic import get_exception PRIVATE_KEYS_RE = re.compile('__.+__') def invoke(name, *args, **kwargs): func = globals().get(name) if func: return func(*args, **kwargs) def get_instance(module): instance = dict(state='absent') try: resp = module.cli('show nxapi', 'json') except NetworkError: return instance instance['state'] = 'present' instance['http'] = 'http_port' in resp[0] instance['http_port'] = resp[0].get('http_port') or 80 instance['https'] = 'https_port' in resp[0] instance['https_port'] = resp[0].get('https_port') or 443 instance['sandbox'] = resp[0]['sandbox_status'] return instance def present(module, instance, commands): commands.append('feature nxapi') setters = set() for key, value in module.argument_spec.items(): setter = value.get('setter') or 'set_%s' % key if setter not in setters: setters.add(setter) if module.params[key] is not None: invoke(setter, module, instance, commands) def absent(module, instance, commands): if instance['state'] != 'absent': commands.append('no feature nxapi') def set_http(module, instance, commands): port = module.params['http_port'] if not 0 <= port <= 65535: module.fail_json(msg='http_port must be between 1 and 65535') elif module.params['http'] is True: commands.append('nxapi http port %s' % port) elif module.params['http'] is False: commands.append('no nxapi http') def set_https(module, instance, commands): port = module.params['https_port'] if not 0 <= port <= 65535: module.fail_json(msg='https_port must be between 1 and 65535') elif module.params['https'] is True: commands.append('nxapi https port %s' % port) elif module.params['https'] is False: commands.append('no nxapi https') def set_sandbox(module, instance, commands): if module.params['sandbox'] is True: commands.append('nxapi sandbox') elif module.params['sandbox'] is False: commands.append('no nxapi sandbox') def get_config(module): contents = module.params['config'] if not contents: try: contents = module.cli(['show running-config nxapi all'])[0] except NetworkError: contents = None config = NetworkConfig(indent=2) if contents: config.load(contents) return config def load_checkpoint(module, result): try: checkpoint = result['__checkpoint__'] module.cli(['rollback running-config checkpoint %s' % checkpoint, 'no checkpoint %s' % checkpoint], output='text') except KeyError: module.fail_json(msg='unable to rollback, checkpoint not found') except NetworkError: exc = get_exception() msg = 'unable to rollback configuration' module.fail_json(msg=msg, checkpoint=checkpoint, **exc.kwargs) def load_config(module, commands, result): # create a config checkpoint checkpoint = 'ansible_%s' % int(time.time()) module.cli(['checkpoint %s' % checkpoint], output='text') result['__checkpoint__'] = checkpoint # load the config into the device module.config.load_config(commands) # load was successfully, remove the config checkpoint module.cli(['no checkpoint %s' % checkpoint]) def load(module, commands, result): candidate = NetworkConfig(indent=2, contents='\n'.join(commands)) config = get_config(module) configobjs = candidate.difference(config) if configobjs: commands = dumps(configobjs, 'commands').split('\n') result['updates'] = commands if not module.check_mode: load_config(module, commands, result) result['changed'] = True def clean_result(result): # strip out any keys that have two leading and two trailing # underscore characters for key in result.keys(): if PRIVATE_KEYS_RE.match(key): del result[key] def main(): """ main entry point for module execution """ argument_spec = dict( http=dict(aliases=['enable_http'], default=True, type='bool', setter='set_http'), http_port=dict(default=80, type='int', setter='set_http'), https=dict(aliases=['enable_https'], default=False, type='bool', setter='set_https'), https_port=dict(default=443, type='int', setter='set_https'), sandbox=dict(aliases=['enable_sandbox'], default=False, type='bool'), # Only allow configuration of NXAPI using cli transport transport=dict(required=True, choices=['cli']), config=dict(), # Support for started and stopped is for backwards capability only and # will be removed in a future version state=dict(default='present', choices=['started', 'stopped', 'present', 'absent']) ) module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, supports_check_mode=True) state = module.params['state'] warnings = list() result = dict(changed=False, warnings=warnings) if state == 'started': state = 'present' warnings.append('state=started is deprecated and will be removed in a ' 'a future release. Please use state=present instead') elif state == 'stopped': state = 'absent' warnings.append('state=stopped is deprecated and will be removed in a ' 'a future release. Please use state=absent instead') commands = list() instance = get_instance(module) invoke(state, module, instance, commands) try: load(module, commands, result) except (ValueError, NetworkError): load_checkpoint(module, result) exc = get_exception() module.fail_json(msg=str(exc), **exc.kwargs) clean_result(result) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
mwiencek/picard
picard/acoustidmanager.py
1
3290
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2011 Lukáš Lalinský # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from PyQt4 import QtCore from picard.util import partial class Submission(object): def __init__(self, fingerprint, duration, orig_trackid=None, trackid=None, puid=None): self.fingerprint = fingerprint self.duration = duration self.puid = puid self.orig_trackid = orig_trackid self.trackid = trackid class AcoustIDManager(QtCore.QObject): def __init__(self): QtCore.QObject.__init__(self) self._fingerprints = {} def add(self, file, trackid): if not hasattr(file, 'acoustid_fingerprint'): return if not hasattr(file, 'acoustid_length'): return puid = file.metadata['musicip_puid'] self._fingerprints[file] = Submission(file.acoustid_fingerprint, file.acoustid_length, trackid, trackid, puid) self._check_unsubmitted() def update(self, file, trackid): submission = self._fingerprints.get(file) if submission is None: return submission.trackid = trackid self._check_unsubmitted() def remove(self, file): if file in self._fingerprints: del self._fingerprints[file] self._check_unsubmitted() def _unsubmitted(self): for submission in self._fingerprints.itervalues(): if submission.trackid and submission.orig_trackid != submission.trackid: yield submission def _check_unsubmitted(self): enabled = False for submission in self._unsubmitted(): enabled = True break self.tagger.window.enable_submit(enabled) def submit(self): fingerprints = list(self._unsubmitted()) if not fingerprints: self._check_unsubmitted() return self.tagger.window.set_statusbar_message(N_('Submitting AcoustIDs...')) self.tagger.xmlws.submit_acoustid_fingerprints(fingerprints, partial(self.__fingerprint_submission_finished, fingerprints)) def __fingerprint_submission_finished(self, fingerprints, document, http, error): if error: self.tagger.window.set_statusbar_message(N_('AcoustID submission failed: %s'), error, timeout=3000) else: self.tagger.window.set_statusbar_message(N_('AcoustIDs successfully submitted!'), timeout=3000) for submission in fingerprints: submission.orig_trackid = submission.trackid self._check_unsubmitted()
gpl-2.0
Fiona/Diagonex
src/mrf/structs.py
1
7467
""" Copyright (c) 2009 Mark Frimston 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. --------------- Data Structures Module Contains data structures: TicketQueue - queue for restricting actions to x per frame IntrospectType - metaclass which invokes setup method on classes created """ import copy class TicketQueue(object): """ Queue for restricting actions to x per game cycle """ def __init__(self, max_sim=1): self.max_sim = max_sim self.queue = [set([])] self.next_ticket = 0 def enter(self): t = self.next_ticket self.next_ticket += 1 if len(self.queue[-1]) >= self.max_sim: self.queue.append(set([])) self.queue[-1].add(t) return t def at_front(self, ticket): return ticket in self.queue[0] def advance(self): self.queue.pop(0) if len(self.queue)==0: self.queue.append(set([])) def isiterable(item): try: iter(item) return True except TypeError: return False def iscollection(item): if isinstance(item,basestring): return False return isiterable(item) def isindexable(item): try: item[0] return True except TypeError: return False except IndexError: return True class IntrospectType(type): """ Metaclass allowing introspection of class definition on creation """ def __new__(typ, *args, **kargs): cls = type.__new__(typ, *args, **kargs) cls._class_init() return cls class TagLookup(object): """ Collection allowing groups of items to be associated with multiple different keys and looked up using them. """ def __init__(self): self.clear() def has_item(self, item): return self.items.has_key(item) def has_tag(self, tag): return self.groups.has_key(tag) def add_item(self, item): if self.has_item(item): self.remove_item(item) self.items[item] = set() def remove_item(self, item): if self.has_item(item): for tag in self.get_item_tags(item): self.untag_item(item, tag) del(self.items[item]) def tag_item(self, item, tag): if not self.has_item(item): self.add_item(item) if not self.has_tag(tag): self.add_tag(tag) self.items[item].add(tag) self.groups[tag].add(item) def untag_item(self, item, tag): if self.has_item(item) and self.has_tag(tag): self.items[item].remove(tag) self.groups[tag].remove(item) def add_tag(self, tag): if self.has_tag(tag): self.remove_tag(tag) self.groups[tag] = set() def remove_tag(self, tag): if self.has_tag(tag): for item in self.get_tag_items(tag): self.untag_item(item, tag) del(self.groups[tag]) def get_items(self): return set(self.items.keys()) def get_tags(self): return set(self.groups.keys()) def get_item_tags(self, item): if self.has_item(item): return copy.copy(self.items[item]) else: return set() def get_tag_items(self, tag): if self.has_tag(tag): return copy.copy(self.groups[tag]) else: return set() def clear(self): self.items = {} self.groups = {} def __getitem__(self, key): # index can be used to retrieve tag groups return self.get_tag_items(key) def __contains__(self, key): # "in" operator can be used to test if item is present return self.has_item(key) # -- Testing ----------------------------- if __name__ == "__main__": import unittest class TestTicketQueue(unittest.TestCase): def testTicketQueue(self): q = TicketQueue(2) t1 = q.enter() t2 = q.enter() t3 = q.enter() self.assertTrue(q.at_front(t1)) self.assertTrue(q.at_front(t2)) self.assertFalse(q.at_front(t3)) q.advance() self.assertTrue(q.at_front(t3)) t4 = q.enter() t5 = q.enter() self.assertTrue(q.at_front(t4)) self.assertFalse(q.at_front(t5)) q.advance() self.assertTrue(q.at_front(t5)) q.advance() q.advance() self.assertEquals(1,len(q.queue)) class TestTagLookup(unittest.TestCase): def testAddRemoveItem(self): t = TagLookup() t.remove_item("foo") t.add_item("foo") t.add_item("goo") self.assertEquals(True,t.has_item("foo")) self.assertEquals(False,t.has_item("hoo")) self.assertEquals(set(["foo","goo"]),t.get_items()) t.remove_item("foo") self.assertEquals(set(["goo"]),t.get_items()) t.remove_item("goo") self.assertEquals(set(),t.get_items()) def testAddRemoveTag(self): t = TagLookup() t.remove_tag("bar") t.add_tag("bar") t.add_tag("car") self.assertEquals(True,t.has_tag("bar")) self.assertEquals(False,t.has_tag("dar")) self.assertEquals(set(["bar","car"]),t.get_tags()) t.remove_tag("bar") self.assertEquals(set(["car"]),t.get_tags()) t.remove_tag("car") self.assertEquals(set(),t.get_tags()) def testTaggingUntagging(self): t = TagLookup() t.tag_item("foo", "bar") t.tag_item("goo", "car") t.tag_item("foo", "car") self.assertEquals(set(["foo","goo"]),t.get_items()) self.assertEquals(set(["bar","car"]),t.get_tags()) self.assertEquals(set(["bar","car"]),t.get_item_tags("foo")) self.assertEquals(set(["car"]),t.get_item_tags("goo")) self.assertEquals(set(),t.get_item_tags("hoo")) self.assertEquals(set(["foo"]),t.get_tag_items("bar")) self.assertEquals(set(["foo","goo"]),t.get_tag_items("car")) self.assertEquals(set(),t.get_tag_items("dar")) t.untag_item("hoo","dar") t.untag_item("foo","bar") self.assertEquals(set(["car"]),t.get_item_tags("foo")) self.assertEquals(set(),t.get_tag_items("bar")) def testRemoveTagsAndItems(self): t = TagLookup() t.tag_item("foo", "bar") t.tag_item("foo", "car") t.tag_item("foo", "dar") self.assertEquals(set(["foo"]),t.get_items()) self.assertEquals(set(["bar","car","dar"]),t.get_tags()) t.remove_tag("car") self.assertEquals(set(["bar","dar"]),t.get_tags()) t.remove_item("foo") self.assertEquals(set([]),t.get_items()) self.assertEquals(set(["bar","dar"]),t.get_tags()) def testClear(self): t = TagLookup() t.tag_item("foo", "bar") t.tag_item("foo", "car") t.tag_item("goo", "car") self.assertEquals(2, len(t.get_items())) self.assertEquals(2, len(t.get_tags())) t.clear() self.assertEquals(set(),t.get_items()) self.assertEquals(set(),t.get_tags()) def testSpecialMethods(self): t = TagLookup() t.tag_item("foo", "bar") t.tag_item("foo", "car") t.tag_item("goo", "car") self.assertEquals(set(["foo","goo"]),t["car"]) self.assertEquals(set(),t["dar"]) self.assertEquals(True, "foo" in t) self.assertEquals(False, "hoo" in t) unittest.main()
mit
musicrighter/CIS422-P2
env/lib/python3.4/site-packages/pip/_vendor/colorama/ansitowin32.py
84
9545
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import re import sys import os from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style from .winterm import WinTerm, WinColor, WinStyle from .win32 import windll, winapi_test winterm = None if windll is not None: winterm = WinTerm() def is_a_tty(stream): return hasattr(stream, 'isatty') and stream.isatty() class StreamWrapper(object): ''' Wraps a stream (such as stdout), acting as a transparent proxy for all attribute access apart from method 'write()', which is delegated to our Converter instance. ''' def __init__(self, wrapped, converter): # double-underscore everything to prevent clashes with names of # attributes on the wrapped stream object. self.__wrapped = wrapped self.__convertor = converter def __getattr__(self, name): return getattr(self.__wrapped, name) def write(self, text): self.__convertor.write(text) class AnsiToWin32(object): ''' Implements a 'write()' method which, on Windows, will strip ANSI character sequences from the text, and if outputting to a tty, will convert them into win32 function calls. ''' ANSI_CSI_RE = re.compile('\001?\033\[((?:\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer ANSI_OSC_RE = re.compile('\001?\033\]((?:.|;)*?)(\x07)\002?') # Operating System Command def __init__(self, wrapped, convert=None, strip=None, autoreset=False): # The wrapped stream (normally sys.stdout or sys.stderr) self.wrapped = wrapped # should we reset colors to defaults after every .write() self.autoreset = autoreset # create the proxy wrapping our output stream self.stream = StreamWrapper(wrapped, self) on_windows = os.name == 'nt' # We test if the WinAPI works, because even if we are on Windows # we may be using a terminal that doesn't support the WinAPI # (e.g. Cygwin Terminal). In this case it's up to the terminal # to support the ANSI codes. conversion_supported = on_windows and winapi_test() # should we strip ANSI sequences from our output? if strip is None: strip = conversion_supported or (not wrapped.closed and not is_a_tty(wrapped)) self.strip = strip # should we should convert ANSI sequences into win32 calls? if convert is None: convert = conversion_supported and not wrapped.closed and is_a_tty(wrapped) self.convert = convert # dict of ansi codes to win32 functions and parameters self.win32_calls = self.get_win32_calls() # are we wrapping stderr? self.on_stderr = self.wrapped is sys.stderr def should_wrap(self): ''' True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init() ''' return self.convert or self.strip or self.autoreset def get_win32_calls(self): if self.convert and winterm: return { AnsiStyle.RESET_ALL: (winterm.reset_all, ), AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT), AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL), AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL), AnsiFore.BLACK: (winterm.fore, WinColor.BLACK), AnsiFore.RED: (winterm.fore, WinColor.RED), AnsiFore.GREEN: (winterm.fore, WinColor.GREEN), AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW), AnsiFore.BLUE: (winterm.fore, WinColor.BLUE), AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA), AnsiFore.CYAN: (winterm.fore, WinColor.CYAN), AnsiFore.WHITE: (winterm.fore, WinColor.GREY), AnsiFore.RESET: (winterm.fore, ), AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True), AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True), AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True), AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True), AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True), AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True), AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True), AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True), AnsiBack.BLACK: (winterm.back, WinColor.BLACK), AnsiBack.RED: (winterm.back, WinColor.RED), AnsiBack.GREEN: (winterm.back, WinColor.GREEN), AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW), AnsiBack.BLUE: (winterm.back, WinColor.BLUE), AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA), AnsiBack.CYAN: (winterm.back, WinColor.CYAN), AnsiBack.WHITE: (winterm.back, WinColor.GREY), AnsiBack.RESET: (winterm.back, ), AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True), AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True), AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True), AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True), AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True), AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True), AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True), AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True), } return dict() def write(self, text): if self.strip or self.convert: self.write_and_convert(text) else: self.wrapped.write(text) self.wrapped.flush() if self.autoreset: self.reset_all() def reset_all(self): if self.convert: self.call_win32('m', (0,)) elif not self.strip and not self.wrapped.closed: self.wrapped.write(Style.RESET_ALL) def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 text = self.convert_osc(text) for match in self.ANSI_CSI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text)) def write_plain_text(self, text, start, end): if start < end: self.wrapped.write(text[start:end]) self.wrapped.flush() def convert_ansi(self, paramstring, command): if self.convert: params = self.extract_params(command, paramstring) self.call_win32(command, params) def extract_params(self, command, paramstring): if command in 'Hf': params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';')) while len(params) < 2: # defaults: params = params + (1,) else: params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0) if len(params) == 0: # defaults: if command in 'JKm': params = (0,) elif command in 'ABCD': params = (1,) return params def call_win32(self, command, params): if command == 'm': for param in params: if param in self.win32_calls: func_args = self.win32_calls[param] func = func_args[0] args = func_args[1:] kwargs = dict(on_stderr=self.on_stderr) func(*args, **kwargs) elif command in 'J': winterm.erase_screen(params[0], on_stderr=self.on_stderr) elif command in 'K': winterm.erase_line(params[0], on_stderr=self.on_stderr) elif command in 'Hf': # cursor position - absolute winterm.set_cursor_position(params, on_stderr=self.on_stderr) elif command in 'ABCD': # cursor position - relative n = params[0] # A - up, B - down, C - forward, D - back x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command] winterm.cursor_adjust(x, y, on_stderr=self.on_stderr) def convert_osc(self, text): for match in self.ANSI_OSC_RE.finditer(text): start, end = match.span() text = text[:start] + text[end:] paramstring, command = match.groups() if command in '\x07': # \x07 = BEL params = paramstring.split(";") # 0 - change title and icon (we will only change title) # 1 - change icon (we don't support this) # 2 - change title if params[0] in '02': winterm.set_title(params[1]) return text
artistic-2.0
firerszd/kbengine
kbe/res/scripts/common/Lib/glob.py
86
3461
"""Filename globbing utility.""" import os import re import fnmatch __all__ = ["glob", "iglob"] def glob(pathname): """Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. """ return list(iglob(pathname)) def iglob(pathname): """Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. """ dirname, basename = os.path.split(pathname) if not has_magic(pathname): if basename: if os.path.lexists(pathname): yield pathname else: # Patterns ending with a slash should match only directories if os.path.isdir(dirname): yield pathname return if not dirname: yield from glob1(None, basename) return # `os.path.split()` returns the argument itself as a dirname if it is a # drive or UNC path. Prevent an infinite recursion if a drive or UNC path # contains magic characters (i.e. r'\\?\C:'). if dirname != pathname and has_magic(dirname): dirs = iglob(dirname) else: dirs = [dirname] if has_magic(basename): glob_in_dir = glob1 else: glob_in_dir = glob0 for dirname in dirs: for name in glob_in_dir(dirname, basename): yield os.path.join(dirname, name) # These 2 helper functions non-recursively glob inside a literal directory. # They return a list of basenames. `glob1` accepts a pattern while `glob0` # takes a literal basename (so it only has to check for its existence). def glob1(dirname, pattern): if not dirname: if isinstance(pattern, bytes): dirname = bytes(os.curdir, 'ASCII') else: dirname = os.curdir try: names = os.listdir(dirname) except OSError: return [] if not _ishidden(pattern): names = [x for x in names if not _ishidden(x)] return fnmatch.filter(names, pattern) def glob0(dirname, basename): if not basename: # `os.path.split()` returns an empty basename for paths ending with a # directory separator. 'q*x/' should match only directories. if os.path.isdir(dirname): return [basename] else: if os.path.lexists(os.path.join(dirname, basename)): return [basename] return [] magic_check = re.compile('([*?[])') magic_check_bytes = re.compile(b'([*?[])') def has_magic(s): if isinstance(s, bytes): match = magic_check_bytes.search(s) else: match = magic_check.search(s) return match is not None def _ishidden(path): return path[0] in ('.', b'.'[0]) def escape(pathname): """Escape all special characters. """ # Escaping is done by wrapping any of "*?[" between square brackets. # Metacharacters do not work in the drive part and shouldn't be escaped. drive, pathname = os.path.splitdrive(pathname) if isinstance(pathname, bytes): pathname = magic_check_bytes.sub(br'[\1]', pathname) else: pathname = magic_check.sub(r'[\1]', pathname) return drive + pathname
lgpl-3.0
jonathanschmitz/car-price-modelling
car_scraper/car_scraper/settings.py
1
3176
# -*- coding: utf-8 -*- # Scrapy settings for car_scraper project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'car_scraper' SPIDER_MODULES = ['car_scraper.spiders'] NEWSPIDER_MODULE = 'car_scraper.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'car_scraper (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'car_scraper.middlewares.CarScraperSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'car_scraper.middlewares.MyCustomDownloaderMiddleware': 543, #} # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'car_scraper.pipelines.CarScraperPipeline': 300, #} # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
mit
1013553207/django
tests/view_tests/tests/test_i18n.py
188
13917
# -*- coding:utf-8 -*- from __future__ import unicode_literals import gettext import json import os import unittest from os import path from django.conf import settings from django.core.urlresolvers import reverse from django.test import ( LiveServerTestCase, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.utils import six from django.utils._os import upath from django.utils.module_loading import import_string from django.utils.translation import LANGUAGE_SESSION_KEY, override from ..urls import locale_dir @override_settings(ROOT_URLCONF='view_tests.urls') class I18NTests(TestCase): """ Tests django views in django/views/i18n.py """ def test_setlang(self): """ The set_language view can be used to change the session language. The user is redirected to the 'next' argument if provided. """ for lang_code, lang_name in settings.LANGUAGES: post_data = dict(language=lang_code, next='/') response = self.client.post('/i18n/setlang/', data=post_data) self.assertRedirects(response, '/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_unsafe_next(self): """ The set_language view only redirects to the 'next' argument if it is "safe". """ lang_code, lang_name = settings.LANGUAGES[0] post_data = dict(language=lang_code, next='//unsafe/redirection/') response = self.client.post('/i18n/setlang/', data=post_data) self.assertEqual(response.url, '/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_reversal(self): self.assertEqual(reverse('set_language'), '/i18n/setlang/') def test_setlang_cookie(self): # we force saving language to a cookie rather than a session # by excluding session middleware and those which do require it test_settings = dict( MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'], LANGUAGE_COOKIE_NAME='mylanguage', LANGUAGE_COOKIE_AGE=3600 * 7 * 2, LANGUAGE_COOKIE_DOMAIN='.example.com', LANGUAGE_COOKIE_PATH='/test/', ) with self.settings(**test_settings): post_data = dict(language='pl', next='/views/') response = self.client.post('/i18n/setlang/', data=post_data) language_cookie = response.cookies.get('mylanguage') self.assertEqual(language_cookie.value, 'pl') self.assertEqual(language_cookie['domain'], '.example.com') self.assertEqual(language_cookie['path'], '/test/') self.assertEqual(language_cookie['max-age'], 3600 * 7 * 2) @modify_settings(MIDDLEWARE_CLASSES={ 'append': 'django.middleware.locale.LocaleMiddleware', }) def test_lang_from_translated_i18n_pattern(self): response = self.client.post( '/i18n/setlang/', data={'language': 'nl'}, follow=True, HTTP_REFERER='/en/translated/' ) self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'nl') self.assertRedirects(response, '/nl/vertaald/') # And reverse response = self.client.post( '/i18n/setlang/', data={'language': 'en'}, follow=True, HTTP_REFERER='/nl/vertaald/' ) self.assertRedirects(response, '/en/translated/') def test_jsi18n(self): """The javascript_catalog can be deployed with language settings""" for lang_code in ['es', 'fr', 'ru']: with override(lang_code): catalog = gettext.translation('djangojs', locale_dir, [lang_code]) if six.PY3: trans_txt = catalog.gettext('this is to be translated') else: trans_txt = catalog.ugettext('this is to be translated') response = self.client.get('/jsi18n/') # response content must include a line like: # "this is to be translated": <value of trans_txt Python variable> # json.dumps() is used to be able to check unicode strings self.assertContains(response, json.dumps(trans_txt), 1) if lang_code == 'fr': # Message with context (msgctxt) self.assertContains(response, '"month name\\u0004May": "mai"', 1) def test_jsoni18n(self): """ The json_catalog returns the language catalog and settings as JSON. """ with override('de'): response = self.client.get('/jsoni18n/') data = json.loads(response.content.decode('utf-8')) self.assertIn('catalog', data) self.assertIn('formats', data) self.assertIn('plural', data) self.assertEqual(data['catalog']['month name\x04May'], 'Mai') self.assertIn('DATETIME_FORMAT', data['formats']) self.assertEqual(data['plural'], '(n != 1)') @override_settings(ROOT_URLCONF='view_tests.urls') class JsI18NTests(SimpleTestCase): """ Tests django views in django/views/i18n.py that need to change settings.LANGUAGE_CODE. """ def test_jsi18n_with_missing_en_files(self): """ The javascript_catalog shouldn't load the fallback language in the case that the current selected language is actually the one translated from, and hence missing translation files completely. This happens easily when you're translating from English to other languages and you've set settings.LANGUAGE_CODE to some other language than English. """ with self.settings(LANGUAGE_CODE='es'), override('en-us'): response = self.client.get('/jsi18n/') self.assertNotContains(response, 'esto tiene que ser traducido') def test_jsoni18n_with_missing_en_files(self): """ Same as above for the json_catalog view. Here we also check for the expected JSON format. """ with self.settings(LANGUAGE_CODE='es'), override('en-us'): response = self.client.get('/jsoni18n/') data = json.loads(response.content.decode('utf-8')) self.assertIn('catalog', data) self.assertIn('formats', data) self.assertIn('plural', data) self.assertEqual(data['catalog'], {}) self.assertIn('DATETIME_FORMAT', data['formats']) self.assertIsNone(data['plural']) def test_jsi18n_fallback_language(self): """ Let's make sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE='fr'), override('fi'): response = self.client.get('/jsi18n/') self.assertContains(response, 'il faut le traduire') def test_i18n_language_non_english_default(self): """ Check if the Javascript i18n view returns an empty language catalog if the default language is non-English, the selected language is English and there is not 'en' translation available. See #13388, #3594 and #13726 for more details. """ with self.settings(LANGUAGE_CODE='fr'), override('en-us'): response = self.client.get('/jsi18n/') self.assertNotContains(response, 'Choisir une heure') @modify_settings(INSTALLED_APPS={'append': 'view_tests.app0'}) def test_non_english_default_english_userpref(self): """ Same as above with the difference that there IS an 'en' translation available. The Javascript i18n view must return a NON empty language catalog with the proper English translations. See #13726 for more details. """ with self.settings(LANGUAGE_CODE='fr'), override('en-us'): response = self.client.get('/jsi18n_english_translation/') self.assertContains(response, 'this app0 string is to be translated') def test_i18n_language_non_english_fallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE='fr'), override('none'): response = self.client.get('/jsi18n/') self.assertContains(response, 'Choisir une heure') def test_escaping(self): # Force a language via GET otherwise the gettext functions are a noop! response = self.client.get('/jsi18n_admin/?language=de') self.assertContains(response, '\\x04') @modify_settings(INSTALLED_APPS={'append': ['view_tests.app5']}) def test_non_BMP_char(self): """ Non-BMP characters should not break the javascript_catalog (#21725). """ with self.settings(LANGUAGE_CODE='en-us'), override('fr'): response = self.client.get('/jsi18n/app5/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'emoji') self.assertContains(response, '\\ud83d\\udca9') @override_settings(ROOT_URLCONF='view_tests.urls') class JsI18NTestsMultiPackage(SimpleTestCase): """ Tests for django views in django/views/i18n.py that need to change settings.LANGUAGE_CODE and merge JS translation from several packages. """ @modify_settings(INSTALLED_APPS={'append': ['view_tests.app1', 'view_tests.app2']}) def test_i18n_language_english_default(self): """ Check if the JavaScript i18n view returns a complete language catalog if the default language is en-us, the selected language has a translation available and a catalog composed by djangojs domain translations of multiple Python packages is requested. See #13388, #3594 and #13514 for more details. """ with self.settings(LANGUAGE_CODE='en-us'), override('fr'): response = self.client.get('/jsi18n_multi_packages1/') self.assertContains(response, 'il faut traduire cette cha\\u00eene de caract\\u00e8res de app1') @modify_settings(INSTALLED_APPS={'append': ['view_tests.app3', 'view_tests.app4']}) def test_i18n_different_non_english_languages(self): """ Similar to above but with neither default or requested language being English. """ with self.settings(LANGUAGE_CODE='fr'), override('es-ar'): response = self.client.get('/jsi18n_multi_packages2/') self.assertContains(response, 'este texto de app3 debe ser traducido') def test_i18n_with_locale_paths(self): extended_locale_paths = settings.LOCALE_PATHS + [ path.join( path.dirname(path.dirname(path.abspath(upath(__file__)))), 'app3', 'locale', ), ] with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths): with override('es-ar'): response = self.client.get('/jsi18n/') self.assertContains(response, 'este texto de app3 debe ser traducido') skip_selenium = not os.environ.get('DJANGO_SELENIUM_TESTS', False) @unittest.skipIf(skip_selenium, 'Selenium tests not requested') @override_settings(ROOT_URLCONF='view_tests.urls') class JavascriptI18nTests(LiveServerTestCase): # The test cases use fixtures & translations from these apps. available_apps = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'view_tests', ] webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver' @classmethod def setUpClass(cls): try: cls.selenium = import_string(cls.webdriver_class)() except Exception as e: raise unittest.SkipTest('Selenium webdriver "%s" not installed or ' 'not operational: %s' % (cls.webdriver_class, str(e))) super(JavascriptI18nTests, cls).setUpClass() @classmethod def tearDownClass(cls): cls.selenium.quit() super(JavascriptI18nTests, cls).tearDownClass() @override_settings(LANGUAGE_CODE='de') def test_javascript_gettext(self): self.selenium.get('%s%s' % (self.live_server_url, '/jsi18n_template/')) elem = self.selenium.find_element_by_id("gettext") self.assertEqual(elem.text, "Entfernen") elem = self.selenium.find_element_by_id("ngettext_sing") self.assertEqual(elem.text, "1 Element") elem = self.selenium.find_element_by_id("ngettext_plur") self.assertEqual(elem.text, "455 Elemente") elem = self.selenium.find_element_by_id("pgettext") self.assertEqual(elem.text, "Kann") elem = self.selenium.find_element_by_id("npgettext_sing") self.assertEqual(elem.text, "1 Resultat") elem = self.selenium.find_element_by_id("npgettext_plur") self.assertEqual(elem.text, "455 Resultate") @modify_settings(INSTALLED_APPS={'append': ['view_tests.app1', 'view_tests.app2']}) @override_settings(LANGUAGE_CODE='fr') def test_multiple_catalogs(self): self.selenium.get('%s%s' % (self.live_server_url, '/jsi18n_multi_catalogs/')) elem = self.selenium.find_element_by_id('app1string') self.assertEqual(elem.text, 'il faut traduire cette chaîne de caractères de app1') elem = self.selenium.find_element_by_id('app2string') self.assertEqual(elem.text, 'il faut traduire cette chaîne de caractères de app2') class JavascriptI18nChromeTests(JavascriptI18nTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class JavascriptI18nIETests(JavascriptI18nTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
bsd-3-clause
aricchen/openHR
openerp/tools/parse_version.py
76
4445
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 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/>. # ############################################################################## ## this functions are taken from the setuptools package (version 0.6c8) ## http://peak.telecommunity.com/DevCenter/PkgResources#parsing-utilities import re component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE) replace = {'pre':'c', 'preview':'c','-':'final-','_':'final-','rc':'c','dev':'@'}.get def _parse_version_parts(s): for part in component_re.split(s): part = replace(part,part) if not part or part=='.': continue if part[:1] in '0123456789': yield part.zfill(8) # pad for numeric comparison else: yield '*'+part yield '*final' # ensure that alpha/beta/candidate are before final def parse_version(s): """Convert a version string to a chronologically-sortable key This is a rough cross between distutils' StrictVersion and LooseVersion; if you give it versions that would work with StrictVersion, then it behaves the same; otherwise it acts like a slightly-smarter LooseVersion. It is *possible* to create pathological version coding schemes that will fool this parser, but they should be very rare in practice. The returned value will be a tuple of strings. Numeric portions of the version are padded to 8 digits so they will compare numerically, but without relying on how numbers compare relative to strings. Dots are dropped, but dashes are retained. Trailing zeros between alpha segments or dashes are suppressed, so that e.g. "2.4.0" is considered the same as "2.4". Alphanumeric parts are lower-cased. The algorithm assumes that strings like "-" and any alpha string that alphabetically follows "final" represents a "patch level". So, "2.4-1" is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is considered newer than "2.4-1", whic in turn is newer than "2.4". Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that come before "final" alphabetically) are assumed to be pre-release versions, so that the version "2.4" is considered newer than "2.4a1". Finally, to handle miscellaneous cases, the strings "pre", "preview", and "rc" are treated as if they were "c", i.e. as though they were release candidates, and therefore are not as new as a version string that does not contain them. """ parts = [] for part in _parse_version_parts((s or '0.1').lower()): if part.startswith('*'): if part<'*final': # remove '-' before a prerelease tag while parts and parts[-1]=='*final-': parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1]=='00000000': parts.pop() parts.append(part) return tuple(parts) if __name__ == '__main__': def cmp(a, b): msg = '%s < %s == %s' % (a, b, a < b) assert a < b, msg return b def chk(lst, verbose=False): pvs = [] for v in lst: pv = parse_version(v) pvs.append(pv) if verbose: print v, pv reduce(cmp, pvs) chk(('0', '4.2', '4.2.3.4', '5.0.0-alpha', '5.0.0-rc1', '5.0.0-rc1.1', '5.0.0_rc2', '5.0.0_rc3', '5.0.0'), False) chk(('5.0.0-0_rc3', '5.0.0-1dev', '5.0.0-1'), False) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
mancoast/CPythonPyc_test
cpython/264_test_zipimport.py
55
17378
import sys import os import marshal import imp import struct import time import unittest import zlib # implied prerequisite from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED from test import test_support from test.test_importhooks import ImportHooksBaseTestCase, test_src, test_co import zipimport import linecache import doctest import inspect import StringIO from traceback import extract_tb, extract_stack, print_tb raise_src = 'def do_raise(): raise TypeError\n' # so we only run testAFakeZlib once if this test is run repeatedly # which happens when we look for ref leaks test_imported = False def make_pyc(co, mtime): data = marshal.dumps(co) if type(mtime) is type(0.0): # Mac mtimes need a bit of special casing if mtime < 0x7fffffff: mtime = int(mtime) else: mtime = int(-0x100000000L + long(mtime)) pyc = imp.get_magic() + struct.pack("<i", int(mtime)) + data return pyc def module_path_to_dotted_name(path): return path.replace(os.sep, '.') NOW = time.time() test_pyc = make_pyc(test_co, NOW) if __debug__: pyc_ext = ".pyc" else: pyc_ext = ".pyo" TESTMOD = "ziptestmodule" TESTPACK = "ziptestpackage" TESTPACK2 = "ziptestpackage2" TEMP_ZIP = os.path.abspath("junk95142" + os.extsep + "zip") class UncompressedZipImportTestCase(ImportHooksBaseTestCase): compression = ZIP_STORED def setUp(self): # We're reusing the zip archive path, so we must clear the # cached directory info and linecache linecache.clearcache() zipimport._zip_directory_cache.clear() ImportHooksBaseTestCase.setUp(self) def doTest(self, expected_ext, files, *modules, **kw): z = ZipFile(TEMP_ZIP, "w") try: for name, (mtime, data) in files.items(): zinfo = ZipInfo(name, time.localtime(mtime)) zinfo.compress_type = self.compression z.writestr(zinfo, data) z.close() stuff = kw.get("stuff", None) if stuff is not None: # Prepend 'stuff' to the start of the zipfile f = open(TEMP_ZIP, "rb") data = f.read() f.close() f = open(TEMP_ZIP, "wb") f.write(stuff) f.write(data) f.close() sys.path.insert(0, TEMP_ZIP) mod = __import__(".".join(modules), globals(), locals(), ["__dummy__"]) call = kw.get('call') if call is not None: call(mod) if expected_ext: file = mod.get_file() self.assertEquals(file, os.path.join(TEMP_ZIP, *modules) + expected_ext) finally: z.close() os.remove(TEMP_ZIP) def testAFakeZlib(self): # # This could cause a stack overflow before: importing zlib.py # from a compressed archive would cause zlib to be imported # which would find zlib.py in the archive, which would... etc. # # This test *must* be executed first: it must be the first one # to trigger zipimport to import zlib (zipimport caches the # zlib.decompress function object, after which the problem being # tested here wouldn't be a problem anymore... # (Hence the 'A' in the test method name: to make it the first # item in a list sorted by name, like unittest.makeSuite() does.) # # This test fails on platforms on which the zlib module is # statically linked, but the problem it tests for can't # occur in that case (builtin modules are always found first), # so we'll simply skip it then. Bug #765456. # if "zlib" in sys.builtin_module_names: return if "zlib" in sys.modules: del sys.modules["zlib"] files = {"zlib.py": (NOW, test_src)} try: self.doTest(".py", files, "zlib") except ImportError: if self.compression != ZIP_DEFLATED: self.fail("expected test to not raise ImportError") else: if self.compression != ZIP_STORED: self.fail("expected test to raise ImportError") def testPy(self): files = {TESTMOD + ".py": (NOW, test_src)} self.doTest(".py", files, TESTMOD) def testPyc(self): files = {TESTMOD + pyc_ext: (NOW, test_pyc)} self.doTest(pyc_ext, files, TESTMOD) def testBoth(self): files = {TESTMOD + ".py": (NOW, test_src), TESTMOD + pyc_ext: (NOW, test_pyc)} self.doTest(pyc_ext, files, TESTMOD) def testEmptyPy(self): files = {TESTMOD + ".py": (NOW, "")} self.doTest(None, files, TESTMOD) def testBadMagic(self): # make pyc magic word invalid, forcing loading from .py m0 = ord(test_pyc[0]) m0 ^= 0x04 # flip an arbitrary bit badmagic_pyc = chr(m0) + test_pyc[1:] files = {TESTMOD + ".py": (NOW, test_src), TESTMOD + pyc_ext: (NOW, badmagic_pyc)} self.doTest(".py", files, TESTMOD) def testBadMagic2(self): # make pyc magic word invalid, causing an ImportError m0 = ord(test_pyc[0]) m0 ^= 0x04 # flip an arbitrary bit badmagic_pyc = chr(m0) + test_pyc[1:] files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)} try: self.doTest(".py", files, TESTMOD) except ImportError: pass else: self.fail("expected ImportError; import from bad pyc") def testBadMTime(self): t3 = ord(test_pyc[7]) t3 ^= 0x02 # flip the second bit -- not the first as that one # isn't stored in the .py's mtime in the zip archive. badtime_pyc = test_pyc[:7] + chr(t3) + test_pyc[8:] files = {TESTMOD + ".py": (NOW, test_src), TESTMOD + pyc_ext: (NOW, badtime_pyc)} self.doTest(".py", files, TESTMOD) def testPackage(self): packdir = TESTPACK + os.sep files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc), packdir + TESTMOD + pyc_ext: (NOW, test_pyc)} self.doTest(pyc_ext, files, TESTPACK, TESTMOD) def testDeepPackage(self): packdir = TESTPACK + os.sep packdir2 = packdir + TESTPACK2 + os.sep files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc), packdir2 + "__init__" + pyc_ext: (NOW, test_pyc), packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)} self.doTest(pyc_ext, files, TESTPACK, TESTPACK2, TESTMOD) def testZipImporterMethods(self): packdir = TESTPACK + os.sep packdir2 = packdir + TESTPACK2 + os.sep files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc), packdir2 + "__init__" + pyc_ext: (NOW, test_pyc), packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)} z = ZipFile(TEMP_ZIP, "w") try: for name, (mtime, data) in files.items(): zinfo = ZipInfo(name, time.localtime(mtime)) zinfo.compress_type = self.compression z.writestr(zinfo, data) z.close() zi = zipimport.zipimporter(TEMP_ZIP) self.assertEquals(zi.archive, TEMP_ZIP) self.assertEquals(zi.is_package(TESTPACK), True) mod = zi.load_module(TESTPACK) self.assertEquals(zi._get_filename(TESTPACK), mod.__file__) self.assertEquals(zi.is_package(packdir + '__init__'), False) self.assertEquals(zi.is_package(packdir + TESTPACK2), True) self.assertEquals(zi.is_package(packdir2 + TESTMOD), False) mod_path = packdir2 + TESTMOD mod_name = module_path_to_dotted_name(mod_path) pkg = __import__(mod_name) mod = sys.modules[mod_name] self.assertEquals(zi.get_source(TESTPACK), None) self.assertEquals(zi.get_source(mod_path), None) self.assertEquals(zi._get_filename(mod_path), mod.__file__) # To pass in the module name instead of the path, we must use the right importer loader = mod.__loader__ self.assertEquals(loader.get_source(mod_name), None) self.assertEquals(loader._get_filename(mod_name), mod.__file__) # test prefix and archivepath members zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK) self.assertEquals(zi2.archive, TEMP_ZIP) self.assertEquals(zi2.prefix, TESTPACK + os.sep) finally: z.close() os.remove(TEMP_ZIP) def testZipImporterMethodsInSubDirectory(self): packdir = TESTPACK + os.sep packdir2 = packdir + TESTPACK2 + os.sep files = {packdir2 + "__init__" + pyc_ext: (NOW, test_pyc), packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)} z = ZipFile(TEMP_ZIP, "w") try: for name, (mtime, data) in files.items(): zinfo = ZipInfo(name, time.localtime(mtime)) zinfo.compress_type = self.compression z.writestr(zinfo, data) z.close() zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir) self.assertEquals(zi.archive, TEMP_ZIP) self.assertEquals(zi.prefix, packdir) self.assertEquals(zi.is_package(TESTPACK2), True) mod = zi.load_module(TESTPACK2) self.assertEquals(zi._get_filename(TESTPACK2), mod.__file__) self.assertEquals(zi.is_package(TESTPACK2 + os.sep + '__init__'), False) self.assertEquals(zi.is_package(TESTPACK2 + os.sep + TESTMOD), False) mod_path = TESTPACK2 + os.sep + TESTMOD mod_name = module_path_to_dotted_name(mod_path) pkg = __import__(mod_name) mod = sys.modules[mod_name] self.assertEquals(zi.get_source(TESTPACK2), None) self.assertEquals(zi.get_source(mod_path), None) self.assertEquals(zi._get_filename(mod_path), mod.__file__) # To pass in the module name instead of the path, we must use the right importer loader = mod.__loader__ self.assertEquals(loader.get_source(mod_name), None) self.assertEquals(loader._get_filename(mod_name), mod.__file__) finally: z.close() os.remove(TEMP_ZIP) def testGetData(self): z = ZipFile(TEMP_ZIP, "w") z.compression = self.compression try: name = "testdata.dat" data = "".join([chr(x) for x in range(256)]) * 500 z.writestr(name, data) z.close() zi = zipimport.zipimporter(TEMP_ZIP) self.assertEquals(data, zi.get_data(name)) self.assert_('zipimporter object' in repr(zi)) finally: z.close() os.remove(TEMP_ZIP) def testImporterAttr(self): src = """if 1: # indent hack def get_file(): return __file__ if __loader__.get_data("some.data") != "some data": raise AssertionError, "bad data"\n""" pyc = make_pyc(compile(src, "<???>", "exec"), NOW) files = {TESTMOD + pyc_ext: (NOW, pyc), "some.data": (NOW, "some data")} self.doTest(pyc_ext, files, TESTMOD) def testImport_WithStuff(self): # try importing from a zipfile which contains additional # stuff at the beginning of the file files = {TESTMOD + ".py": (NOW, test_src)} self.doTest(".py", files, TESTMOD, stuff="Some Stuff"*31) def assertModuleSource(self, module): self.assertEqual(inspect.getsource(module), test_src) def testGetSource(self): files = {TESTMOD + ".py": (NOW, test_src)} self.doTest(".py", files, TESTMOD, call=self.assertModuleSource) def testGetCompiledSource(self): pyc = make_pyc(compile(test_src, "<???>", "exec"), NOW) files = {TESTMOD + ".py": (NOW, test_src), TESTMOD + pyc_ext: (NOW, pyc)} self.doTest(pyc_ext, files, TESTMOD, call=self.assertModuleSource) def runDoctest(self, callback): files = {TESTMOD + ".py": (NOW, test_src), "xyz.txt": (NOW, ">>> log.append(True)\n")} self.doTest(".py", files, TESTMOD, call=callback) def doDoctestFile(self, module): log = [] old_master, doctest.master = doctest.master, None try: doctest.testfile( 'xyz.txt', package=module, module_relative=True, globs=locals() ) finally: doctest.master = old_master self.assertEqual(log,[True]) def testDoctestFile(self): self.runDoctest(self.doDoctestFile) def doDoctestSuite(self, module): log = [] doctest.DocFileTest( 'xyz.txt', package=module, module_relative=True, globs=locals() ).run() self.assertEqual(log,[True]) def testDoctestSuite(self): self.runDoctest(self.doDoctestSuite) def doTraceback(self, module): try: module.do_raise() except: tb = sys.exc_info()[2].tb_next f,lno,n,line = extract_tb(tb, 1)[0] self.assertEqual(line, raise_src.strip()) f,lno,n,line = extract_stack(tb.tb_frame, 1)[0] self.assertEqual(line, raise_src.strip()) s = StringIO.StringIO() print_tb(tb, 1, s) self.failUnless(s.getvalue().endswith(raise_src)) else: raise AssertionError("This ought to be impossible") def testTraceback(self): files = {TESTMOD + ".py": (NOW, raise_src)} self.doTest(None, files, TESTMOD, call=self.doTraceback) class CompressedZipImportTestCase(UncompressedZipImportTestCase): compression = ZIP_DEFLATED class BadFileZipImportTestCase(unittest.TestCase): def assertZipFailure(self, filename): self.assertRaises(zipimport.ZipImportError, zipimport.zipimporter, filename) def testNoFile(self): self.assertZipFailure('AdfjdkFJKDFJjdklfjs') def testEmptyFilename(self): self.assertZipFailure('') def testBadArgs(self): self.assertRaises(TypeError, zipimport.zipimporter, None) self.assertRaises(TypeError, zipimport.zipimporter, TESTMOD, kwd=None) def testFilenameTooLong(self): self.assertZipFailure('A' * 33000) def testEmptyFile(self): test_support.unlink(TESTMOD) open(TESTMOD, 'w+').close() self.assertZipFailure(TESTMOD) def testFileUnreadable(self): test_support.unlink(TESTMOD) fd = os.open(TESTMOD, os.O_CREAT, 000) try: os.close(fd) self.assertZipFailure(TESTMOD) finally: # If we leave "the read-only bit" set on Windows, nothing can # delete TESTMOD, and later tests suffer bogus failures. os.chmod(TESTMOD, 0666) test_support.unlink(TESTMOD) def testNotZipFile(self): test_support.unlink(TESTMOD) fp = open(TESTMOD, 'w+') fp.write('a' * 22) fp.close() self.assertZipFailure(TESTMOD) # XXX: disabled until this works on Big-endian machines def _testBogusZipFile(self): test_support.unlink(TESTMOD) fp = open(TESTMOD, 'w+') fp.write(struct.pack('=I', 0x06054B50)) fp.write('a' * 18) fp.close() z = zipimport.zipimporter(TESTMOD) try: self.assertRaises(TypeError, z.find_module, None) self.assertRaises(TypeError, z.load_module, None) self.assertRaises(TypeError, z.is_package, None) self.assertRaises(TypeError, z.get_code, None) self.assertRaises(TypeError, z.get_data, None) self.assertRaises(TypeError, z.get_source, None) error = zipimport.ZipImportError self.assertEqual(z.find_module('abc'), None) self.assertRaises(error, z.load_module, 'abc') self.assertRaises(error, z.get_code, 'abc') self.assertRaises(IOError, z.get_data, 'abc') self.assertRaises(error, z.get_source, 'abc') self.assertRaises(error, z.is_package, 'abc') finally: zipimport._zip_directory_cache.clear() def cleanup(): # this is necessary if test is run repeated (like when finding leaks) global test_imported if test_imported: zipimport._zip_directory_cache.clear() if hasattr(UncompressedZipImportTestCase, 'testAFakeZlib'): delattr(UncompressedZipImportTestCase, 'testAFakeZlib') if hasattr(CompressedZipImportTestCase, 'testAFakeZlib'): delattr(CompressedZipImportTestCase, 'testAFakeZlib') test_imported = True def test_main(): cleanup() try: test_support.run_unittest( UncompressedZipImportTestCase, CompressedZipImportTestCase, BadFileZipImportTestCase, ) finally: test_support.unlink(TESTMOD) if __name__ == "__main__": test_main()
gpl-3.0
jtimon/bitcoin
test/functional/rpc_txoutproof.py
23
6532
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test gettxoutproof and verifytxoutproof RPCs.""" from test_framework.messages import CMerkleBlock, FromHex, ToHex from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error, connect_nodes class MerkleBlockTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 self.setup_clean_chain = True # Nodes 0/1 are "wallet" nodes, Nodes 2/3 are used for testing self.extra_args = [[], [], [], ["-txindex"]] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def setup_network(self): self.setup_nodes() connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 2) connect_nodes(self.nodes[0], 3) self.sync_all() def run_test(self): self.log.info("Mining blocks...") self.nodes[0].generate(105) self.sync_all() chain_height = self.nodes[1].getblockcount() assert_equal(chain_height, 105) assert_equal(self.nodes[1].getbalance(), 0) assert_equal(self.nodes[2].getbalance(), 0) node0utxos = self.nodes[0].listunspent(1) tx1 = self.nodes[0].createrawtransaction([node0utxos.pop()], {self.nodes[1].getnewaddress(): 49.99}) txid1 = self.nodes[0].sendrawtransaction(self.nodes[0].signrawtransactionwithwallet(tx1)["hex"]) tx2 = self.nodes[0].createrawtransaction([node0utxos.pop()], {self.nodes[1].getnewaddress(): 49.99}) txid2 = self.nodes[0].sendrawtransaction(self.nodes[0].signrawtransactionwithwallet(tx2)["hex"]) # This will raise an exception because the transaction is not yet in a block assert_raises_rpc_error(-5, "Transaction not yet in block", self.nodes[0].gettxoutproof, [txid1]) self.nodes[0].generate(1) blockhash = self.nodes[0].getblockhash(chain_height + 1) self.sync_all() txlist = [] blocktxn = self.nodes[0].getblock(blockhash, True)["tx"] txlist.append(blocktxn[1]) txlist.append(blocktxn[2]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1])), [txid1]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1, txid2])), txlist) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1, txid2], blockhash)), txlist) txin_spent = self.nodes[1].listunspent(1).pop() tx3 = self.nodes[1].createrawtransaction([txin_spent], {self.nodes[0].getnewaddress(): 49.98}) txid3 = self.nodes[0].sendrawtransaction(self.nodes[1].signrawtransactionwithwallet(tx3)["hex"]) self.nodes[0].generate(1) self.sync_all() txid_spent = txin_spent["txid"] txid_unspent = txid1 if txin_spent["txid"] != txid1 else txid2 # Invalid txids assert_raises_rpc_error(-8, "txid must be of length 64 (not 32, for '00000000000000000000000000000000')", self.nodes[2].gettxoutproof, ["00000000000000000000000000000000"], blockhash) assert_raises_rpc_error(-8, "txid must be hexadecimal string (not 'ZZZ0000000000000000000000000000000000000000000000000000000000000')", self.nodes[2].gettxoutproof, ["ZZZ0000000000000000000000000000000000000000000000000000000000000"], blockhash) # Invalid blockhashes assert_raises_rpc_error(-8, "blockhash must be of length 64 (not 32, for '00000000000000000000000000000000')", self.nodes[2].gettxoutproof, [txid_spent], "00000000000000000000000000000000") assert_raises_rpc_error(-8, "blockhash must be hexadecimal string (not 'ZZZ0000000000000000000000000000000000000000000000000000000000000')", self.nodes[2].gettxoutproof, [txid_spent], "ZZZ0000000000000000000000000000000000000000000000000000000000000") # We can't find the block from a fully-spent tx assert_raises_rpc_error(-5, "Transaction not yet in block", self.nodes[2].gettxoutproof, [txid_spent]) # We can get the proof if we specify the block assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_spent], blockhash)), [txid_spent]) # We can't get the proof if we specify a non-existent block assert_raises_rpc_error(-5, "Block not found", self.nodes[2].gettxoutproof, [txid_spent], "0000000000000000000000000000000000000000000000000000000000000000") # We can get the proof if the transaction is unspent assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_unspent])), [txid_unspent]) # We can get the proof if we provide a list of transactions and one of them is unspent. The ordering of the list should not matter. assert_equal(sorted(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid1, txid2]))), sorted(txlist)) assert_equal(sorted(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid2, txid1]))), sorted(txlist)) # We can always get a proof if we have a -txindex assert_equal(self.nodes[2].verifytxoutproof(self.nodes[3].gettxoutproof([txid_spent])), [txid_spent]) # We can't get a proof if we specify transactions from different blocks assert_raises_rpc_error(-5, "Not all transactions found in specified or retrieved block", self.nodes[2].gettxoutproof, [txid1, txid3]) # Now we'll try tweaking a proof. proof = self.nodes[3].gettxoutproof([txid1, txid2]) assert txid1 in self.nodes[0].verifytxoutproof(proof) assert txid2 in self.nodes[1].verifytxoutproof(proof) tweaked_proof = FromHex(CMerkleBlock(), proof) # Make sure that our serialization/deserialization is working assert txid1 in self.nodes[2].verifytxoutproof(ToHex(tweaked_proof)) # Check to see if we can go up the merkle tree and pass this off as a # single-transaction block tweaked_proof.txn.nTransactions = 1 tweaked_proof.txn.vHash = [tweaked_proof.header.hashMerkleRoot] tweaked_proof.txn.vBits = [True] + [False]*7 for n in self.nodes: assert not n.verifytxoutproof(ToHex(tweaked_proof)) # TODO: try more variants, eg transactions at different depths, and # verify that the proofs are invalid if __name__ == '__main__': MerkleBlockTest().main()
mit
GuardOscar/Starbound_RU
tools/vk_announce.py
8
1593
from urllib.request import urlopen from urllib.parse import urlencode, quote from json import dumps from codecs import encode from os import getenv from subprocess import check_output def post_n_pin(token, oid, message, link): ## Fallback method post_json = dumps({ "owner_id": oid, "from_group": 1, "message": message, "signed": 0, "attachments": link, "access_token": token }, ensure_ascii=False) pin_json = dumps({ "owner_id": oid, "access_token": token }) vkscript = """ var post = API.wall.post(%s); if (post != null && post.post_id != null) { var post_id = post.post_id; var pin_json = %s; pin_json.post_id = post_id; var result = API.wall.pin(pin_json); return [result, post]; } """ % (post_json, pin_json) data = urlencode({"code": vkscript, "V": "5.65", "access_token": token}, encoding='utf-8', quote_via=quote) return urlopen("https://api.vk.com/method/execute", data.encode('utf-8')) def post_n_pin_app(token, oid, message, link): ## Default publication method data = urlencode({"owner_id": oid, "message": message, "link": link, "access_token": token}).encode('utf-8') return urlopen("https://api.vk.com/method/execute.announce", data) atoken = getenv("VK_TOKEN") group_id = getenv("GROUP_ID") message = check_output(["git", "log", "-1", "--pretty=%B"]) result = post_n_pin_app(atoken, group_id, message, "https://github.com/sbt-community/Starbound_RU/releases/latest/") print(result.read())
apache-2.0
cbertinato/pandas
pandas/tests/io/formats/test_style.py
1
54948
import copy import re import textwrap import numpy as np import pytest import pandas.util._test_decorators as td import pandas as pd from pandas import DataFrame import pandas.util.testing as tm jinja2 = pytest.importorskip('jinja2') from pandas.io.formats.style import Styler, _get_level_lengths # noqa # isort:skip class TestStyler: def setup_method(self, method): np.random.seed(24) self.s = DataFrame({'A': np.random.permutation(range(6))}) self.df = DataFrame({'A': [0, 1], 'B': np.random.randn(2)}) self.f = lambda x: x self.g = lambda x: x def h(x, foo='bar'): return pd.Series( 'color: {foo}'.format(foo=foo), index=x.index, name=x.name) self.h = h self.styler = Styler(self.df) self.attrs = pd.DataFrame({'A': ['color: red', 'color: blue']}) self.dataframes = [ self.df, pd.DataFrame({'f': [1., 2.], 'o': ['a', 'b'], 'c': pd.Categorical(['a', 'b'])}) ] def test_init_non_pandas(self): with pytest.raises(TypeError): Styler([1, 2, 3]) def test_init_series(self): result = Styler(pd.Series([1, 2])) assert result.data.ndim == 2 def test_repr_html_ok(self): self.styler._repr_html_() def test_repr_html_mathjax(self): # gh-19824 assert 'tex2jax_ignore' not in self.styler._repr_html_() with pd.option_context('display.html.use_mathjax', False): assert 'tex2jax_ignore' in self.styler._repr_html_() def test_update_ctx(self): self.styler._update_ctx(self.attrs) expected = {(0, 0): ['color: red'], (1, 0): ['color: blue']} assert self.styler.ctx == expected def test_update_ctx_flatten_multi(self): attrs = DataFrame({"A": ['color: red; foo: bar', 'color: blue; foo: baz']}) self.styler._update_ctx(attrs) expected = {(0, 0): ['color: red', ' foo: bar'], (1, 0): ['color: blue', ' foo: baz']} assert self.styler.ctx == expected def test_update_ctx_flatten_multi_traliing_semi(self): attrs = DataFrame({"A": ['color: red; foo: bar;', 'color: blue; foo: baz;']}) self.styler._update_ctx(attrs) expected = {(0, 0): ['color: red', ' foo: bar'], (1, 0): ['color: blue', ' foo: baz']} assert self.styler.ctx == expected def test_copy(self): s2 = copy.copy(self.styler) assert self.styler is not s2 assert self.styler.ctx is s2.ctx # shallow assert self.styler._todo is s2._todo self.styler._update_ctx(self.attrs) self.styler.highlight_max() assert self.styler.ctx == s2.ctx assert self.styler._todo == s2._todo def test_deepcopy(self): s2 = copy.deepcopy(self.styler) assert self.styler is not s2 assert self.styler.ctx is not s2.ctx assert self.styler._todo is not s2._todo self.styler._update_ctx(self.attrs) self.styler.highlight_max() assert self.styler.ctx != s2.ctx assert s2._todo == [] assert self.styler._todo != s2._todo def test_clear(self): s = self.df.style.highlight_max()._compute() assert len(s.ctx) > 0 assert len(s._todo) > 0 s.clear() assert len(s.ctx) == 0 assert len(s._todo) == 0 def test_render(self): df = pd.DataFrame({"A": [0, 1]}) style = lambda x: pd.Series(["color: red", "color: blue"], name=x.name) s = Styler(df, uuid='AB').apply(style) s.render() # it worked? def test_render_empty_dfs(self): empty_df = DataFrame() es = Styler(empty_df) es.render() # An index but no columns DataFrame(columns=['a']).style.render() # A column but no index DataFrame(index=['a']).style.render() # No IndexError raised? def test_render_double(self): df = pd.DataFrame({"A": [0, 1]}) style = lambda x: pd.Series(["color: red; border: 1px", "color: blue; border: 2px"], name=x.name) s = Styler(df, uuid='AB').apply(style) s.render() # it worked? def test_set_properties(self): df = pd.DataFrame({"A": [0, 1]}) result = df.style.set_properties(color='white', size='10px')._compute().ctx # order is deterministic v = ["color: white", "size: 10px"] expected = {(0, 0): v, (1, 0): v} assert result.keys() == expected.keys() for v1, v2 in zip(result.values(), expected.values()): assert sorted(v1) == sorted(v2) def test_set_properties_subset(self): df = pd.DataFrame({'A': [0, 1]}) result = df.style.set_properties(subset=pd.IndexSlice[0, 'A'], color='white')._compute().ctx expected = {(0, 0): ['color: white']} assert result == expected def test_empty_index_name_doesnt_display(self): # https://github.com/pandas-dev/pandas/pull/12090#issuecomment-180695902 df = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6]}) result = df.style._translate() expected = [[{'class': 'blank level0', 'type': 'th', 'value': '', 'is_visible': True, 'display_value': ''}, {'class': 'col_heading level0 col0', 'display_value': 'A', 'type': 'th', 'value': 'A', 'is_visible': True, }, {'class': 'col_heading level0 col1', 'display_value': 'B', 'type': 'th', 'value': 'B', 'is_visible': True, }, {'class': 'col_heading level0 col2', 'display_value': 'C', 'type': 'th', 'value': 'C', 'is_visible': True, }]] assert result['head'] == expected def test_index_name(self): # https://github.com/pandas-dev/pandas/issues/11655 df = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6]}) result = df.set_index('A').style._translate() expected = [[{'class': 'blank level0', 'type': 'th', 'value': '', 'display_value': '', 'is_visible': True}, {'class': 'col_heading level0 col0', 'type': 'th', 'value': 'B', 'display_value': 'B', 'is_visible': True}, {'class': 'col_heading level0 col1', 'type': 'th', 'value': 'C', 'display_value': 'C', 'is_visible': True}], [{'class': 'index_name level0', 'type': 'th', 'value': 'A'}, {'class': 'blank', 'type': 'th', 'value': ''}, {'class': 'blank', 'type': 'th', 'value': ''}]] assert result['head'] == expected def test_multiindex_name(self): # https://github.com/pandas-dev/pandas/issues/11655 df = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6]}) result = df.set_index(['A', 'B']).style._translate() expected = [[ {'class': 'blank', 'type': 'th', 'value': '', 'display_value': '', 'is_visible': True}, {'class': 'blank level0', 'type': 'th', 'value': '', 'display_value': '', 'is_visible': True}, {'class': 'col_heading level0 col0', 'type': 'th', 'value': 'C', 'display_value': 'C', 'is_visible': True}], [{'class': 'index_name level0', 'type': 'th', 'value': 'A'}, {'class': 'index_name level1', 'type': 'th', 'value': 'B'}, {'class': 'blank', 'type': 'th', 'value': ''}]] assert result['head'] == expected def test_numeric_columns(self): # https://github.com/pandas-dev/pandas/issues/12125 # smoke test for _translate df = pd.DataFrame({0: [1, 2, 3]}) df.style._translate() def test_apply_axis(self): df = pd.DataFrame({'A': [0, 0], 'B': [1, 1]}) f = lambda x: ['val: {max}'.format(max=x.max()) for v in x] result = df.style.apply(f, axis=1) assert len(result._todo) == 1 assert len(result.ctx) == 0 result._compute() expected = {(0, 0): ['val: 1'], (0, 1): ['val: 1'], (1, 0): ['val: 1'], (1, 1): ['val: 1']} assert result.ctx == expected result = df.style.apply(f, axis=0) expected = {(0, 0): ['val: 0'], (0, 1): ['val: 1'], (1, 0): ['val: 0'], (1, 1): ['val: 1']} result._compute() assert result.ctx == expected result = df.style.apply(f) # default result._compute() assert result.ctx == expected def test_apply_subset(self): axes = [0, 1] slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']], pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']], pd.IndexSlice[:2, ['A', 'B']]] for ax in axes: for slice_ in slices: result = self.df.style.apply(self.h, axis=ax, subset=slice_, foo='baz')._compute().ctx expected = {(r, c): ['color: baz'] for r, row in enumerate(self.df.index) for c, col in enumerate(self.df.columns) if row in self.df.loc[slice_].index and col in self.df.loc[slice_].columns} assert result == expected def test_applymap_subset(self): def f(x): return 'foo: bar' slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']], pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']], pd.IndexSlice[:2, ['A', 'B']]] for slice_ in slices: result = self.df.style.applymap(f, subset=slice_)._compute().ctx expected = {(r, c): ['foo: bar'] for r, row in enumerate(self.df.index) for c, col in enumerate(self.df.columns) if row in self.df.loc[slice_].index and col in self.df.loc[slice_].columns} assert result == expected def test_applymap_subset_multiindex(self): # GH 19861 # Smoke test for applymap def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'red' if val < 0 else 'black' return 'color: %s' % color dic = { ('a', 'd'): [-1.12, 2.11], ('a', 'c'): [2.78, -2.88], ('b', 'c'): [-3.99, 3.77], ('b', 'd'): [4.21, -1.22], } idx = pd.IndexSlice df = pd.DataFrame(dic, index=[0, 1]) (df.style .applymap(color_negative_red, subset=idx[:, idx['b', 'd']]) .render()) def test_where_with_one_style(self): # GH 17474 def f(x): return x > 0.5 style1 = 'foo: bar' result = self.df.style.where(f, style1)._compute().ctx expected = {(r, c): [style1 if f(self.df.loc[row, col]) else ''] for r, row in enumerate(self.df.index) for c, col in enumerate(self.df.columns)} assert result == expected def test_where_subset(self): # GH 17474 def f(x): return x > 0.5 style1 = 'foo: bar' style2 = 'baz: foo' slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']], pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']], pd.IndexSlice[:2, ['A', 'B']]] for slice_ in slices: result = self.df.style.where(f, style1, style2, subset=slice_)._compute().ctx expected = {(r, c): [style1 if f(self.df.loc[row, col]) else style2] for r, row in enumerate(self.df.index) for c, col in enumerate(self.df.columns) if row in self.df.loc[slice_].index and col in self.df.loc[slice_].columns} assert result == expected def test_where_subset_compare_with_applymap(self): # GH 17474 def f(x): return x > 0.5 style1 = 'foo: bar' style2 = 'baz: foo' def g(x): return style1 if f(x) else style2 slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']], pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']], pd.IndexSlice[:2, ['A', 'B']]] for slice_ in slices: result = self.df.style.where(f, style1, style2, subset=slice_)._compute().ctx expected = self.df.style.applymap(g, subset=slice_)._compute().ctx assert result == expected def test_empty(self): df = pd.DataFrame({'A': [1, 0]}) s = df.style s.ctx = {(0, 0): ['color: red'], (1, 0): ['']} result = s._translate()['cellstyle'] expected = [{'props': [['color', ' red']], 'selector': 'row0_col0'}, {'props': [['', '']], 'selector': 'row1_col0'}] assert result == expected def test_bar_align_left(self): df = pd.DataFrame({'A': [0, 1, 2]}) result = df.style.bar()._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(' '90deg,#d65f5f 50.0%, transparent 50.0%)'], (2, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(' '90deg,#d65f5f 100.0%, transparent 100.0%)'] } assert result == expected result = df.style.bar(color='red', width=50)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(' '90deg,red 25.0%, transparent 25.0%)'], (2, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(' '90deg,red 50.0%, transparent 50.0%)'] } assert result == expected df['C'] = ['a'] * len(df) result = df.style.bar(color='red', width=50)._compute().ctx assert result == expected df['C'] = df['C'].astype('category') result = df.style.bar(color='red', width=50)._compute().ctx assert result == expected def test_bar_align_left_0points(self): df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) result = df.style.bar()._compute().ctx expected = {(0, 0): ['width: 10em', ' height: 80%'], (0, 1): ['width: 10em', ' height: 80%'], (0, 2): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 50.0%,' ' transparent 50.0%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 50.0%,' ' transparent 50.0%)'], (1, 2): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 50.0%,' ' transparent 50.0%)'], (2, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 100.0%' ', transparent 100.0%)'], (2, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 100.0%' ', transparent 100.0%)'], (2, 2): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 100.0%' ', transparent 100.0%)']} assert result == expected result = df.style.bar(axis=1)._compute().ctx expected = {(0, 0): ['width: 10em', ' height: 80%'], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 50.0%,' ' transparent 50.0%)'], (0, 2): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 100.0%' ', transparent 100.0%)'], (1, 0): ['width: 10em', ' height: 80%'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 50.0%' ', transparent 50.0%)'], (1, 2): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 100.0%' ', transparent 100.0%)'], (2, 0): ['width: 10em', ' height: 80%'], (2, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 50.0%' ', transparent 50.0%)'], (2, 2): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,#d65f5f 100.0%' ', transparent 100.0%)']} assert result == expected def test_bar_align_mid_pos_and_neg(self): df = pd.DataFrame({'A': [-10, 0, 20, 90]}) result = df.style.bar(align='mid', color=[ '#d65f5f', '#5fba7d'])._compute().ctx expected = {(0, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#d65f5f 10.0%, transparent 10.0%)'], (1, 0): ['width: 10em', ' height: 80%', ], (2, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 10.0%, #5fba7d 10.0%' ', #5fba7d 30.0%, transparent 30.0%)'], (3, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 10.0%, ' '#5fba7d 10.0%, #5fba7d 100.0%, ' 'transparent 100.0%)']} assert result == expected def test_bar_align_mid_all_pos(self): df = pd.DataFrame({'A': [10, 20, 50, 100]}) result = df.style.bar(align='mid', color=[ '#d65f5f', '#5fba7d'])._compute().ctx expected = {(0, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#5fba7d 10.0%, transparent 10.0%)'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#5fba7d 20.0%, transparent 20.0%)'], (2, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#5fba7d 50.0%, transparent 50.0%)'], (3, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#5fba7d 100.0%, transparent 100.0%)']} assert result == expected def test_bar_align_mid_all_neg(self): df = pd.DataFrame({'A': [-100, -60, -30, -20]}) result = df.style.bar(align='mid', color=[ '#d65f5f', '#5fba7d'])._compute().ctx expected = {(0, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#d65f5f 100.0%, transparent 100.0%)'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 40.0%, ' '#d65f5f 40.0%, #d65f5f 100.0%, ' 'transparent 100.0%)'], (2, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 70.0%, ' '#d65f5f 70.0%, #d65f5f 100.0%, ' 'transparent 100.0%)'], (3, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 80.0%, ' '#d65f5f 80.0%, #d65f5f 100.0%, ' 'transparent 100.0%)']} assert result == expected def test_bar_align_zero_pos_and_neg(self): # See https://github.com/pandas-dev/pandas/pull/14757 df = pd.DataFrame({'A': [-10, 0, 20, 90]}) result = df.style.bar(align='zero', color=[ '#d65f5f', '#5fba7d'], width=90)._compute().ctx expected = {(0, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 40.0%, #d65f5f 40.0%, ' '#d65f5f 45.0%, transparent 45.0%)'], (1, 0): ['width: 10em', ' height: 80%'], (2, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 45.0%, #5fba7d 45.0%, ' '#5fba7d 55.0%, transparent 55.0%)'], (3, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 45.0%, #5fba7d 45.0%, ' '#5fba7d 90.0%, transparent 90.0%)']} assert result == expected def test_bar_align_left_axis_none(self): df = pd.DataFrame({'A': [0, 1], 'B': [2, 4]}) result = df.style.bar(axis=None)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#d65f5f 25.0%, transparent 25.0%)'], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#d65f5f 50.0%, transparent 50.0%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#d65f5f 100.0%, transparent 100.0%)'] } assert result == expected def test_bar_align_zero_axis_none(self): df = pd.DataFrame({'A': [0, 1], 'B': [-2, 4]}) result = df.style.bar(align='zero', axis=None)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 50.0%, #d65f5f 50.0%, ' '#d65f5f 62.5%, transparent 62.5%)'], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 25.0%, #d65f5f 25.0%, ' '#d65f5f 50.0%, transparent 50.0%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 50.0%, #d65f5f 50.0%, ' '#d65f5f 100.0%, transparent 100.0%)'] } assert result == expected def test_bar_align_mid_axis_none(self): df = pd.DataFrame({'A': [0, 1], 'B': [-2, 4]}) result = df.style.bar(align='mid', axis=None)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 33.3%, #d65f5f 33.3%, ' '#d65f5f 50.0%, transparent 50.0%)'], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#d65f5f 33.3%, transparent 33.3%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 33.3%, #d65f5f 33.3%, ' '#d65f5f 100.0%, transparent 100.0%)'] } assert result == expected def test_bar_align_mid_vmin(self): df = pd.DataFrame({'A': [0, 1], 'B': [-2, 4]}) result = df.style.bar(align='mid', axis=None, vmin=-6)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 60.0%, #d65f5f 60.0%, ' '#d65f5f 70.0%, transparent 70.0%)'], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 40.0%, #d65f5f 40.0%, ' '#d65f5f 60.0%, transparent 60.0%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 60.0%, #d65f5f 60.0%, ' '#d65f5f 100.0%, transparent 100.0%)'] } assert result == expected def test_bar_align_mid_vmax(self): df = pd.DataFrame({'A': [0, 1], 'B': [-2, 4]}) result = df.style.bar(align='mid', axis=None, vmax=8)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 20.0%, #d65f5f 20.0%, ' '#d65f5f 30.0%, transparent 30.0%)'], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#d65f5f 20.0%, transparent 20.0%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 20.0%, #d65f5f 20.0%, ' '#d65f5f 60.0%, transparent 60.0%)'] } assert result == expected def test_bar_align_mid_vmin_vmax_wide(self): df = pd.DataFrame({'A': [0, 1], 'B': [-2, 4]}) result = df.style.bar(align='mid', axis=None, vmin=-3, vmax=7)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 30.0%, #d65f5f 30.0%, ' '#d65f5f 40.0%, transparent 40.0%)'], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 10.0%, #d65f5f 10.0%, ' '#d65f5f 30.0%, transparent 30.0%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 30.0%, #d65f5f 30.0%, ' '#d65f5f 70.0%, transparent 70.0%)'] } assert result == expected def test_bar_align_mid_vmin_vmax_clipping(self): df = pd.DataFrame({'A': [0, 1], 'B': [-2, 4]}) result = df.style.bar(align='mid', axis=None, vmin=-1, vmax=3)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%'], (1, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 25.0%, #d65f5f 25.0%, ' '#d65f5f 50.0%, transparent 50.0%)'], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#d65f5f 25.0%, transparent 25.0%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 25.0%, #d65f5f 25.0%, ' '#d65f5f 100.0%, transparent 100.0%)'] } assert result == expected def test_bar_align_mid_nans(self): df = pd.DataFrame({'A': [1, None], 'B': [-1, 3]}) result = df.style.bar(align='mid', axis=None)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 25.0%, #d65f5f 25.0%, ' '#d65f5f 50.0%, transparent 50.0%)'], (1, 0): [''], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg,' '#d65f5f 25.0%, transparent 25.0%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 25.0%, #d65f5f 25.0%, ' '#d65f5f 100.0%, transparent 100.0%)'] } assert result == expected def test_bar_align_zero_nans(self): df = pd.DataFrame({'A': [1, None], 'B': [-1, 2]}) result = df.style.bar(align='zero', axis=None)._compute().ctx expected = { (0, 0): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 50.0%, #d65f5f 50.0%, ' '#d65f5f 75.0%, transparent 75.0%)'], (1, 0): [''], (0, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 25.0%, #d65f5f 25.0%, ' '#d65f5f 50.0%, transparent 50.0%)'], (1, 1): ['width: 10em', ' height: 80%', 'background: linear-gradient(90deg, ' 'transparent 50.0%, #d65f5f 50.0%, ' '#d65f5f 100.0%, transparent 100.0%)'] } assert result == expected def test_bar_bad_align_raises(self): df = pd.DataFrame({'A': [-100, -60, -30, -20]}) with pytest.raises(ValueError): df.style.bar(align='poorly', color=['#d65f5f', '#5fba7d']) def test_highlight_null(self, null_color='red'): df = pd.DataFrame({'A': [0, np.nan]}) result = df.style.highlight_null()._compute().ctx expected = {(0, 0): [''], (1, 0): ['background-color: red']} assert result == expected def test_nonunique_raises(self): df = pd.DataFrame([[1, 2]], columns=['A', 'A']) with pytest.raises(ValueError): df.style with pytest.raises(ValueError): Styler(df) def test_caption(self): styler = Styler(self.df, caption='foo') result = styler.render() assert all(['caption' in result, 'foo' in result]) styler = self.df.style result = styler.set_caption('baz') assert styler is result assert styler.caption == 'baz' def test_uuid(self): styler = Styler(self.df, uuid='abc123') result = styler.render() assert 'abc123' in result styler = self.df.style result = styler.set_uuid('aaa') assert result is styler assert result.uuid == 'aaa' def test_unique_id(self): # See https://github.com/pandas-dev/pandas/issues/16780 df = pd.DataFrame({'a': [1, 3, 5, 6], 'b': [2, 4, 12, 21]}) result = df.style.render(uuid='test') assert 'test' in result ids = re.findall('id="(.*?)"', result) assert np.unique(ids).size == len(ids) def test_table_styles(self): style = [{'selector': 'th', 'props': [('foo', 'bar')]}] styler = Styler(self.df, table_styles=style) result = ' '.join(styler.render().split()) assert 'th { foo: bar; }' in result styler = self.df.style result = styler.set_table_styles(style) assert styler is result assert styler.table_styles == style def test_table_attributes(self): attributes = 'class="foo" data-bar' styler = Styler(self.df, table_attributes=attributes) result = styler.render() assert 'class="foo" data-bar' in result result = self.df.style.set_table_attributes(attributes).render() assert 'class="foo" data-bar' in result def test_precision(self): with pd.option_context('display.precision', 10): s = Styler(self.df) assert s.precision == 10 s = Styler(self.df, precision=2) assert s.precision == 2 s2 = s.set_precision(4) assert s is s2 assert s.precision == 4 def test_apply_none(self): def f(x): return pd.DataFrame(np.where(x == x.max(), 'color: red', ''), index=x.index, columns=x.columns) result = (pd.DataFrame([[1, 2], [3, 4]]) .style.apply(f, axis=None)._compute().ctx) assert result[(1, 1)] == ['color: red'] def test_trim(self): result = self.df.style.render() # trim=True assert result.count('#') == 0 result = self.df.style.highlight_max().render() assert result.count('#') == len(self.df.columns) def test_highlight_max(self): df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B']) # max(df) = min(-df) for max_ in [True, False]: if max_: attr = 'highlight_max' else: df = -df attr = 'highlight_min' result = getattr(df.style, attr)()._compute().ctx assert result[(1, 1)] == ['background-color: yellow'] result = getattr(df.style, attr)(color='green')._compute().ctx assert result[(1, 1)] == ['background-color: green'] result = getattr(df.style, attr)(subset='A')._compute().ctx assert result[(1, 0)] == ['background-color: yellow'] result = getattr(df.style, attr)(axis=0)._compute().ctx expected = {(1, 0): ['background-color: yellow'], (1, 1): ['background-color: yellow'], (0, 1): [''], (0, 0): ['']} assert result == expected result = getattr(df.style, attr)(axis=1)._compute().ctx expected = {(0, 1): ['background-color: yellow'], (1, 1): ['background-color: yellow'], (0, 0): [''], (1, 0): ['']} assert result == expected # separate since we can't negate the strs df['C'] = ['a', 'b'] result = df.style.highlight_max()._compute().ctx expected = {(1, 1): ['background-color: yellow']} result = df.style.highlight_min()._compute().ctx expected = {(0, 0): ['background-color: yellow']} def test_export(self): f = lambda x: 'color: red' if x > 0 else 'color: blue' g = lambda x, y, z: 'color: {z}'.format(z=z) \ if x > 0 else 'color: {z}'.format(z=z) style1 = self.styler style1.applymap(f)\ .applymap(g, y='a', z='b')\ .highlight_max() result = style1.export() style2 = self.df.style style2.use(result) assert style1._todo == style2._todo style2.render() def test_display_format(self): df = pd.DataFrame(np.random.random(size=(2, 2))) ctx = df.style.format("{:0.1f}")._translate() assert all(['display_value' in c for c in row] for row in ctx['body']) assert all([len(c['display_value']) <= 3 for c in row[1:]] for row in ctx['body']) assert len(ctx['body'][0][1]['display_value'].lstrip('-')) <= 3 def test_display_format_raises(self): df = pd.DataFrame(np.random.randn(2, 2)) with pytest.raises(TypeError): df.style.format(5) with pytest.raises(TypeError): df.style.format(True) def test_display_subset(self): df = pd.DataFrame([[.1234, .1234], [1.1234, 1.1234]], columns=['a', 'b']) ctx = df.style.format({"a": "{:0.1f}", "b": "{0:.2%}"}, subset=pd.IndexSlice[0, :])._translate() expected = '0.1' assert ctx['body'][0][1]['display_value'] == expected assert ctx['body'][1][1]['display_value'] == '1.1234' assert ctx['body'][0][2]['display_value'] == '12.34%' raw_11 = '1.1234' ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, :])._translate() assert ctx['body'][0][1]['display_value'] == expected assert ctx['body'][1][1]['display_value'] == raw_11 ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, :])._translate() assert ctx['body'][0][1]['display_value'] == expected assert ctx['body'][1][1]['display_value'] == raw_11 ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice['a'])._translate() assert ctx['body'][0][1]['display_value'] == expected assert ctx['body'][0][2]['display_value'] == '0.1234' ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, 'a'])._translate() assert ctx['body'][0][1]['display_value'] == expected assert ctx['body'][1][1]['display_value'] == raw_11 ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[[0, 1], ['a']])._translate() assert ctx['body'][0][1]['display_value'] == expected assert ctx['body'][1][1]['display_value'] == '1.1' assert ctx['body'][0][2]['display_value'] == '0.1234' assert ctx['body'][1][2]['display_value'] == '1.1234' def test_display_dict(self): df = pd.DataFrame([[.1234, .1234], [1.1234, 1.1234]], columns=['a', 'b']) ctx = df.style.format({"a": "{:0.1f}", "b": "{0:.2%}"})._translate() assert ctx['body'][0][1]['display_value'] == '0.1' assert ctx['body'][0][2]['display_value'] == '12.34%' df['c'] = ['aaa', 'bbb'] ctx = df.style.format({"a": "{:0.1f}", "c": str.upper})._translate() assert ctx['body'][0][1]['display_value'] == '0.1' assert ctx['body'][0][3]['display_value'] == 'AAA' def test_bad_apply_shape(self): df = pd.DataFrame([[1, 2], [3, 4]]) with pytest.raises(ValueError): df.style._apply(lambda x: 'x', subset=pd.IndexSlice[[0, 1], :]) with pytest.raises(ValueError): df.style._apply(lambda x: [''], subset=pd.IndexSlice[[0, 1], :]) with pytest.raises(ValueError): df.style._apply(lambda x: ['', '', '', '']) with pytest.raises(ValueError): df.style._apply(lambda x: ['', '', ''], subset=1) with pytest.raises(ValueError): df.style._apply(lambda x: ['', '', ''], axis=1) def test_apply_bad_return(self): def f(x): return '' df = pd.DataFrame([[1, 2], [3, 4]]) with pytest.raises(TypeError): df.style._apply(f, axis=None) def test_apply_bad_labels(self): def f(x): return pd.DataFrame(index=[1, 2], columns=['a', 'b']) df = pd.DataFrame([[1, 2], [3, 4]]) with pytest.raises(ValueError): df.style._apply(f, axis=None) def test_get_level_lengths(self): index = pd.MultiIndex.from_product([['a', 'b'], [0, 1, 2]]) expected = {(0, 0): 3, (0, 3): 3, (1, 0): 1, (1, 1): 1, (1, 2): 1, (1, 3): 1, (1, 4): 1, (1, 5): 1} result = _get_level_lengths(index) tm.assert_dict_equal(result, expected) def test_get_level_lengths_un_sorted(self): index = pd.MultiIndex.from_arrays([ [1, 1, 2, 1], ['a', 'b', 'b', 'd'] ]) expected = {(0, 0): 2, (0, 2): 1, (0, 3): 1, (1, 0): 1, (1, 1): 1, (1, 2): 1, (1, 3): 1} result = _get_level_lengths(index) tm.assert_dict_equal(result, expected) def test_mi_sparse(self): df = pd.DataFrame({'A': [1, 2]}, index=pd.MultiIndex.from_arrays([['a', 'a'], [0, 1]])) result = df.style._translate() body_0 = result['body'][0][0] expected_0 = { "value": "a", "display_value": "a", "is_visible": True, "type": "th", "attributes": ["rowspan=2"], "class": "row_heading level0 row0", "id": "level0_row0" } tm.assert_dict_equal(body_0, expected_0) body_1 = result['body'][0][1] expected_1 = { "value": 0, "display_value": 0, "is_visible": True, "type": "th", "class": "row_heading level1 row0", "id": "level1_row0" } tm.assert_dict_equal(body_1, expected_1) body_10 = result['body'][1][0] expected_10 = { "value": 'a', "display_value": 'a', "is_visible": False, "type": "th", "class": "row_heading level0 row1", "id": "level0_row1" } tm.assert_dict_equal(body_10, expected_10) head = result['head'][0] expected = [ {'type': 'th', 'class': 'blank', 'value': '', 'is_visible': True, "display_value": ''}, {'type': 'th', 'class': 'blank level0', 'value': '', 'is_visible': True, 'display_value': ''}, {'type': 'th', 'class': 'col_heading level0 col0', 'value': 'A', 'is_visible': True, 'display_value': 'A'}] assert head == expected def test_mi_sparse_disabled(self): with pd.option_context('display.multi_sparse', False): df = pd.DataFrame({'A': [1, 2]}, index=pd.MultiIndex.from_arrays([['a', 'a'], [0, 1]])) result = df.style._translate() body = result['body'] for row in body: assert 'attributes' not in row[0] def test_mi_sparse_index_names(self): df = pd.DataFrame({'A': [1, 2]}, index=pd.MultiIndex.from_arrays( [['a', 'a'], [0, 1]], names=['idx_level_0', 'idx_level_1']) ) result = df.style._translate() head = result['head'][1] expected = [{ 'class': 'index_name level0', 'value': 'idx_level_0', 'type': 'th'}, {'class': 'index_name level1', 'value': 'idx_level_1', 'type': 'th'}, {'class': 'blank', 'value': '', 'type': 'th'}] assert head == expected def test_mi_sparse_column_names(self): df = pd.DataFrame( np.arange(16).reshape(4, 4), index=pd.MultiIndex.from_arrays( [['a', 'a', 'b', 'a'], [0, 1, 1, 2]], names=['idx_level_0', 'idx_level_1']), columns=pd.MultiIndex.from_arrays( [['C1', 'C1', 'C2', 'C2'], [1, 0, 1, 0]], names=['col_0', 'col_1'] ) ) result = df.style._translate() head = result['head'][1] expected = [ {'class': 'blank', 'value': '', 'display_value': '', 'type': 'th', 'is_visible': True}, {'class': 'index_name level1', 'value': 'col_1', 'display_value': 'col_1', 'is_visible': True, 'type': 'th'}, {'class': 'col_heading level1 col0', 'display_value': 1, 'is_visible': True, 'type': 'th', 'value': 1}, {'class': 'col_heading level1 col1', 'display_value': 0, 'is_visible': True, 'type': 'th', 'value': 0}, {'class': 'col_heading level1 col2', 'display_value': 1, 'is_visible': True, 'type': 'th', 'value': 1}, {'class': 'col_heading level1 col3', 'display_value': 0, 'is_visible': True, 'type': 'th', 'value': 0}, ] assert head == expected def test_hide_single_index(self): # GH 14194 # single unnamed index ctx = self.df.style._translate() assert ctx['body'][0][0]['is_visible'] assert ctx['head'][0][0]['is_visible'] ctx2 = self.df.style.hide_index()._translate() assert not ctx2['body'][0][0]['is_visible'] assert not ctx2['head'][0][0]['is_visible'] # single named index ctx3 = self.df.set_index('A').style._translate() assert ctx3['body'][0][0]['is_visible'] assert len(ctx3['head']) == 2 # 2 header levels assert ctx3['head'][0][0]['is_visible'] ctx4 = self.df.set_index('A').style.hide_index()._translate() assert not ctx4['body'][0][0]['is_visible'] assert len(ctx4['head']) == 1 # only 1 header levels assert not ctx4['head'][0][0]['is_visible'] def test_hide_multiindex(self): # GH 14194 df = pd.DataFrame({'A': [1, 2]}, index=pd.MultiIndex.from_arrays( [['a', 'a'], [0, 1]], names=['idx_level_0', 'idx_level_1']) ) ctx1 = df.style._translate() # tests for 'a' and '0' assert ctx1['body'][0][0]['is_visible'] assert ctx1['body'][0][1]['is_visible'] # check for blank header rows assert ctx1['head'][0][0]['is_visible'] assert ctx1['head'][0][1]['is_visible'] ctx2 = df.style.hide_index()._translate() # tests for 'a' and '0' assert not ctx2['body'][0][0]['is_visible'] assert not ctx2['body'][0][1]['is_visible'] # check for blank header rows assert not ctx2['head'][0][0]['is_visible'] assert not ctx2['head'][0][1]['is_visible'] def test_hide_columns_single_level(self): # GH 14194 # test hiding single column ctx = self.df.style._translate() assert ctx['head'][0][1]['is_visible'] assert ctx['head'][0][1]['display_value'] == 'A' assert ctx['head'][0][2]['is_visible'] assert ctx['head'][0][2]['display_value'] == 'B' assert ctx['body'][0][1]['is_visible'] # col A, row 1 assert ctx['body'][1][2]['is_visible'] # col B, row 1 ctx = self.df.style.hide_columns('A')._translate() assert not ctx['head'][0][1]['is_visible'] assert not ctx['body'][0][1]['is_visible'] # col A, row 1 assert ctx['body'][1][2]['is_visible'] # col B, row 1 # test hiding mulitiple columns ctx = self.df.style.hide_columns(['A', 'B'])._translate() assert not ctx['head'][0][1]['is_visible'] assert not ctx['head'][0][2]['is_visible'] assert not ctx['body'][0][1]['is_visible'] # col A, row 1 assert not ctx['body'][1][2]['is_visible'] # col B, row 1 def test_hide_columns_mult_levels(self): # GH 14194 # setup dataframe with multiple column levels and indices i1 = pd.MultiIndex.from_arrays([['a', 'a'], [0, 1]], names=['idx_level_0', 'idx_level_1']) i2 = pd.MultiIndex.from_arrays([['b', 'b'], [0, 1]], names=['col_level_0', 'col_level_1']) df = pd.DataFrame([[1, 2], [3, 4]], index=i1, columns=i2) ctx = df.style._translate() # column headers assert ctx['head'][0][2]['is_visible'] assert ctx['head'][1][2]['is_visible'] assert ctx['head'][1][3]['display_value'] == 1 # indices assert ctx['body'][0][0]['is_visible'] # data assert ctx['body'][1][2]['is_visible'] assert ctx['body'][1][2]['display_value'] == 3 assert ctx['body'][1][3]['is_visible'] assert ctx['body'][1][3]['display_value'] == 4 # hide top column level, which hides both columns ctx = df.style.hide_columns('b')._translate() assert not ctx['head'][0][2]['is_visible'] # b assert not ctx['head'][1][2]['is_visible'] # 0 assert not ctx['body'][1][2]['is_visible'] # 3 assert ctx['body'][0][0]['is_visible'] # index # hide first column only ctx = df.style.hide_columns([('b', 0)])._translate() assert ctx['head'][0][2]['is_visible'] # b assert not ctx['head'][1][2]['is_visible'] # 0 assert not ctx['body'][1][2]['is_visible'] # 3 assert ctx['body'][1][3]['is_visible'] assert ctx['body'][1][3]['display_value'] == 4 # hide second column and index ctx = df.style.hide_columns([('b', 1)]).hide_index()._translate() assert not ctx['body'][0][0]['is_visible'] # index assert ctx['head'][0][2]['is_visible'] # b assert ctx['head'][1][2]['is_visible'] # 0 assert not ctx['head'][1][3]['is_visible'] # 1 assert not ctx['body'][1][3]['is_visible'] # 4 assert ctx['body'][1][2]['is_visible'] assert ctx['body'][1][2]['display_value'] == 3 def test_pipe(self): def set_caption_from_template(styler, a, b): return styler.set_caption( 'Dataframe with a = {a} and b = {b}'.format(a=a, b=b)) styler = self.df.style.pipe(set_caption_from_template, 'A', b='B') assert 'Dataframe with a = A and b = B' in styler.render() # Test with an argument that is a (callable, keyword_name) pair. def f(a, b, styler): return (a, b, styler) styler = self.df.style result = styler.pipe((f, 'styler'), a=1, b=2) assert result == (1, 2, styler) @td.skip_if_no_mpl class TestStylerMatplotlibDep: def test_background_gradient(self): df = pd.DataFrame([[1, 2], [2, 4]], columns=['A', 'B']) for c_map in [None, 'YlOrRd']: result = df.style.background_gradient(cmap=c_map)._compute().ctx assert all("#" in x[0] for x in result.values()) assert result[(0, 0)] == result[(0, 1)] assert result[(1, 0)] == result[(1, 1)] result = df.style.background_gradient( subset=pd.IndexSlice[1, 'A'])._compute().ctx assert result[(1, 0)] == ['background-color: #fff7fb', 'color: #000000'] @pytest.mark.parametrize( 'c_map,expected', [ (None, { (0, 0): ['background-color: #440154', 'color: #f1f1f1'], (1, 0): ['background-color: #fde725', 'color: #000000']}), ('YlOrRd', { (0, 0): ['background-color: #ffffcc', 'color: #000000'], (1, 0): ['background-color: #800026', 'color: #f1f1f1']})]) def test_text_color_threshold(self, c_map, expected): df = pd.DataFrame([1, 2], columns=['A']) result = df.style.background_gradient(cmap=c_map)._compute().ctx assert result == expected @pytest.mark.parametrize("text_color_threshold", [1.1, '1', -1, [2, 2]]) def test_text_color_threshold_raises(self, text_color_threshold): df = pd.DataFrame([[1, 2], [2, 4]], columns=['A', 'B']) msg = "`text_color_threshold` must be a value from 0 to 1." with pytest.raises(ValueError, match=msg): df.style.background_gradient( text_color_threshold=text_color_threshold)._compute() @td.skip_if_no_mpl def test_background_gradient_axis(self): df = pd.DataFrame([[1, 2], [2, 4]], columns=['A', 'B']) low = ['background-color: #f7fbff', 'color: #000000'] high = ['background-color: #08306b', 'color: #f1f1f1'] mid = ['background-color: #abd0e6', 'color: #000000'] result = df.style.background_gradient(cmap='Blues', axis=0)._compute().ctx assert result[(0, 0)] == low assert result[(0, 1)] == low assert result[(1, 0)] == high assert result[(1, 1)] == high result = df.style.background_gradient(cmap='Blues', axis=1)._compute().ctx assert result[(0, 0)] == low assert result[(0, 1)] == high assert result[(1, 0)] == low assert result[(1, 1)] == high result = df.style.background_gradient(cmap='Blues', axis=None)._compute().ctx assert result[(0, 0)] == low assert result[(0, 1)] == mid assert result[(1, 0)] == mid assert result[(1, 1)] == high def test_block_names(): # catch accidental removal of a block expected = { 'before_style', 'style', 'table_styles', 'before_cellstyle', 'cellstyle', 'before_table', 'table', 'caption', 'thead', 'tbody', 'after_table', 'before_head_rows', 'head_tr', 'after_head_rows', 'before_rows', 'tr', 'after_rows', } result = set(Styler.template.blocks) assert result == expected def test_from_custom_template(tmpdir): p = tmpdir.mkdir("templates").join("myhtml.tpl") p.write(textwrap.dedent("""\ {% extends "html.tpl" %} {% block table %} <h1>{{ table_title|default("My Table") }}</h1> {{ super() }} {% endblock table %}""")) result = Styler.from_custom_template(str(tmpdir.join('templates')), 'myhtml.tpl') assert issubclass(result, Styler) assert result.env is not Styler.env assert result.template is not Styler.template styler = result(pd.DataFrame({"A": [1, 2]})) assert styler.render()
bsd-3-clause
slisson/intellij-community
python/lib/Lib/distutils/msvccompiler.py
81
23450
"""distutils.msvccompiler Contains MSVCCompiler, an implementation of the abstract CCompiler class for the Microsoft Visual Studio. """ # Written by Perry Stoll # hacked by Robin Becker and Thomas Heller to do a better job of # finding DevStudio (through the registry) # This module should be kept compatible with Python 2.1. __revision__ = "$Id: msvccompiler.py 54645 2007-04-01 18:29:47Z neal.norwitz $" import sys, os, string from distutils.errors import \ DistutilsExecError, DistutilsPlatformError, \ CompileError, LibError, LinkError from distutils.ccompiler import \ CCompiler, gen_preprocess_options, gen_lib_options from distutils import log _can_read_reg = 0 try: import _winreg _can_read_reg = 1 hkey_mod = _winreg RegOpenKeyEx = _winreg.OpenKeyEx RegEnumKey = _winreg.EnumKey RegEnumValue = _winreg.EnumValue RegError = _winreg.error except ImportError: try: import win32api import win32con _can_read_reg = 1 hkey_mod = win32con RegOpenKeyEx = win32api.RegOpenKeyEx RegEnumKey = win32api.RegEnumKey RegEnumValue = win32api.RegEnumValue RegError = win32api.error except ImportError: log.info("Warning: Can't read registry to find the " "necessary compiler setting\n" "Make sure that Python modules _winreg, " "win32api or win32con are installed.") pass if _can_read_reg: HKEYS = (hkey_mod.HKEY_USERS, hkey_mod.HKEY_CURRENT_USER, hkey_mod.HKEY_LOCAL_MACHINE, hkey_mod.HKEY_CLASSES_ROOT) def read_keys(base, key): """Return list of registry keys.""" try: handle = RegOpenKeyEx(base, key) except RegError: return None L = [] i = 0 while 1: try: k = RegEnumKey(handle, i) except RegError: break L.append(k) i = i + 1 return L def read_values(base, key): """Return dict of registry keys and values. All names are converted to lowercase. """ try: handle = RegOpenKeyEx(base, key) except RegError: return None d = {} i = 0 while 1: try: name, value, type = RegEnumValue(handle, i) except RegError: break name = name.lower() d[convert_mbcs(name)] = convert_mbcs(value) i = i + 1 return d def convert_mbcs(s): enc = getattr(s, "encode", None) if enc is not None: try: s = enc("mbcs") except UnicodeError: pass return s class MacroExpander: def __init__(self, version): self.macros = {} self.load_macros(version) def set_macro(self, macro, path, key): for base in HKEYS: d = read_values(base, path) if d: self.macros["$(%s)" % macro] = d[key] break def load_macros(self, version): vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir") self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir") net = r"Software\Microsoft\.NETFramework" self.set_macro("FrameworkDir", net, "installroot") try: if version > 7.0: self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") except KeyError, exc: # raise DistutilsPlatformError, \ ("""Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""") p = r"Software\Microsoft\NET Framework Setup\Product" for base in HKEYS: try: h = RegOpenKeyEx(base, p) except RegError: continue key = RegEnumKey(h, 0) d = read_values(base, r"%s\%s" % (p, key)) self.macros["$(FrameworkVersion)"] = d["version"] def sub(self, s): for k, v in self.macros.items(): s = string.replace(s, k, v) return s def get_build_version(): """Return the version of MSVC that was used to build Python. For Python 2.3 and up, the version number is included in sys.version. For earlier versions, assume the compiler is MSVC 6. """ prefix = "MSC v." i = string.find(sys.version, prefix) if i == -1: return 6 i = i + len(prefix) s, rest = sys.version[i:].split(" ", 1) majorVersion = int(s[:-2]) - 6 minorVersion = int(s[2:3]) / 10.0 # I don't think paths are affected by minor version in version 6 if majorVersion == 6: minorVersion = 0 if majorVersion >= 6: return majorVersion + minorVersion # else we don't know what version of the compiler this is return None def get_build_architecture(): """Return the processor architecture. Possible results are "Intel", "Itanium", or "AMD64". """ prefix = " bit (" i = string.find(sys.version, prefix) if i == -1: return "Intel" j = string.find(sys.version, ")", i) return sys.version[i+len(prefix):j] def normalize_and_reduce_paths(paths): """Return a list of normalized paths with duplicates removed. The current order of paths is maintained. """ # Paths are normalized so things like: /a and /a/ aren't both preserved. reduced_paths = [] for p in paths: np = os.path.normpath(p) # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set. if np not in reduced_paths: reduced_paths.append(np) return reduced_paths class MSVCCompiler (CCompiler) : """Concrete class that implements an interface to Microsoft Visual C++, as defined by the CCompiler abstract class.""" compiler_type = 'msvc' # Just set this so CCompiler's constructor doesn't barf. We currently # don't use the 'set_executables()' bureaucracy provided by CCompiler, # as it really isn't necessary for this sort of single-compiler class. # Would be nice to have a consistent interface with UnixCCompiler, # though, so it's worth thinking about. executables = {} # Private class data (need to distinguish C from C++ source for compiler) _c_extensions = ['.c'] _cpp_extensions = ['.cc', '.cpp', '.cxx'] _rc_extensions = ['.rc'] _mc_extensions = ['.mc'] # Needed for the filename generation methods provided by the # base class, CCompiler. src_extensions = (_c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions) res_extension = '.res' obj_extension = '.obj' static_lib_extension = '.lib' shared_lib_extension = '.dll' static_lib_format = shared_lib_format = '%s%s' exe_extension = '.exe' def __init__ (self, verbose=0, dry_run=0, force=0): CCompiler.__init__ (self, verbose, dry_run, force) self.__version = get_build_version() self.__arch = get_build_architecture() if self.__arch == "Intel": # x86 if self.__version >= 7: self.__root = r"Software\Microsoft\VisualStudio" self.__macros = MacroExpander(self.__version) else: self.__root = r"Software\Microsoft\Devstudio" self.__product = "Visual Studio version %s" % self.__version else: # Win64. Assume this was built with the platform SDK self.__product = "Microsoft SDK compiler %s" % (self.__version + 6) self.initialized = False def initialize(self): self.__paths = [] if os.environ.has_key("DISTUTILS_USE_SDK") and os.environ.has_key("MSSdk") and self.find_exe("cl.exe"): # Assume that the SDK set up everything alright; don't try to be # smarter self.cc = "cl.exe" self.linker = "link.exe" self.lib = "lib.exe" self.rc = "rc.exe" self.mc = "mc.exe" else: self.__paths = self.get_msvc_paths("path") if len (self.__paths) == 0: raise DistutilsPlatformError, \ ("Python was built with %s, " "and extensions need to be built with the same " "version of the compiler, but it isn't installed." % self.__product) self.cc = self.find_exe("cl.exe") self.linker = self.find_exe("link.exe") self.lib = self.find_exe("lib.exe") self.rc = self.find_exe("rc.exe") # resource compiler self.mc = self.find_exe("mc.exe") # message compiler self.set_path_env_var('lib') self.set_path_env_var('include') # extend the MSVC path with the current path try: for p in string.split(os.environ['path'], ';'): self.__paths.append(p) except KeyError: pass self.__paths = normalize_and_reduce_paths(self.__paths) os.environ['path'] = string.join(self.__paths, ';') self.preprocess_options = None if self.__arch == "Intel": self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GX' , '/DNDEBUG'] self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GX', '/Z7', '/D_DEBUG'] else: # Win64 self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GS-' , '/DNDEBUG'] self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-', '/Z7', '/D_DEBUG'] self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO'] if self.__version >= 7: self.ldflags_shared_debug = [ '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG' ] else: self.ldflags_shared_debug = [ '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG' ] self.ldflags_static = [ '/nologo'] self.initialized = True # -- Worker methods ------------------------------------------------ def object_filenames (self, source_filenames, strip_dir=0, output_dir=''): # Copied from ccompiler.py, extended to return .res as 'object'-file # for .rc input file if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: (base, ext) = os.path.splitext (src_name) base = os.path.splitdrive(base)[1] # Chop off the drive base = base[os.path.isabs(base):] # If abs, chop off leading / if ext not in self.src_extensions: # Better to raise an exception instead of silently continuing # and later complain about sources and targets having # different lengths raise CompileError ("Don't know how to compile %s" % src_name) if strip_dir: base = os.path.basename (base) if ext in self._rc_extensions: obj_names.append (os.path.join (output_dir, base + self.res_extension)) elif ext in self._mc_extensions: obj_names.append (os.path.join (output_dir, base + self.res_extension)) else: obj_names.append (os.path.join (output_dir, base + self.obj_extension)) return obj_names # object_filenames () def compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): if not self.initialized: self.initialize() macros, objects, extra_postargs, pp_opts, build = \ self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) compile_opts = extra_preargs or [] compile_opts.append ('/c') if debug: compile_opts.extend(self.compile_options_debug) else: compile_opts.extend(self.compile_options) for obj in objects: try: src, ext = build[obj] except KeyError: continue if debug: # pass the full pathname to MSVC in debug mode, # this allows the debugger to find the source file # without asking the user to browse for it src = os.path.abspath(src) if ext in self._c_extensions: input_opt = "/Tc" + src elif ext in self._cpp_extensions: input_opt = "/Tp" + src elif ext in self._rc_extensions: # compile .RC to .RES file input_opt = src output_opt = "/fo" + obj try: self.spawn ([self.rc] + pp_opts + [output_opt] + [input_opt]) except DistutilsExecError, msg: raise CompileError, msg continue elif ext in self._mc_extensions: # Compile .MC to .RC file to .RES file. # * '-h dir' specifies the directory for the # generated include file # * '-r dir' specifies the target directory of the # generated RC file and the binary message resource # it includes # # For now (since there are no options to change this), # we use the source-directory for the include file and # the build directory for the RC file and message # resources. This works at least for win32all. h_dir = os.path.dirname (src) rc_dir = os.path.dirname (obj) try: # first compile .MC to .RC and .H file self.spawn ([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src]) base, _ = os.path.splitext (os.path.basename (src)) rc_file = os.path.join (rc_dir, base + '.rc') # then compile .RC to .RES file self.spawn ([self.rc] + ["/fo" + obj] + [rc_file]) except DistutilsExecError, msg: raise CompileError, msg continue else: # how to handle this file? raise CompileError ( "Don't know how to compile %s to %s" % \ (src, obj)) output_opt = "/Fo" + obj try: self.spawn ([self.cc] + compile_opts + pp_opts + [input_opt, output_opt] + extra_postargs) except DistutilsExecError, msg: raise CompileError, msg return objects # compile () def create_static_lib (self, objects, output_libname, output_dir=None, debug=0, target_lang=None): if not self.initialized: self.initialize() (objects, output_dir) = self._fix_object_args (objects, output_dir) output_filename = \ self.library_filename (output_libname, output_dir=output_dir) if self._need_link (objects, output_filename): lib_args = objects + ['/OUT:' + output_filename] if debug: pass # XXX what goes here? try: self.spawn ([self.lib] + lib_args) except DistutilsExecError, msg: raise LibError, msg else: log.debug("skipping %s (up-to-date)", output_filename) # create_static_lib () def link (self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): if not self.initialized: self.initialize() (objects, output_dir) = self._fix_object_args (objects, output_dir) (libraries, library_dirs, runtime_library_dirs) = \ self._fix_lib_args (libraries, library_dirs, runtime_library_dirs) if runtime_library_dirs: self.warn ("I don't know what to do with 'runtime_library_dirs': " + str (runtime_library_dirs)) lib_opts = gen_lib_options (self, library_dirs, runtime_library_dirs, libraries) if output_dir is not None: output_filename = os.path.join (output_dir, output_filename) if self._need_link (objects, output_filename): if target_desc == CCompiler.EXECUTABLE: if debug: ldflags = self.ldflags_shared_debug[1:] else: ldflags = self.ldflags_shared[1:] else: if debug: ldflags = self.ldflags_shared_debug else: ldflags = self.ldflags_shared export_opts = [] for sym in (export_symbols or []): export_opts.append("/EXPORT:" + sym) ld_args = (ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]) # The MSVC linker generates .lib and .exp files, which cannot be # suppressed by any linker switches. The .lib files may even be # needed! Make sure they are generated in the temporary build # directory. Since they have different names for debug and release # builds, they can go into the same directory. if export_symbols is not None: (dll_name, dll_ext) = os.path.splitext( os.path.basename(output_filename)) implib_file = os.path.join( os.path.dirname(objects[0]), self.library_filename(dll_name)) ld_args.append ('/IMPLIB:' + implib_file) if extra_preargs: ld_args[:0] = extra_preargs if extra_postargs: ld_args.extend(extra_postargs) self.mkpath (os.path.dirname (output_filename)) try: self.spawn ([self.linker] + ld_args) except DistutilsExecError, msg: raise LinkError, msg else: log.debug("skipping %s (up-to-date)", output_filename) # link () # -- Miscellaneous methods ----------------------------------------- # These are all used by the 'gen_lib_options() function, in # ccompiler.py. def library_dir_option (self, dir): return "/LIBPATH:" + dir def runtime_library_dir_option (self, dir): raise DistutilsPlatformError, \ "don't know how to set runtime library search path for MSVC++" def library_option (self, lib): return self.library_filename (lib) def find_library_file (self, dirs, lib, debug=0): # Prefer a debugging library if found (and requested), but deal # with it if we don't have one. if debug: try_names = [lib + "_d", lib] else: try_names = [lib] for dir in dirs: for name in try_names: libfile = os.path.join(dir, self.library_filename (name)) if os.path.exists(libfile): return libfile else: # Oops, didn't find it in *any* of 'dirs' return None # find_library_file () # Helper methods for using the MSVC registry settings def find_exe(self, exe): """Return path to an MSVC executable program. Tries to find the program in several places: first, one of the MSVC program search paths from the registry; next, the directories in the PATH environment variable. If any of those work, return an absolute path that is known to exist. If none of them work, just return the original program name, 'exe'. """ for p in self.__paths: fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn # didn't find it; try existing path for p in string.split(os.environ['Path'],';'): fn = os.path.join(os.path.abspath(p),exe) if os.path.isfile(fn): return fn return exe def get_msvc_paths(self, path, platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings. The list will be empty if unable to access the registry or appropriate registry keys not found. """ if not _can_read_reg: return [] path = path + " dirs" if self.__version >= 7: key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories" % (self.__root, self.__version)) else: key = (r"%s\6.0\Build System\Components\Platforms" r"\Win32 (%s)\Directories" % (self.__root, platform)) for base in HKEYS: d = read_values(base, key) if d: if self.__version >= 7: return string.split(self.__macros.sub(d[path]), ";") else: return string.split(d[path], ";") # MSVC 6 seems to create the registry entries we need only when # the GUI is run. if self.__version == 6: for base in HKEYS: if read_values(base, r"%s\6.0" % self.__root) is not None: self.warn("It seems you have Visual Studio 6 installed, " "but the expected registry settings are not present.\n" "You must at least run the Visual Studio GUI once " "so that these entries are created.") break return [] def set_path_env_var(self, name): """Set environment variable 'name' to an MSVC path type value. This is equivalent to a SET command prior to execution of spawned commands. """ if name == "lib": p = self.get_msvc_paths("library") else: p = self.get_msvc_paths(name) if p: os.environ[name] = string.join(p, ';')
apache-2.0
zhjunlang/kbengine
kbe/res/scripts/common/Lib/distutils/tests/test_install_data.py
147
2603
"""Tests for distutils.command.install_data.""" import sys import os import unittest import getpass from distutils.command.install_data import install_data from distutils.tests import support from test.support import run_unittest class InstallDataTestCase(support.TempdirManager, support.LoggingSilencer, support.EnvironGuard, unittest.TestCase): def test_simple_run(self): pkg_dir, dist = self.create_dist() cmd = install_data(dist) cmd.install_dir = inst = os.path.join(pkg_dir, 'inst') # data_files can contain # - simple files # - a tuple with a path, and a list of file one = os.path.join(pkg_dir, 'one') self.write_file(one, 'xxx') inst2 = os.path.join(pkg_dir, 'inst2') two = os.path.join(pkg_dir, 'two') self.write_file(two, 'xxx') cmd.data_files = [one, (inst2, [two])] self.assertEqual(cmd.get_inputs(), [one, (inst2, [two])]) # let's run the command cmd.ensure_finalized() cmd.run() # let's check the result self.assertEqual(len(cmd.get_outputs()), 2) rtwo = os.path.split(two)[-1] self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) rone = os.path.split(one)[-1] self.assertTrue(os.path.exists(os.path.join(inst, rone))) cmd.outfiles = [] # let's try with warn_dir one cmd.warn_dir = 1 cmd.ensure_finalized() cmd.run() # let's check the result self.assertEqual(len(cmd.get_outputs()), 2) self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) self.assertTrue(os.path.exists(os.path.join(inst, rone))) cmd.outfiles = [] # now using root and empty dir cmd.root = os.path.join(pkg_dir, 'root') inst3 = os.path.join(cmd.install_dir, 'inst3') inst4 = os.path.join(pkg_dir, 'inst4') three = os.path.join(cmd.install_dir, 'three') self.write_file(three, 'xx') cmd.data_files = [one, (inst2, [two]), ('inst3', [three]), (inst4, [])] cmd.ensure_finalized() cmd.run() # let's check the result self.assertEqual(len(cmd.get_outputs()), 4) self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) self.assertTrue(os.path.exists(os.path.join(inst, rone))) def test_suite(): return unittest.makeSuite(InstallDataTestCase) if __name__ == "__main__": run_unittest(test_suite())
lgpl-3.0
BioGRID/BioGRID-Annotation
EG_parseGeneHistoryToStaging.py
2
1105
# Parses Entrez Gene gene_history file format # into staging area table import sys, string import MySQLdb import Database import gzip import Config with Database.db as cursor : cursor.execute( "TRUNCATE TABLE " + Config.DB_STAGING + ".entrez_gene_history" ) insertCount = 0 with gzip.open( Config.EG_GENEHISTORY, 'r' ) as historyFile : for line in historyFile.readlines( ) : # Ignore Header Line if "#" == line[0] : continue splitLine = line.strip( ).split( "\t" ) if "-" == splitLine[1] : splitLine[1] = "-1" if "-" == splitLine[2] : splitLine[2] = "-1" if "-" == splitLine[3] : splitLine[3] = "-1" formattedEntries = ','.join( ['%s'] * len( splitLine ) ) query = "INSERT INTO " + Config.DB_STAGING + ".entrez_gene_history VALUES( %s, NOW( ) )" query = query % formattedEntries cursor.execute( query, tuple( splitLine ) ) insertCount = insertCount + 1 if 0 == (insertCount % Config.DB_COMMIT_COUNT ) : Database.db.commit( ) Database.db.commit( ) sys.exit( )
mit
roadmapper/ansible
lib/ansible/modules/system/aix_devices.py
44
9870
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, 2018 Kairo Araujo <kairo@kairo.eti.br> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- author: - Kairo Araujo (@kairoaraujo) module: aix_devices short_description: Manages AIX devices description: - This module discovers, defines, removes and modifies attributes of AIX devices. version_added: '2.8' options: attributes: description: - A list of device attributes. type: dict device: description: - The name of the device. - C(all) is valid to rescan C(available) all devices (AIX cfgmgr command). type: str required: true force: description: - Forces action. type: bool default: no recursive: description: - Removes or defines a device and children devices. type: bool default: no state: description: - Controls the device state. - C(available) (alias C(present)) rescan a specific device or all devices (when C(device) is not specified). - C(removed) (alias C(absent) removes a device. - C(defined) changes device to Defined state. type: str choices: [ available, defined, removed ] default: available ''' EXAMPLES = r''' - name: Scan new devices aix_devices: device: all state: available - name: Scan new virtual devices (vio0) aix_devices: device: vio0 state: available - name: Removing IP alias to en0 aix_devices: device: en0 attributes: delalias4: 10.0.0.100,255.255.255.0 - name: Removes ent2 aix_devices: device: ent2 state: removed - name: Put device en2 in Defined aix_devices: device: en2 state: defined - name: Removes ent4 (inexistent). aix_devices: device: ent4 state: removed - name: Put device en4 in Defined (inexistent) aix_devices: device: en4 state: defined - name: Put vscsi1 and children devices in Defined state. aix_devices: device: vscsi1 recursive: yes state: defined - name: Removes vscsi1 and children devices. aix_devices: device: vscsi1 recursive: yes state: removed - name: Changes en1 mtu to 9000 and disables arp. aix_devices: device: en1 attributes: mtu: 900 arp: off state: available - name: Configure IP, netmask and set en1 up. aix_devices: device: en1 attributes: netaddr: 192.168.0.100 netmask: 255.255.255.0 state: up state: available - name: Adding IP alias to en0 aix_devices: device: en0 attributes: alias4: 10.0.0.100,255.255.255.0 state: available ''' RETURN = r''' # ''' from ansible.module_utils.basic import AnsibleModule def _check_device(module, device): """ Check if device already exists and the state. Args: module: Ansible module. device: device to be checked. Returns: bool, device state """ lsdev_cmd = module.get_bin_path('lsdev', True) rc, lsdev_out, err = module.run_command(["%s" % lsdev_cmd, '-C', '-l', "%s" % device]) if rc != 0: module.fail_json(msg="Failed to run lsdev", rc=rc, err=err) if lsdev_out: device_state = lsdev_out.split()[1] return True, device_state device_state = None return False, device_state def _check_device_attr(module, device, attr): """ Args: module: Ansible module. device: device to check attributes. attr: attribute to be checked. Returns: """ lsattr_cmd = module.get_bin_path('lsattr', True) rc, lsattr_out, err = module.run_command(["%s" % lsattr_cmd, '-El', "%s" % device, '-a', "%s" % attr]) hidden_attrs = ['delalias4', 'delalias6'] if rc == 255: if attr in hidden_attrs: current_param = '' else: current_param = None return current_param elif rc != 0: module.fail_json(msg="Failed to run lsattr: %s" % err, rc=rc, err=err) current_param = lsattr_out.split()[1] return current_param def discover_device(module, device): """ Discover AIX devices.""" cfgmgr_cmd = module.get_bin_path('cfgmgr', True) if device is not None: device = "-l %s" % device else: device = '' changed = True msg = '' if not module.check_mode: rc, cfgmgr_out, err = module.run_command(["%s" % cfgmgr_cmd, "%s" % device]) changed = True msg = cfgmgr_out return changed, msg def change_device_attr(module, attributes, device, force): """ Change AIX device attribute. """ attr_changed = [] attr_not_changed = [] attr_invalid = [] chdev_cmd = module.get_bin_path('chdev', True) for attr in list(attributes.keys()): new_param = attributes[attr] current_param = _check_device_attr(module, device, attr) if current_param is None: attr_invalid.append(attr) elif current_param != new_param: if force: cmd = ["%s" % chdev_cmd, '-l', "%s" % device, '-a', "%s=%s" % (attr, attributes[attr]), "%s" % force] else: cmd = ["%s" % chdev_cmd, '-l', "%s" % device, '-a', "%s=%s" % (attr, attributes[attr])] if not module.check_mode: rc, chdev_out, err = module.run_command(cmd) if rc != 0: module.exit_json(msg="Failed to run chdev.", rc=rc, err=err) attr_changed.append(attributes[attr]) else: attr_not_changed.append(attributes[attr]) if len(attr_changed) > 0: changed = True attr_changed_msg = "Attributes changed: %s. " % ','.join(attr_changed) else: changed = False attr_changed_msg = '' if len(attr_not_changed) > 0: attr_not_changed_msg = "Attributes already set: %s. " % ','.join(attr_not_changed) else: attr_not_changed_msg = '' if len(attr_invalid) > 0: attr_invalid_msg = "Invalid attributes: %s " % ', '.join(attr_invalid) else: attr_invalid_msg = '' msg = "%s%s%s" % (attr_changed_msg, attr_not_changed_msg, attr_invalid_msg) return changed, msg def remove_device(module, device, force, recursive, state): """ Puts device in defined state or removes device. """ state_opt = { 'removed': '-d', 'absent': '-d', 'defined': '' } recursive_opt = { True: '-R', False: '' } recursive = recursive_opt[recursive] state = state_opt[state] changed = True msg = '' rmdev_cmd = module.get_bin_path('rmdev', True) if not module.check_mode: if state: rc, rmdev_out, err = module.run_command(["%s" % rmdev_cmd, "-l", "%s" % device, "%s" % recursive, "%s" % force]) else: rc, rmdev_out, err = module.run_command(["%s" % rmdev_cmd, "-l", "%s" % device, "%s" % recursive]) if rc != 0: module.fail_json(msg="Failed to run rmdev", rc=rc, err=err) msg = rmdev_out return changed, msg def main(): module = AnsibleModule( argument_spec=dict( attributes=dict(type='dict'), device=dict(type='str'), force=dict(type='bool', default=False), recursive=dict(type='bool', default=False), state=dict(type='str', default='available', choices=['available', 'defined', 'removed']), ), supports_check_mode=True, ) force_opt = { True: '-f', False: '', } attributes = module.params['attributes'] device = module.params['device'] force = force_opt[module.params['force']] recursive = module.params['recursive'] state = module.params['state'] result = dict( changed=False, msg='', ) if state == 'available' or state == 'present': if attributes: # change attributes on device device_status, device_state = _check_device(module, device) if device_status: result['changed'], result['msg'] = change_device_attr(module, attributes, device, force) else: result['msg'] = "Device %s does not exist." % device else: # discovery devices (cfgmgr) if device and device != 'all': device_status, device_state = _check_device(module, device) if device_status: # run cfgmgr on specific device result['changed'], result['msg'] = discover_device(module, device) else: result['msg'] = "Device %s does not exist." % device else: result['changed'], result['msg'] = discover_device(module, device) elif state == 'removed' or state == 'absent' or state == 'defined': if not device: result['msg'] = "device is required to removed or defined state." else: # Remove device check_device, device_state = _check_device(module, device) if check_device: if state == 'defined' and device_state == 'Defined': result['changed'] = False result['msg'] = 'Device %s already in Defined' % device else: result['changed'], result['msg'] = remove_device(module, device, force, recursive, state) else: result['msg'] = "Device %s does not exist." % device else: result['msg'] = "Unexpected state %s." % state module.fail_json(**result) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
sander76/home-assistant
homeassistant/components/linode/switch.py
5
2884
"""Support for interacting with Linode nodes.""" import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity import homeassistant.helpers.config_validation as cv from . import ( ATTR_CREATED, ATTR_IPV4_ADDRESS, ATTR_IPV6_ADDRESS, ATTR_MEMORY, ATTR_NODE_ID, ATTR_NODE_NAME, ATTR_REGION, ATTR_VCPUS, CONF_NODES, DATA_LINODE, ) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Node" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_NODES): vol.All(cv.ensure_list, [cv.string])} ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Linode Node switch.""" linode = hass.data.get(DATA_LINODE) nodes = config.get(CONF_NODES) dev = [] for node in nodes: node_id = linode.get_node_id(node) if node_id is None: _LOGGER.error("Node %s is not available", node) return dev.append(LinodeSwitch(linode, node_id)) add_entities(dev, True) class LinodeSwitch(SwitchEntity): """Representation of a Linode Node switch.""" def __init__(self, li, node_id): """Initialize a new Linode sensor.""" self._linode = li self._node_id = node_id self.data = None self._state = None self._attrs = {} self._name = None @property def name(self): """Return the name of the switch.""" return self._name @property def is_on(self): """Return true if switch is on.""" return self._state @property def extra_state_attributes(self): """Return the state attributes of the Linode Node.""" return self._attrs def turn_on(self, **kwargs): """Boot-up the Node.""" if self.data.status != "running": self.data.boot() def turn_off(self, **kwargs): """Shutdown the nodes.""" if self.data.status == "running": self.data.shutdown() def update(self): """Get the latest data from the device and update the data.""" self._linode.update() if self._linode.data is not None: for node in self._linode.data: if node.id == self._node_id: self.data = node if self.data is not None: self._state = self.data.status == "running" self._attrs = { ATTR_CREATED: self.data.created, ATTR_NODE_ID: self.data.id, ATTR_NODE_NAME: self.data.label, ATTR_IPV4_ADDRESS: self.data.ipv4, ATTR_IPV6_ADDRESS: self.data.ipv6, ATTR_MEMORY: self.data.specs.memory, ATTR_REGION: self.data.region.country, ATTR_VCPUS: self.data.specs.vcpus, } self._name = self.data.label
apache-2.0
kastriothaliti/techstitution
venv/lib/python2.7/site-packages/pip/vcs/git.py
340
11197
from __future__ import absolute_import import logging import tempfile import os.path from pip.compat import samefile from pip.exceptions import BadCommand from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._vendor.packaging.version import parse as parse_version from pip.utils import display_path, rmtree from pip.vcs import vcs, VersionControl urlsplit = urllib_parse.urlsplit urlunsplit = urllib_parse.urlunsplit logger = logging.getLogger(__name__) class Git(VersionControl): name = 'git' dirname = '.git' repo_name = 'clone' schemes = ( 'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file', ) def __init__(self, url=None, *args, **kwargs): # Works around an apparent Git bug # (see http://article.gmane.org/gmane.comp.version-control.git/146500) if url: scheme, netloc, path, query, fragment = urlsplit(url) if scheme.endswith('file'): initial_slashes = path[:-len(path.lstrip('/'))] newpath = ( initial_slashes + urllib_request.url2pathname(path) .replace('\\', '/').lstrip('/') ) url = urlunsplit((scheme, netloc, newpath, query, fragment)) after_plus = scheme.find('+') + 1 url = scheme[:after_plus] + urlunsplit( (scheme[after_plus:], netloc, newpath, query, fragment), ) super(Git, self).__init__(url, *args, **kwargs) def get_git_version(self): VERSION_PFX = 'git version ' version = self.run_command(['version'], show_stdout=False) if version.startswith(VERSION_PFX): version = version[len(VERSION_PFX):] else: version = '' # get first 3 positions of the git version becasue # on windows it is x.y.z.windows.t, and this parses as # LegacyVersion which always smaller than a Version. version = '.'.join(version.split('.')[:3]) return parse_version(version) def export(self, location): """Export the Git repository at the url to the destination location""" temp_dir = tempfile.mkdtemp('-export', 'pip-') self.unpack(temp_dir) try: if not location.endswith('/'): location = location + '/' self.run_command( ['checkout-index', '-a', '-f', '--prefix', location], show_stdout=False, cwd=temp_dir) finally: rmtree(temp_dir) def check_rev_options(self, rev, dest, rev_options): """Check the revision options before checkout to compensate that tags and branches may need origin/ as a prefix. Returns the SHA1 of the branch or tag if found. """ revisions = self.get_short_refs(dest) origin_rev = 'origin/%s' % rev if origin_rev in revisions: # remote branch return [revisions[origin_rev]] elif rev in revisions: # a local tag or branch name return [revisions[rev]] else: logger.warning( "Could not find a tag or branch '%s', assuming commit.", rev, ) return rev_options def check_version(self, dest, rev_options): """ Compare the current sha to the ref. ref may be a branch or tag name, but current rev will always point to a sha. This means that a branch or tag will never compare as True. So this ultimately only matches against exact shas. """ return self.get_revision(dest).startswith(rev_options[0]) def switch(self, dest, url, rev_options): self.run_command(['config', 'remote.origin.url', url], cwd=dest) self.run_command(['checkout', '-q'] + rev_options, cwd=dest) self.update_submodules(dest) def update(self, dest, rev_options): # First fetch changes from the default remote if self.get_git_version() >= parse_version('1.9.0'): # fetch tags in addition to everything else self.run_command(['fetch', '-q', '--tags'], cwd=dest) else: self.run_command(['fetch', '-q'], cwd=dest) # Then reset to wanted revision (maybe even origin/master) if rev_options: rev_options = self.check_rev_options( rev_options[0], dest, rev_options, ) self.run_command(['reset', '--hard', '-q'] + rev_options, cwd=dest) #: update submodules self.update_submodules(dest) def obtain(self, dest): url, rev = self.get_url_rev() if rev: rev_options = [rev] rev_display = ' (to %s)' % rev else: rev_options = ['origin/master'] rev_display = '' if self.check_destination(dest, url, rev_options, rev_display): logger.info( 'Cloning %s%s to %s', url, rev_display, display_path(dest), ) self.run_command(['clone', '-q', url, dest]) if rev: rev_options = self.check_rev_options(rev, dest, rev_options) # Only do a checkout if rev_options differs from HEAD if not self.check_version(dest, rev_options): self.run_command( ['checkout', '-q'] + rev_options, cwd=dest, ) #: repo may contain submodules self.update_submodules(dest) def get_url(self, location): """Return URL of the first remote encountered.""" remotes = self.run_command( ['config', '--get-regexp', 'remote\..*\.url'], show_stdout=False, cwd=location) remotes = remotes.splitlines() found_remote = remotes[0] for remote in remotes: if remote.startswith('remote.origin.url '): found_remote = remote break url = found_remote.split(' ')[1] return url.strip() def get_revision(self, location): current_rev = self.run_command( ['rev-parse', 'HEAD'], show_stdout=False, cwd=location) return current_rev.strip() def get_full_refs(self, location): """Yields tuples of (commit, ref) for branches and tags""" output = self.run_command(['show-ref'], show_stdout=False, cwd=location) for line in output.strip().splitlines(): commit, ref = line.split(' ', 1) yield commit.strip(), ref.strip() def is_ref_remote(self, ref): return ref.startswith('refs/remotes/') def is_ref_branch(self, ref): return ref.startswith('refs/heads/') def is_ref_tag(self, ref): return ref.startswith('refs/tags/') def is_ref_commit(self, ref): """A ref is a commit sha if it is not anything else""" return not any(( self.is_ref_remote(ref), self.is_ref_branch(ref), self.is_ref_tag(ref), )) # Should deprecate `get_refs` since it's ambiguous def get_refs(self, location): return self.get_short_refs(location) def get_short_refs(self, location): """Return map of named refs (branches or tags) to commit hashes.""" rv = {} for commit, ref in self.get_full_refs(location): ref_name = None if self.is_ref_remote(ref): ref_name = ref[len('refs/remotes/'):] elif self.is_ref_branch(ref): ref_name = ref[len('refs/heads/'):] elif self.is_ref_tag(ref): ref_name = ref[len('refs/tags/'):] if ref_name is not None: rv[ref_name] = commit return rv def _get_subdirectory(self, location): """Return the relative path of setup.py to the git repo root.""" # find the repo root git_dir = self.run_command(['rev-parse', '--git-dir'], show_stdout=False, cwd=location).strip() if not os.path.isabs(git_dir): git_dir = os.path.join(location, git_dir) root_dir = os.path.join(git_dir, '..') # find setup.py orig_location = location while not os.path.exists(os.path.join(location, 'setup.py')): last_location = location location = os.path.dirname(location) if location == last_location: # We've traversed up to the root of the filesystem without # finding setup.py logger.warning( "Could not find setup.py for directory %s (tried all " "parent directories)", orig_location, ) return None # relative path of setup.py to repo root if samefile(root_dir, location): return None return os.path.relpath(location, root_dir) def get_src_requirement(self, dist, location): repo = self.get_url(location) if not repo.lower().startswith('git:'): repo = 'git+' + repo egg_project_name = dist.egg_name().split('-', 1)[0] if not repo: return None current_rev = self.get_revision(location) req = '%s@%s#egg=%s' % (repo, current_rev, egg_project_name) subdirectory = self._get_subdirectory(location) if subdirectory: req += '&subdirectory=' + subdirectory return req def get_url_rev(self): """ Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes doesn't work with a ssh:// scheme (e.g. Github). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. """ if '://' not in self.url: assert 'file:' not in self.url self.url = self.url.replace('git+', 'git+ssh://') url, rev = super(Git, self).get_url_rev() url = url.replace('ssh://', '') else: url, rev = super(Git, self).get_url_rev() return url, rev def update_submodules(self, location): if not os.path.exists(os.path.join(location, '.gitmodules')): return self.run_command( ['submodule', 'update', '--init', '--recursive', '-q'], cwd=location, ) @classmethod def controls_location(cls, location): if super(Git, cls).controls_location(location): return True try: r = cls().run_command(['rev-parse'], cwd=location, show_stdout=False, on_returncode='ignore') return not r except BadCommand: logger.debug("could not determine if %s is under git control " "because git is not available", location) return False vcs.register(Git)
gpl-3.0
ted-gould/nova
nova/tests/unit/scheduler/filters/test_exact_core_filter.py
41
1954
# 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 nova.scheduler.filters import exact_core_filter from nova import test from nova.tests.unit.scheduler import fakes class TestExactCoreFilter(test.NoDBTestCase): def setUp(self): super(TestExactCoreFilter, self).setUp() self.filt_cls = exact_core_filter.ExactCoreFilter() def test_exact_core_filter_passes(self): filter_properties = {'instance_type': {'vcpus': 1}} host = self._get_host({'vcpus_total': 3, 'vcpus_used': 2}) self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) def test_exact_core_filter_fails(self): filter_properties = {'instance_type': {'vcpus': 2}} host = self._get_host({'vcpus_total': 3, 'vcpus_used': 2}) self.assertFalse(self.filt_cls.host_passes(host, filter_properties)) def test_exact_core_filter_passes_no_instance_type(self): filter_properties = {} host = self._get_host({'vcpus_total': 3, 'vcpus_used': 2}) self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) def test_exact_core_filter_fails_host_vcpus_not_set(self): filter_properties = {'instance_type': {'vcpus': 1}} host = self._get_host({}) self.assertFalse(self.filt_cls.host_passes(host, filter_properties)) def _get_host(self, host_attributes): return fakes.FakeHostState('host1', 'node1', host_attributes)
apache-2.0
drjeep/django
django/contrib/postgres/lookups.py
199
1175
from django.db.models import Lookup, Transform class PostgresSimpleLookup(Lookup): def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return '%s %s %s' % (lhs, self.operator, rhs), params class FunctionTransform(Transform): def as_sql(self, qn, connection): lhs, params = qn.compile(self.lhs) return "%s(%s)" % (self.function, lhs), params class DataContains(PostgresSimpleLookup): lookup_name = 'contains' operator = '@>' class ContainedBy(PostgresSimpleLookup): lookup_name = 'contained_by' operator = '<@' class Overlap(PostgresSimpleLookup): lookup_name = 'overlap' operator = '&&' class HasKey(PostgresSimpleLookup): lookup_name = 'has_key' operator = '?' class HasKeys(PostgresSimpleLookup): lookup_name = 'has_keys' operator = '?&' class HasAnyKeys(PostgresSimpleLookup): lookup_name = 'has_any_keys' operator = '?|' class Unaccent(FunctionTransform): bilateral = True lookup_name = 'unaccent' function = 'UNACCENT'
bsd-3-clause
infinit/grpc
tools/buildgen/plugins/make_fuzzer_tests.py
12
2571
# Copyright 2016, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Create tests for each fuzzer""" import copy import glob def mako_plugin(dictionary): targets = dictionary['targets'] tests = dictionary['tests'] for tgt in targets: if tgt['build'] == 'fuzzer': new_target = copy.deepcopy(tgt) new_target['build'] = 'test' new_target['name'] += '_one_entry' new_target['run'] = False new_target['src'].append('test/core/util/one_corpus_entry_fuzzer.c') new_target['own_src'].append('test/core/util/one_corpus_entry_fuzzer.c') targets.append(new_target) for corpus in new_target['corpus_dirs']: for fn in sorted(glob.glob('%s/*' % corpus)): tests.append({ 'name': new_target['name'], 'args': [fn], 'exclude_iomgrs': ['uv'], 'exclude_configs': ['tsan'], 'uses_polling': False, 'platforms': ['linux'], 'ci_platforms': ['linux'], 'flaky': False, 'language': 'c', 'cpu_cost': 0.1, })
bsd-3-clause
joelthompson/ansible-modules-core
files/assemble.py
15
8743
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Stephen Fromm <sfromm@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. import os import os.path import tempfile import re DOCUMENTATION = ''' --- module: assemble short_description: Assembles a configuration file from fragments description: - Assembles a configuration file from fragments. Often a particular program will take a single configuration file and does not support a C(conf.d) style structure where it is easy to build up the configuration from multiple sources. M(assemble) will take a directory of files that can be local or have already been transferred to the system, and concatenate them together to produce a destination file. Files are assembled in string sorting order. Puppet calls this idea I(fragments). version_added: "0.5" options: src: description: - An already existing directory full of source files. required: true default: null aliases: [] dest: description: - A file to create using the concatenation of all of the source files. required: true default: null backup: description: - Create a backup file (if C(yes)), including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. required: false choices: [ "yes", "no" ] default: "no" delimiter: description: - A delimiter to separate the file contents. version_added: "1.4" required: false default: null remote_src: description: - If False, it will search for src at originating/master machine, if True it will go to the remote/target machine for the src. Default is True. choices: [ "True", "False" ] required: false default: "True" version_added: "1.4" regexp: description: - Assemble files only if C(regex) matches the filename. If not set, all files are assembled. All "\\" (backslash) must be escaped as "\\\\" to comply yaml syntax. Uses Python regular expressions; see U(http://docs.python.org/2/library/re.html). required: false default: null ignore_hidden: description: - A boolean that controls if files that start with a '.' will be included or not. required: false default: false version_added: "2.0" validate: description: - The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the sshd example below. The command is passed securely so shell features like expansion and pipes won't work. required: false default: null version_added: "2.0" author: "Stephen Fromm (@sfromm)" extends_documentation_fragment: - files ''' EXAMPLES = ''' # Example from Ansible Playbooks - assemble: src=/etc/someapp/fragments dest=/etc/someapp/someapp.conf # When a delimiter is specified, it will be inserted in between each fragment - assemble: src=/etc/someapp/fragments dest=/etc/someapp/someapp.conf delimiter='### START FRAGMENT ###' # Copy a new "sshd_config" file into place, after passing validation with sshd - assemble: src=/etc/ssh/conf.d/ dest=/etc/ssh/sshd_config validate='/usr/sbin/sshd -t -f %s' ''' # =========================================== # Support method def assemble_from_fragments(src_path, delimiter=None, compiled_regexp=None, ignore_hidden=False): ''' assemble a file from a directory of fragments ''' tmpfd, temp_path = tempfile.mkstemp() tmp = os.fdopen(tmpfd,'w') delimit_me = False add_newline = False for f in sorted(os.listdir(src_path)): if compiled_regexp and not compiled_regexp.search(f): continue fragment = "%s/%s" % (src_path, f) if not os.path.isfile(fragment) or (ignore_hidden and os.path.basename(fragment).startswith('.')): continue fragment_content = file(fragment).read() # always put a newline between fragments if the previous fragment didn't end with a newline. if add_newline: tmp.write('\n') # delimiters should only appear between fragments if delimit_me: if delimiter: # un-escape anything like newlines delimiter = delimiter.decode('unicode-escape') tmp.write(delimiter) # always make sure there's a newline after the # delimiter, so lines don't run together if delimiter[-1] != '\n': tmp.write('\n') tmp.write(fragment_content) delimit_me = True if fragment_content.endswith('\n'): add_newline = False else: add_newline = True tmp.close() return temp_path def cleanup(path, result=None): # cleanup just in case if os.path.exists(path): try: os.remove(path) except (IOError, OSError), e: # don't error on possible race conditions, but keep warning if result is not None: result['warnings'] = ['Unable to remove temp file (%s): %s' % (path, str(e))] # ============================================================== # main def main(): module = AnsibleModule( # not checking because of daisy chain to file module argument_spec = dict( src = dict(required=True), delimiter = dict(required=False), dest = dict(required=True), backup=dict(default=False, type='bool'), remote_src=dict(default=False, type='bool'), regexp = dict(required=False), ignore_hidden = dict(default=False, type='bool'), validate = dict(required=False, type='str'), ), add_file_common_args=True ) changed = False path_hash = None dest_hash = None src = os.path.expanduser(module.params['src']) dest = os.path.expanduser(module.params['dest']) backup = module.params['backup'] delimiter = module.params['delimiter'] regexp = module.params['regexp'] compiled_regexp = None ignore_hidden = module.params['ignore_hidden'] validate = module.params.get('validate', None) result = dict(src=src, dest=dest) if not os.path.exists(src): module.fail_json(msg="Source (%s) does not exist" % src) if not os.path.isdir(src): module.fail_json(msg="Source (%s) is not a directory" % src) if regexp != None: try: compiled_regexp = re.compile(regexp) except re.error, e: module.fail_json(msg="Invalid Regexp (%s) in \"%s\"" % (e, regexp)) if validate and "%s" not in validate: module.fail_json(msg="validate must contain %%s: %s" % validate) path = assemble_from_fragments(src, delimiter, compiled_regexp, ignore_hidden) path_hash = module.sha1(path) result['checksum'] = path_hash # Backwards compat. This won't return data if FIPS mode is active try: pathmd5 = module.md5(path) except ValueError: pathmd5 = None result['md5sum'] = pathmd5 if os.path.exists(dest): dest_hash = module.sha1(dest) if path_hash != dest_hash: if validate: (rc, out, err) = module.run_command(validate % path) result['validation'] = dict(rc=rc, stdout=out, stderr=err) if rc != 0: cleanup(path) result['msg'] = "failed to validate: rc:%s error:%s" % (rc, err) module.fail_json(result) if backup and dest_hash is not None: result['backup_file'] = module.backup_local(dest) module.atomic_move(path, dest) changed = True cleanup(path, result) # handle file permissions file_args = module.load_file_common_arguments(module.params) result['changed'] = module.set_fs_attributes_if_different(file_args, changed) # Mission complete result['msg'] = "OK" module.exit_json(**result) # import module snippets from ansible.module_utils.basic import * main()
gpl-3.0
laserson/phip-stat
phip/utils.py
1
4345
# Copyright 2017 Uri Laserson # # 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. # used for hit calling DEFAULT_FDR = 0.01 def one_base_mutants(seq): alphabet = set(["A", "C", "G", "T", "N"]) for i in range(len(seq)): for alt in alphabet - set([seq[i].upper()]): yield seq[:i] + alt + seq[i + 1 :] def load_mapping(path): """Load barcode-to-sample mapping Expects a tab-delimited file: the first column is the barcode sequence, the second column is the sample name. No header line. """ bc2sample = {} with open(path, "r") as ip: for line in ip: (bc, sample) = [field.strip() for field in line.split("\t")] bc2sample[bc] = sample return bc2sample def edit1_mapping(mapping): """Insert edit-distance=1 seqs into barcode-to-sample mapping Input should be a dictionary of barcode sequence to sample string. The keys should be in the alphabet ACGTN. """ extended_mapping = mapping.copy() for bc in mapping.keys(): for mut in one_base_mutants(bc): if mut in extended_mapping: raise ValueError( "{} already in dict: BCs are within 1 edit".format(mut) ) extended_mapping[mut] = mapping[bc] return extended_mapping def compute_size_factors(counts): """Compute size factors from Anders and Huber 2010 counts is a numpy array """ import numpy as np masked = np.ma.masked_equal(counts, 0) geom_means = ( np.ma.exp(np.ma.log(masked).sum(axis=1) / (~masked.mask).sum(axis=1)) .data[np.newaxis] .T ) return np.ma.median(masked / geom_means, axis=0).data # fmt: off # https://github.com/lh3/readfq def readfq(fp): # this is a generator function last = None # this is a buffer keeping the last unprocessed line while True: # mimic closure; is it a bad idea? if not last: # the first record or a record following a fastq for l in fp: # search for the start of the next record if l[0] in '>@': # fasta/q header line last = l[:-1] # save this line break if not last: break name, seqs, last = last[1:].partition(" ")[0], [], None for l in fp: # read the sequence if l[0] in '@+>': last = l[:-1] break seqs.append(l[:-1]) if not last or last[0] != '+': # this is a fasta record yield name, ''.join(seqs), None # yield a fasta record if not last: break else: # this is a fastq record seq, leng, seqs = ''.join(seqs), 0, [] for l in fp: # read the quality seqs.append(l[:-1]) leng += len(l) - 1 if leng >= len(seq): # have read enough quality last = None yield name, seq, ''.join(seqs); # yield a fastq record break if last: # reach EOF before reading enough quality yield name, seq, None # yield a fasta record instead break # fmt: on def read_fastq_nowrap(fp): raw = [None, None, None, None] for (i, line) in enumerate(fp): mod = i % 4 if mod == 0 and line[0] != "@": raise ValueError(f'{line} expected to start with "@"') if mod == 2 and line != "+\n": raise ValueError(f'{line} expected to contain just "+"') raw[mod] = line if mod == 3: rec = (raw[0][1:].rstrip(), raw[1].rstrip(), raw[3].rstrip()) if len(rec[1]) != len(rec[2]): raise ValueError(f"{rec} seq and qual are diff length") yield rec else: if mod != 3: raise ValueError("wrong number of lines in file")
apache-2.0
julienr/vispy
vispy/util/svg/path.py
21
10724
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Nicolas P. Rougier # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- import re import math import numpy as np from . import geometry from . geometry import epsilon from . transformable import Transformable # ----------------------------------------------------------------- Command --- class Command(object): def __repr__(self): s = '%s ' % self._command for arg in self._args: s += "%.2f " % arg return s def origin(self, current=None, previous=None): relative = self._command in "mlvhcsqtaz" if relative and current: return current else: return 0.0, 0.0 # -------------------------------------------------------------------- Line --- class Line(Command): def __init__(self, x=0, y=0, relative=True): self._command = 'l' if relative else 'L' self._args = [x, y] def vertices(self, current, previous=None): ox, oy = self.origin(current) x, y = self._args self.previous = x, y return (ox + x, oy + y), # ------------------------------------------------------------------- VLine --- class VLine(Command): def __init__(self, y=0, relative=True): self._command = 'v' if relative else 'V' self._args = [y] def vertices(self, current, previous=None): ox, oy = self.origin(current) y = self._args[0] self.previous = ox, oy + y return (ox, oy + y), # ------------------------------------------------------------------- HLine --- class HLine(Command): def __init__(self, x=0, relative=True): self._command = 'h' if relative else 'H' self._args = [x] def vertices(self, current, previous=None): ox, oy = self.origin(current) x = self._args[0] self.previous = ox + x, oy return (ox + x, oy), # -------------------------------------------------------------------- Move --- class Move(Command): def __init__(self, x=0, y=0, relative=True): self._command = 'm' if relative else 'M' self._args = [x, y] def vertices(self, current, previous=None): ox, oy = self.origin(current) x, y = self._args x, y = x + ox, y + oy self.previous = x, y return (x, y), # ------------------------------------------------------------------- Close --- class Close(Command): def __init__(self, relative=True): self._command = 'z' if relative else 'Z' self._args = [] def vertices(self, current, previous=None): self.previous = current return [] # --------------------------------------------------------------------- Arc --- class Arc(Command): def __init__(self, r1=1, r2=1, angle=2 * math.pi, large=True, sweep=True, x=0, y=0, relative=True): self._command = 'a' if relative else 'A' self._args = [r1, r2, angle, large, sweep, x, y] def vertices(self, current, previous=None): ox, oy = self.origin(current) rx, ry, angle, large, sweep, x, y = self._args x, y = x + ox, y + oy x0, y0 = current self.previous = x, y vertices = geometry.elliptical_arc( x0, y0, rx, ry, angle, large, sweep, x, y) return vertices[1:] # ------------------------------------------------------------------- Cubic --- class Cubic(Command): def __init__(self, x1=0, y1=0, x2=0, y2=0, x3=0, y3=0, relative=True): self._command = 'c' if relative else 'C' self._args = [x1, y1, x2, y2, x3, y3] def vertices(self, current, previous=None): ox, oy = self.origin(current) x0, y0 = current x1, y1, x2, y2, x3, y3 = self._args x1, y1 = x1 + ox, y1 + oy x2, y2 = x2 + ox, y2 + oy x3, y3 = x3 + ox, y3 + oy self.previous = x2, y2 vertices = geometry.cubic((x0, y0), (x1, y1), (x2, y2), (x3, y3)) return vertices[1:] # --------------------------------------------------------------- Quadratic --- class Quadratic(Command): def __init__(self, x1=0, y1=0, x2=0, y2=0, relative=True): self._command = 'q' if relative else 'Q' self._args = [x1, y1, x2, y2] def vertices(self, current, last_control_point=None): ox, oy = self.origin(current) x1, y1, x2, y2 = self._args x0, y0 = current x1, y1 = x1 + ox, y1 + oy x2, y2 = x2 + ox, y2 + oy self.previous = x1, y1 vertices = geometry.quadratic((x0, y0), (x1, y1), (x2, y2)) return vertices[1:] # ------------------------------------------------------------- SmoothCubic --- class SmoothCubic(Command): def __init__(self, x2=0, y2=0, x3=0, y3=0, relative=True): self._command = 's' if relative else 'S' self._args = [x2, y2, x3, y3] def vertices(self, current, previous): ox, oy = self.origin(current) x0, y0 = current x2, y2, x3, y3 = self._args x2, y2 = x2 + ox, y2 + oy x3, y3 = x3 + ox, y3 + oy x1, y1 = 2 * x0 - previous[0], 2 * y0 - previous[1] self.previous = x2, y2 vertices = geometry.cubic((x0, y0), (x1, y1), (x2, y2), (x3, y3)) return vertices[1:] # --------------------------------------------------------- SmoothQuadratic --- class SmoothQuadratic(Command): def __init__(self, x2=0, y2=0, relative=True): self._command = 't' if relative else 'T' self._args = [x2, y2] def vertices(self, current, previous): ox, oy = self.origin(current) x2, y2 = self._args x0, y0 = current x1, y1 = 2 * x0 - previous[0], 2 * y0 - previous[1] x2, y2 = x2 + ox, y2 + oy self.previous = x1, y1 vertices = geometry.quadratic((x0, y0), (x1, y1), (x2, y2)) return vertices[1:] # -------------------------------------------------------------------- Path --- class Path(Transformable): def __init__(self, content=None, parent=None): Transformable.__init__(self, content, parent) self._paths = [] if not isinstance(content, str): content = content.get("d", "") commands = re.compile( "(?P<command>[MLVHCSQTAZmlvhcsqtaz])(?P<points>[+\-0-9.e, \n\t]*)") path = [] for match in re.finditer(commands, content): command = match.group("command") points = match.group("points").replace(',', ' ') points = [float(v) for v in points.split()] relative = command in "mlvhcsqtaz" command = command.upper() while len(points) or command == 'Z': if command == 'M': if len(path): self._paths.append(path) path = [] path.append(Move(*points[:2], relative=relative)) points = points[2:] elif command == 'L': path.append(Line(*points[:2], relative=relative)) points = points[2:] elif command == 'V': path.append(VLine(*points[:1], relative=relative)) points = points[1:] elif command == 'H': path.append(HLine(*points[:1], relative=relative)) points = points[1:] elif command == 'C': path.append(Cubic(*points[:6], relative=relative)) points = points[6:] elif command == 'S': path.append(SmoothCubic(*points[:4], relative=relative)) points = points[4:] elif command == 'Q': path.append(Quadratic(*points[:4], relative=relative)) points = points[4:] elif command == 'T': path.append( SmoothQuadratic(*points[2:], relative=relative)) points = points[2:] elif command == 'A': path.append(Arc(*points[:7], relative=relative)) points = points[7:] elif command == 'Z': path.append(Close(relative=relative)) self._paths.append(path) path = [] break else: raise RuntimeError( "Unknown SVG path command(%s)" % command) if len(path): self._paths.append(path) def __repr__(self): s = "" for path in self._paths: for item in path: s += repr(item) return s @property def xml(self): return self._xml() def _xml(self, prefix=""): s = prefix + "<path " s += 'id="%s" ' % self._id s += self._style.xml s += '\n' t = ' ' + prefix + ' d="' s += t prefix = ' ' * len(t) first = True for i, path in enumerate(self._paths): for j, item in enumerate(path): if first: s += repr(item) first = False else: s += prefix + repr(item) if i < len(self._paths) - 1 or j < len(path) - 1: s += '\n' s += '"/>\n' return s @property def vertices(self): self._vertices = [] current = 0, 0 previous = 0, 0 for path in self._paths: vertices = [] for command in path: V = command.vertices(current, previous) previous = command.previous vertices.extend(V) if len(V) > 0: current = V[-1] else: current = 0, 0 closed = False if isinstance(command, Close): closed = True if len(vertices) > 2: d = geometry.calc_sq_distance(vertices[-1][0], vertices[-1][1], # noqa vertices[0][0], vertices[0][1]) # noqa if d < epsilon: vertices = vertices[:-1] # Apply transformation V = np.ones((len(vertices), 3)) V[:, :2] = vertices V = np.dot(V, self.transform.matrix.T) V[:, 2] = 0 self._vertices.append((V, closed)) return self._vertices
bsd-3-clause
dgellis90/nipype
nipype/interfaces/slicer/tests/test_auto_OrientScalarVolume.py
12
1164
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..converters import OrientScalarVolume def test_OrientScalarVolume_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), inputVolume1=dict(argstr='%s', position=-2, ), orientation=dict(argstr='--orientation %s', ), outputVolume=dict(argstr='%s', hash_files=False, position=-1, ), terminal_output=dict(nohash=True, ), ) inputs = OrientScalarVolume.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_OrientScalarVolume_outputs(): output_map = dict(outputVolume=dict(position=-1, ), ) outputs = OrientScalarVolume.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
bsd-3-clause
willhardy/django
tests/template_tests/tests.py
14
5545
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys from django.contrib.auth.models import Group from django.template import Context, Engine, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings from django.urls import NoReverseMatch from django.utils import translation class TemplateTests(SimpleTestCase): def test_string_origin(self): template = Engine().from_string('string template') self.assertEqual(template.origin.name, UNKNOWN_SOURCE) self.assertEqual(template.origin.loader_name, None) self.assertEqual(template.source, 'string template') @override_settings(SETTINGS_MODULE=None) def test_url_reverse_no_settings_module(self): """ #9005 -- url tag shouldn't require settings.SETTINGS_MODULE to be set. """ t = Engine(debug=True).from_string('{% url will_not_match %}') c = Context() with self.assertRaises(NoReverseMatch): t.render(c) def test_url_reverse_view_name(self): """ #19827 -- url tag should keep original strack trace when reraising exception. """ t = Engine().from_string('{% url will_not_match %}') c = Context() try: t.render(c) except NoReverseMatch: tb = sys.exc_info()[2] depth = 0 while tb.tb_next is not None: tb = tb.tb_next depth += 1 self.assertGreater(depth, 5, "The traceback context was lost when reraising the traceback.") def test_no_wrapped_exception(self): """ # 16770 -- The template system doesn't wrap exceptions, but annotates them. """ engine = Engine(debug=True) c = Context({"coconuts": lambda: 42 / 0}) t = engine.from_string("{{ coconuts }}") with self.assertRaises(ZeroDivisionError) as e: t.render(c) debug = e.exception.template_debug self.assertEqual(debug['start'], 0) self.assertEqual(debug['end'], 14) def test_invalid_block_suggestion(self): """ Error messages should include the unexpected block name and be in all English. """ engine = Engine() msg = ( "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' " "or 'endif'. Did you forget to register or load this tag?" ) with self.settings(USE_I18N=True), translation.override('de'): with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}") def test_unknown_block_tag(self): engine = Engine() msg = ( "Invalid block tag on line 1: 'foobar'. Did you forget to " "register or load this tag?" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("lala{% foobar %}") def test_compile_filter_expression_error(self): """ 19819 -- Make sure the correct token is highlighted for FilterExpression errors. """ engine = Engine(debug=True) msg = "Could not parse the remainder: '@bar' from 'foo@bar'" with self.assertRaisesMessage(TemplateSyntaxError, msg) as e: engine.from_string("{% if 1 %}{{ foo@bar }}{% endif %}") debug = e.exception.template_debug self.assertEqual((debug['start'], debug['end']), (10, 23)) self.assertEqual((debug['during']), '{{ foo@bar }}') def test_compile_tag_error(self): """ Errors raised while compiling nodes should include the token information. """ engine = Engine( debug=True, libraries={'bad_tag': 'template_tests.templatetags.bad_tag'}, ) with self.assertRaises(RuntimeError) as e: engine.from_string("{% load bad_tag %}{% badtag %}") self.assertEqual(e.exception.template_debug['during'], '{% badtag %}') def test_super_errors(self): """ #18169 -- NoReverseMatch should not be silence in block.super. """ engine = Engine(app_dirs=True) t = engine.get_template('included_content.html') with self.assertRaises(NoReverseMatch): t.render(Context()) def test_debug_tag_non_ascii(self): """ #23060 -- Test non-ASCII model representation in debug output. """ group = Group(name="清風") c1 = Context({"objs": [group]}) t1 = Engine().from_string('{% debug %}') self.assertIn("清風", t1.render(c1)) def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template objects. """ engine = Engine() parent = engine.from_string('{% block content %}parent{% endblock %}') child = engine.from_string( '{% extends parent %}{% block content %}child{% endblock %}') self.assertEqual(child.render(Context({'parent': parent})), 'child') def test_node_origin(self): """ #25848 -- Set origin on Node so debugging tools can determine which template the node came from even if extending or including templates. """ template = Engine().from_string('content') for node in template.nodelist: self.assertEqual(node.origin, template.origin)
bsd-3-clause
privateip/ansible
lib/ansible/modules/network/sros/sros_rollback.py
21
7400
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = """ --- module: sros_rollback version_added: "2.2" author: "Peter Sprygada (@privateip)" short_description: Configure Nokia SR OS rollback description: - Configure the rollback feature on remote Nokia devices running the SR OS operating system. this module provides a stateful implementation for managing the configuration of the rollback feature extends_documentation_fragment: sros options: rollback_location: description: - The I(rollback_location) specifies the location and filename of the rollback checkpoint files. This argument supports any valid local or remote URL as specified in SR OS required: false default: null remote_max_checkpoints: description: - The I(remote_max_checkpoints) argument configures the maximum number of rollback files that can be transferred and saved to a remote location. Valid values for this argument are in the range of 1 to 50 required: false default: null local_max_checkpoints: description: - The I(local_max_checkpoints) argument configures the maximum number of rollback files that can be saved on the devices local compact flash. Valid values for this argument are in the range of 1 to 50 required: false default: null rescue_location: description: - The I(rescue_location) specifies the location of the rescue file. This argument supports any valid local or remote URL as specified in SR OS required: false default: null state: description: - The I(state) argument specifies the state of the configuration entries in the devices active configuration. When the state value is set to C(true) the configuration is present in the devices active configuration. When the state value is set to C(false) the configuration values are removed from the devices active configuration. required: false default: present choices: ['present', 'absent'] """ EXAMPLES = """ # Note: examples below use the following provider dict to handle # transport and authentication to the node. vars: cli: host: "{{ inventory_hostname }}" username: admin password: admin transport: cli - name: configure rollback location sros_rollback: rollback_location: "cb3:/ansible" provider: "{{ cli }}" - name: remove all rollback configuration sros_rollback: state: absent provider: "{{ cli }}" """ RETURN = """ updates: description: The set of commands that will be pushed to the remote device returned: always type: list sample: ['...', '...'] """ from ansible.module_utils.basic import get_exception from ansible.module_utils.sros import NetworkModule, NetworkError from ansible.module_utils.netcfg import NetworkConfig, dumps def invoke(name, *args, **kwargs): func = globals().get(name) if func: return func(*args, **kwargs) def sanitize_config(lines): commands = list() for line in lines: for index, entry in enumerate(commands): if line.startswith(entry): del commands[index] break commands.append(line) return commands def present(module, commands): setters = set() for key, value in module.argument_spec.items(): if module.params[key] is not None: setter = value.get('setter') or 'set_%s' % key if setter not in setters: setters.add(setter) invoke(setter, module, commands) def absent(module, commands): config = module.config.get_config() if 'rollback-location' in config: commands.append('configure system rollback no rollback-location') if 'rescue-location' in config: commands.append('configure system rollback no rescue-location') if 'remote-max-checkpoints' in config: commands.append('configure system rollback no remote-max-checkpoints') if 'local-max-checkpoints' in config: commands.append('configure system rollback no remote-max-checkpoints') def set_rollback_location(module, commands): value = module.params['rollback_location'] commands.append('configure system rollback rollback-location "%s"' % value) def set_local_max_checkpoints(module, commands): value = module.params['local_max_checkpoints'] if not 1 <= value <= 50: module.fail_json(msg='local_max_checkpoints must be between 1 and 50') commands.append('configure system rollback local-max-checkpoints %s' % value) def set_remote_max_checkpoints(module, commands): value = module.params['remote_max_checkpoints'] if not 1 <= value <= 50: module.fail_json(msg='remote_max_checkpoints must be between 1 and 50') commands.append('configure system rollback remote-max-checkpoints %s' % value) def set_rescue_location(module, commands): value = module.params['rescue_location'] commands.append('configure system rollback rescue-location "%s"' % value) def get_config(module): contents = module.config.get_config() return NetworkConfig(device_os='sros', contents=contents) def load_config(module, commands, result): candidate = NetworkConfig(device_os='sros', contents='\n'.join(commands)) config = get_config(module) configobjs = candidate.difference(config) if configobjs: commands = dumps(configobjs, 'lines') commands = sanitize_config(commands.split('\n')) result['updates'] = commands # send the configuration commands to the device and merge # them with the current running config if not module.check_mode: module.config(commands) result['changed'] = True def main(): """ main entry point for module execution """ argument_spec = dict( rollback_location=dict(), local_max_checkpoints=dict(type='int'), remote_max_checkpoints=dict(type='int'), rescue_location=dict(), state=dict(default='present', choices=['present', 'absent']) ) module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, supports_check_mode=True) state = module.params['state'] result = dict(changed=False) commands = list() invoke(state, module, commands) try: load_config(module, commands, result) except NetworkError: exc = get_exception() module.fail_json(msg=str(exc), **exc.kwargs) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0