id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
4,400
phaethon/kamene
kamene/contrib/gsm_um.py
status
def status(AuxiliaryStates_presence=0): """STATUS Section 9.3.27""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3d) # 00111101 c = Cause() d = CallState() packet = a / b / c / d if AuxiliaryStates_presence is 1: e = AuxiliaryStatesHdr(ieiAS=0x24, eightBitAS=0x0) packet = packet / e return packet
python
def status(AuxiliaryStates_presence=0): """STATUS Section 9.3.27""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3d) # 00111101 c = Cause() d = CallState() packet = a / b / c / d if AuxiliaryStates_presence is 1: e = AuxiliaryStatesHdr(ieiAS=0x24, eightBitAS=0x0) packet = packet / e return packet
[ "def", "status", "(", "AuxiliaryStates_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x3d", ")", "# 00111101", "c", "=", "Cause", "(", ")", "d", "=", "CallState", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "if", "AuxiliaryStates_presence", "is", "1", ":", "e", "=", "AuxiliaryStatesHdr", "(", "ieiAS", "=", "0x24", ",", "eightBitAS", "=", "0x0", ")", "packet", "=", "packet", "/", "e", "return", "packet" ]
STATUS Section 9.3.27
[ "STATUS", "Section", "9", ".", "3", ".", "27" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2265-L2275
4,401
phaethon/kamene
kamene/contrib/gsm_um.py
statusEnquiry
def statusEnquiry(): """STATUS ENQUIRY Section 9.3.28""" a = TpPd(pd=0x3) b = MessageType(mesType=0x34) # 00110100 packet = a / b return packet
python
def statusEnquiry(): """STATUS ENQUIRY Section 9.3.28""" a = TpPd(pd=0x3) b = MessageType(mesType=0x34) # 00110100 packet = a / b return packet
[ "def", "statusEnquiry", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x34", ")", "# 00110100", "packet", "=", "a", "/", "b", "return", "packet" ]
STATUS ENQUIRY Section 9.3.28
[ "STATUS", "ENQUIRY", "Section", "9", ".", "3", ".", "28" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2278-L2283
4,402
phaethon/kamene
kamene/contrib/gsm_um.py
stopDtmf
def stopDtmf(): """STOP DTMF Section 9.3.29""" a = TpPd(pd=0x3) b = MessageType(mesType=0x31) # 00110001 packet = a / b return packet
python
def stopDtmf(): """STOP DTMF Section 9.3.29""" a = TpPd(pd=0x3) b = MessageType(mesType=0x31) # 00110001 packet = a / b return packet
[ "def", "stopDtmf", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x31", ")", "# 00110001", "packet", "=", "a", "/", "b", "return", "packet" ]
STOP DTMF Section 9.3.29
[ "STOP", "DTMF", "Section", "9", ".", "3", ".", "29" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2286-L2291
4,403
phaethon/kamene
kamene/contrib/gsm_um.py
stopDtmfAcknowledge
def stopDtmfAcknowledge(): """STOP DTMF ACKNOWLEDGE Section 9.3.30""" a = TpPd(pd=0x3) b = MessageType(mesType=0x32) # 00110010 packet = a / b return packet
python
def stopDtmfAcknowledge(): """STOP DTMF ACKNOWLEDGE Section 9.3.30""" a = TpPd(pd=0x3) b = MessageType(mesType=0x32) # 00110010 packet = a / b return packet
[ "def", "stopDtmfAcknowledge", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x32", ")", "# 00110010", "packet", "=", "a", "/", "b", "return", "packet" ]
STOP DTMF ACKNOWLEDGE Section 9.3.30
[ "STOP", "DTMF", "ACKNOWLEDGE", "Section", "9", ".", "3", ".", "30" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2295-L2300
4,404
phaethon/kamene
kamene/contrib/gsm_um.py
userInformation
def userInformation(MoreData_presence=0): """USER INFORMATION Section 9.3.31""" a = TpPd(pd=0x3) b = MessageType(mesType=0x20) # 000100000 c = UserUser() packet = a / b / c if MoreData_presence is 1: d = MoreDataHdr(ieiMD=0xA0, eightBitMD=0x0) packet = packet / d return packet
python
def userInformation(MoreData_presence=0): """USER INFORMATION Section 9.3.31""" a = TpPd(pd=0x3) b = MessageType(mesType=0x20) # 000100000 c = UserUser() packet = a / b / c if MoreData_presence is 1: d = MoreDataHdr(ieiMD=0xA0, eightBitMD=0x0) packet = packet / d return packet
[ "def", "userInformation", "(", "MoreData_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x20", ")", "# 000100000", "c", "=", "UserUser", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "if", "MoreData_presence", "is", "1", ":", "d", "=", "MoreDataHdr", "(", "ieiMD", "=", "0xA0", ",", "eightBitMD", "=", "0x0", ")", "packet", "=", "packet", "/", "d", "return", "packet" ]
USER INFORMATION Section 9.3.31
[ "USER", "INFORMATION", "Section", "9", ".", "3", ".", "31" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2303-L2312
4,405
phaethon/kamene
kamene/contrib/gsm_um.py
attachRequest
def attachRequest(PTmsiSignature_presence=0, GprsTimer_presence=0, TmsiStatus_presence=0): """ATTACH REQUEST Section 9.4.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1) # 0000001 c = MsNetworkCapability() d = AttachTypeAndCiphKeySeqNr() f = DrxParameter() g = MobileId() h = RoutingAreaIdentification() i = MsRadioAccessCapability() packet = a / b / c / d / f / g / h / i if PTmsiSignature_presence is 1: j = PTmsiSignature(ieiPTS=0x19) packet = packet / j if GprsTimer_presence is 1: k = GprsTimer(ieiGT=0x17) packet = packet / k if TmsiStatus_presence is 1: l = TmsiStatus(ieiTS=0x9) packet = packet / l return packet
python
def attachRequest(PTmsiSignature_presence=0, GprsTimer_presence=0, TmsiStatus_presence=0): """ATTACH REQUEST Section 9.4.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1) # 0000001 c = MsNetworkCapability() d = AttachTypeAndCiphKeySeqNr() f = DrxParameter() g = MobileId() h = RoutingAreaIdentification() i = MsRadioAccessCapability() packet = a / b / c / d / f / g / h / i if PTmsiSignature_presence is 1: j = PTmsiSignature(ieiPTS=0x19) packet = packet / j if GprsTimer_presence is 1: k = GprsTimer(ieiGT=0x17) packet = packet / k if TmsiStatus_presence is 1: l = TmsiStatus(ieiTS=0x9) packet = packet / l return packet
[ "def", "attachRequest", "(", "PTmsiSignature_presence", "=", "0", ",", "GprsTimer_presence", "=", "0", ",", "TmsiStatus_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x1", ")", "# 0000001", "c", "=", "MsNetworkCapability", "(", ")", "d", "=", "AttachTypeAndCiphKeySeqNr", "(", ")", "f", "=", "DrxParameter", "(", ")", "g", "=", "MobileId", "(", ")", "h", "=", "RoutingAreaIdentification", "(", ")", "i", "=", "MsRadioAccessCapability", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "/", "f", "/", "g", "/", "h", "/", "i", "if", "PTmsiSignature_presence", "is", "1", ":", "j", "=", "PTmsiSignature", "(", "ieiPTS", "=", "0x19", ")", "packet", "=", "packet", "/", "j", "if", "GprsTimer_presence", "is", "1", ":", "k", "=", "GprsTimer", "(", "ieiGT", "=", "0x17", ")", "packet", "=", "packet", "/", "k", "if", "TmsiStatus_presence", "is", "1", ":", "l", "=", "TmsiStatus", "(", "ieiTS", "=", "0x9", ")", "packet", "=", "packet", "/", "l", "return", "packet" ]
ATTACH REQUEST Section 9.4.1
[ "ATTACH", "REQUEST", "Section", "9", ".", "4", ".", "1" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2319-L2340
4,406
phaethon/kamene
kamene/contrib/gsm_um.py
attachAccept
def attachAccept(PTmsiSignature_presence=0, GprsTimer_presence=0, MobileId_presence=0, MobileId_presence1=0, GmmCause_presence=0): """ATTACH ACCEPT Section 9.4.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x2) # 00000010 c = AttachResult() d = ForceToStandby() e = GprsTimer() f = RadioPriorityAndSpareHalfOctets() h = RoutingAreaIdentification() packet = a / b / c / d / e / f / h if PTmsiSignature_presence is 1: i = PTmsiSignature(ieiPTS=0x19) packet = packet / i if GprsTimer_presence is 1: j = GprsTimer(ieiGT=0x17) packet = packet / j if MobileId_presence is 1: k = MobileIdHdr(ieiMI=0x18, eightBitMI=0x0) packet = packet / k if MobileId_presence1 is 1: l = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0) packet = packet / l if GmmCause_presence is 1: m = GmmCause(ieiGC=0x25) packet = packet / m return packet
python
def attachAccept(PTmsiSignature_presence=0, GprsTimer_presence=0, MobileId_presence=0, MobileId_presence1=0, GmmCause_presence=0): """ATTACH ACCEPT Section 9.4.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x2) # 00000010 c = AttachResult() d = ForceToStandby() e = GprsTimer() f = RadioPriorityAndSpareHalfOctets() h = RoutingAreaIdentification() packet = a / b / c / d / e / f / h if PTmsiSignature_presence is 1: i = PTmsiSignature(ieiPTS=0x19) packet = packet / i if GprsTimer_presence is 1: j = GprsTimer(ieiGT=0x17) packet = packet / j if MobileId_presence is 1: k = MobileIdHdr(ieiMI=0x18, eightBitMI=0x0) packet = packet / k if MobileId_presence1 is 1: l = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0) packet = packet / l if GmmCause_presence is 1: m = GmmCause(ieiGC=0x25) packet = packet / m return packet
[ "def", "attachAccept", "(", "PTmsiSignature_presence", "=", "0", ",", "GprsTimer_presence", "=", "0", ",", "MobileId_presence", "=", "0", ",", "MobileId_presence1", "=", "0", ",", "GmmCause_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x2", ")", "# 00000010", "c", "=", "AttachResult", "(", ")", "d", "=", "ForceToStandby", "(", ")", "e", "=", "GprsTimer", "(", ")", "f", "=", "RadioPriorityAndSpareHalfOctets", "(", ")", "h", "=", "RoutingAreaIdentification", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "/", "e", "/", "f", "/", "h", "if", "PTmsiSignature_presence", "is", "1", ":", "i", "=", "PTmsiSignature", "(", "ieiPTS", "=", "0x19", ")", "packet", "=", "packet", "/", "i", "if", "GprsTimer_presence", "is", "1", ":", "j", "=", "GprsTimer", "(", "ieiGT", "=", "0x17", ")", "packet", "=", "packet", "/", "j", "if", "MobileId_presence", "is", "1", ":", "k", "=", "MobileIdHdr", "(", "ieiMI", "=", "0x18", ",", "eightBitMI", "=", "0x0", ")", "packet", "=", "packet", "/", "k", "if", "MobileId_presence1", "is", "1", ":", "l", "=", "MobileIdHdr", "(", "ieiMI", "=", "0x23", ",", "eightBitMI", "=", "0x0", ")", "packet", "=", "packet", "/", "l", "if", "GmmCause_presence", "is", "1", ":", "m", "=", "GmmCause", "(", "ieiGC", "=", "0x25", ")", "packet", "=", "packet", "/", "m", "return", "packet" ]
ATTACH ACCEPT Section 9.4.2
[ "ATTACH", "ACCEPT", "Section", "9", ".", "4", ".", "2" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2343-L2370
4,407
phaethon/kamene
kamene/contrib/gsm_um.py
attachComplete
def attachComplete(): """ATTACH COMPLETE Section 9.4.3""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3) # 00000011 packet = a / b return packet
python
def attachComplete(): """ATTACH COMPLETE Section 9.4.3""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3) # 00000011 packet = a / b return packet
[ "def", "attachComplete", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x3", ")", "# 00000011", "packet", "=", "a", "/", "b", "return", "packet" ]
ATTACH COMPLETE Section 9.4.3
[ "ATTACH", "COMPLETE", "Section", "9", ".", "4", ".", "3" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2373-L2378
4,408
phaethon/kamene
kamene/contrib/gsm_um.py
detachRequest
def detachRequest(GmmCause_presence=0): """DETACH REQUEST Section 9.4.5""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 c = DetachTypeAndForceToStandby() packet = a / b / c if GmmCause_presence is 1: e = GmmCause(ieiGC=0x25) packet = packet / e return packet
python
def detachRequest(GmmCause_presence=0): """DETACH REQUEST Section 9.4.5""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 c = DetachTypeAndForceToStandby() packet = a / b / c if GmmCause_presence is 1: e = GmmCause(ieiGC=0x25) packet = packet / e return packet
[ "def", "detachRequest", "(", "GmmCause_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x5", ")", "# 00000101", "c", "=", "DetachTypeAndForceToStandby", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "if", "GmmCause_presence", "is", "1", ":", "e", "=", "GmmCause", "(", "ieiGC", "=", "0x25", ")", "packet", "=", "packet", "/", "e", "return", "packet" ]
DETACH REQUEST Section 9.4.5
[ "DETACH", "REQUEST", "Section", "9", ".", "4", ".", "5" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2390-L2399
4,409
phaethon/kamene
kamene/contrib/gsm_um.py
detachRequestMsOriginating
def detachRequestMsOriginating(): """DETACH REQUEST Section 9.4.5.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 c = DetachTypeAndSpareHalfOctets() packet = a / b / c return packet
python
def detachRequestMsOriginating(): """DETACH REQUEST Section 9.4.5.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 c = DetachTypeAndSpareHalfOctets() packet = a / b / c return packet
[ "def", "detachRequestMsOriginating", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x5", ")", "# 00000101", "c", "=", "DetachTypeAndSpareHalfOctets", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "return", "packet" ]
DETACH REQUEST Section 9.4.5.2
[ "DETACH", "REQUEST", "Section", "9", ".", "4", ".", "5", ".", "2" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2402-L2408
4,410
phaethon/kamene
kamene/contrib/gsm_um.py
detachAcceptMsTerminated
def detachAcceptMsTerminated(): """DETACH ACCEPT Section 9.4.6.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x6) # 00000110 packet = a / b return packet
python
def detachAcceptMsTerminated(): """DETACH ACCEPT Section 9.4.6.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x6) # 00000110 packet = a / b return packet
[ "def", "detachAcceptMsTerminated", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x6", ")", "# 00000110", "packet", "=", "a", "/", "b", "return", "packet" ]
DETACH ACCEPT Section 9.4.6.1
[ "DETACH", "ACCEPT", "Section", "9", ".", "4", ".", "6", ".", "1" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2411-L2416
4,411
phaethon/kamene
kamene/contrib/gsm_um.py
detachAcceptMsOriginating
def detachAcceptMsOriginating(): """DETACH ACCEPT Section 9.4.6.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x6) # 00000110 c = ForceToStandbyAndSpareHalfOctets() packet = a / b / c return packet
python
def detachAcceptMsOriginating(): """DETACH ACCEPT Section 9.4.6.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x6) # 00000110 c = ForceToStandbyAndSpareHalfOctets() packet = a / b / c return packet
[ "def", "detachAcceptMsOriginating", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x6", ")", "# 00000110", "c", "=", "ForceToStandbyAndSpareHalfOctets", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "return", "packet" ]
DETACH ACCEPT Section 9.4.6.2
[ "DETACH", "ACCEPT", "Section", "9", ".", "4", ".", "6", ".", "2" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2419-L2425
4,412
phaethon/kamene
kamene/contrib/gsm_um.py
ptmsiReallocationCommand
def ptmsiReallocationCommand(PTmsiSignature_presence=0): """P-TMSI REALLOCATION COMMAND Section 9.4.7""" a = TpPd(pd=0x3) b = MessageType(mesType=0x10) # 00010000 c = MobileId() d = RoutingAreaIdentification() e = ForceToStandbyAndSpareHalfOctets() packet = a / b / c / d / e if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g return packet
python
def ptmsiReallocationCommand(PTmsiSignature_presence=0): """P-TMSI REALLOCATION COMMAND Section 9.4.7""" a = TpPd(pd=0x3) b = MessageType(mesType=0x10) # 00010000 c = MobileId() d = RoutingAreaIdentification() e = ForceToStandbyAndSpareHalfOctets() packet = a / b / c / d / e if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g return packet
[ "def", "ptmsiReallocationCommand", "(", "PTmsiSignature_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x10", ")", "# 00010000", "c", "=", "MobileId", "(", ")", "d", "=", "RoutingAreaIdentification", "(", ")", "e", "=", "ForceToStandbyAndSpareHalfOctets", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "/", "e", "if", "PTmsiSignature_presence", "is", "1", ":", "g", "=", "PTmsiSignature", "(", "ieiPTS", "=", "0x19", ")", "packet", "=", "packet", "/", "g", "return", "packet" ]
P-TMSI REALLOCATION COMMAND Section 9.4.7
[ "P", "-", "TMSI", "REALLOCATION", "COMMAND", "Section", "9", ".", "4", ".", "7" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2428-L2439
4,413
phaethon/kamene
kamene/contrib/gsm_um.py
ptmsiReallocationComplete
def ptmsiReallocationComplete(): """P-TMSI REALLOCATION COMPLETE Section 9.4.8""" a = TpPd(pd=0x3) b = MessageType(mesType=0x11) # 00010001 packet = a / b return packet
python
def ptmsiReallocationComplete(): """P-TMSI REALLOCATION COMPLETE Section 9.4.8""" a = TpPd(pd=0x3) b = MessageType(mesType=0x11) # 00010001 packet = a / b return packet
[ "def", "ptmsiReallocationComplete", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x11", ")", "# 00010001", "packet", "=", "a", "/", "b", "return", "packet" ]
P-TMSI REALLOCATION COMPLETE Section 9.4.8
[ "P", "-", "TMSI", "REALLOCATION", "COMPLETE", "Section", "9", ".", "4", ".", "8" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2442-L2447
4,414
phaethon/kamene
kamene/contrib/gsm_um.py
authenticationAndCipheringRequest
def authenticationAndCipheringRequest( AuthenticationParameterRAND_presence=0, CiphKeySeqNr_presence=0): """AUTHENTICATION AND CIPHERING REQUEST Section 9.4.9""" a = TpPd(pd=0x3) b = MessageType(mesType=0x12) # 00010010 d = CipheringAlgorithmAndImeisvRequest() e = ForceToStandbyAndAcReferenceNumber() packet = a / b / d / e if AuthenticationParameterRAND_presence is 1: g = AuthenticationParameterRAND(ieiAPR=0x21) packet = packet / g if CiphKeySeqNr_presence is 1: h = CiphKeySeqNrHdr(ieiCKSN=0x08, eightBitCKSN=0x0) packet = packet / h return packet
python
def authenticationAndCipheringRequest( AuthenticationParameterRAND_presence=0, CiphKeySeqNr_presence=0): """AUTHENTICATION AND CIPHERING REQUEST Section 9.4.9""" a = TpPd(pd=0x3) b = MessageType(mesType=0x12) # 00010010 d = CipheringAlgorithmAndImeisvRequest() e = ForceToStandbyAndAcReferenceNumber() packet = a / b / d / e if AuthenticationParameterRAND_presence is 1: g = AuthenticationParameterRAND(ieiAPR=0x21) packet = packet / g if CiphKeySeqNr_presence is 1: h = CiphKeySeqNrHdr(ieiCKSN=0x08, eightBitCKSN=0x0) packet = packet / h return packet
[ "def", "authenticationAndCipheringRequest", "(", "AuthenticationParameterRAND_presence", "=", "0", ",", "CiphKeySeqNr_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x12", ")", "# 00010010", "d", "=", "CipheringAlgorithmAndImeisvRequest", "(", ")", "e", "=", "ForceToStandbyAndAcReferenceNumber", "(", ")", "packet", "=", "a", "/", "b", "/", "d", "/", "e", "if", "AuthenticationParameterRAND_presence", "is", "1", ":", "g", "=", "AuthenticationParameterRAND", "(", "ieiAPR", "=", "0x21", ")", "packet", "=", "packet", "/", "g", "if", "CiphKeySeqNr_presence", "is", "1", ":", "h", "=", "CiphKeySeqNrHdr", "(", "ieiCKSN", "=", "0x08", ",", "eightBitCKSN", "=", "0x0", ")", "packet", "=", "packet", "/", "h", "return", "packet" ]
AUTHENTICATION AND CIPHERING REQUEST Section 9.4.9
[ "AUTHENTICATION", "AND", "CIPHERING", "REQUEST", "Section", "9", ".", "4", ".", "9" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2450-L2465
4,415
phaethon/kamene
kamene/contrib/gsm_um.py
authenticationAndCipheringResponse
def authenticationAndCipheringResponse( AuthenticationParameterSRES_presence=0, MobileId_presence=0): """AUTHENTICATION AND CIPHERING RESPONSE Section 9.4.10""" a = TpPd(pd=0x3) b = MessageType(mesType=0x13) # 00010011 c = AcReferenceNumberAndSpareHalfOctets() packet = a / b / c if AuthenticationParameterSRES_presence is 1: e = AuthenticationParameterSRES(ieiAPS=0x22) packet = packet / e if MobileId_presence is 1: f = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0) packet = packet / f return packet
python
def authenticationAndCipheringResponse( AuthenticationParameterSRES_presence=0, MobileId_presence=0): """AUTHENTICATION AND CIPHERING RESPONSE Section 9.4.10""" a = TpPd(pd=0x3) b = MessageType(mesType=0x13) # 00010011 c = AcReferenceNumberAndSpareHalfOctets() packet = a / b / c if AuthenticationParameterSRES_presence is 1: e = AuthenticationParameterSRES(ieiAPS=0x22) packet = packet / e if MobileId_presence is 1: f = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0) packet = packet / f return packet
[ "def", "authenticationAndCipheringResponse", "(", "AuthenticationParameterSRES_presence", "=", "0", ",", "MobileId_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x13", ")", "# 00010011", "c", "=", "AcReferenceNumberAndSpareHalfOctets", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "if", "AuthenticationParameterSRES_presence", "is", "1", ":", "e", "=", "AuthenticationParameterSRES", "(", "ieiAPS", "=", "0x22", ")", "packet", "=", "packet", "/", "e", "if", "MobileId_presence", "is", "1", ":", "f", "=", "MobileIdHdr", "(", "ieiMI", "=", "0x23", ",", "eightBitMI", "=", "0x0", ")", "packet", "=", "packet", "/", "f", "return", "packet" ]
AUTHENTICATION AND CIPHERING RESPONSE Section 9.4.10
[ "AUTHENTICATION", "AND", "CIPHERING", "RESPONSE", "Section", "9", ".", "4", ".", "10" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2468-L2482
4,416
phaethon/kamene
kamene/contrib/gsm_um.py
authenticationAndCipheringReject
def authenticationAndCipheringReject(): """AUTHENTICATION AND CIPHERING REJECT Section 9.4.11""" a = TpPd(pd=0x3) b = MessageType(mesType=0x14) # 00010100 packet = a / b return packet
python
def authenticationAndCipheringReject(): """AUTHENTICATION AND CIPHERING REJECT Section 9.4.11""" a = TpPd(pd=0x3) b = MessageType(mesType=0x14) # 00010100 packet = a / b return packet
[ "def", "authenticationAndCipheringReject", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x14", ")", "# 00010100", "packet", "=", "a", "/", "b", "return", "packet" ]
AUTHENTICATION AND CIPHERING REJECT Section 9.4.11
[ "AUTHENTICATION", "AND", "CIPHERING", "REJECT", "Section", "9", ".", "4", ".", "11" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2485-L2490
4,417
phaethon/kamene
kamene/contrib/gsm_um.py
routingAreaUpdateRequest
def routingAreaUpdateRequest(PTmsiSignature_presence=0, GprsTimer_presence=0, DrxParameter_presence=0, TmsiStatus_presence=0): """ROUTING AREA UPDATE REQUEST Section 9.4.14""" a = TpPd(pd=0x3) b = MessageType(mesType=0x8) # 00001000 c = UpdateTypeAndCiphKeySeqNr() e = RoutingAreaIdentification() f = MsNetworkCapability() packet = a / b / c / e / f if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g if GprsTimer_presence is 1: h = GprsTimer(ieiGT=0x17) packet = packet / h if DrxParameter_presence is 1: i = DrxParameter(ieiDP=0x27) packet = packet / i if TmsiStatus_presence is 1: j = TmsiStatus(ieiTS=0x9) packet = packet / j return packet
python
def routingAreaUpdateRequest(PTmsiSignature_presence=0, GprsTimer_presence=0, DrxParameter_presence=0, TmsiStatus_presence=0): """ROUTING AREA UPDATE REQUEST Section 9.4.14""" a = TpPd(pd=0x3) b = MessageType(mesType=0x8) # 00001000 c = UpdateTypeAndCiphKeySeqNr() e = RoutingAreaIdentification() f = MsNetworkCapability() packet = a / b / c / e / f if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g if GprsTimer_presence is 1: h = GprsTimer(ieiGT=0x17) packet = packet / h if DrxParameter_presence is 1: i = DrxParameter(ieiDP=0x27) packet = packet / i if TmsiStatus_presence is 1: j = TmsiStatus(ieiTS=0x9) packet = packet / j return packet
[ "def", "routingAreaUpdateRequest", "(", "PTmsiSignature_presence", "=", "0", ",", "GprsTimer_presence", "=", "0", ",", "DrxParameter_presence", "=", "0", ",", "TmsiStatus_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x8", ")", "# 00001000", "c", "=", "UpdateTypeAndCiphKeySeqNr", "(", ")", "e", "=", "RoutingAreaIdentification", "(", ")", "f", "=", "MsNetworkCapability", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "e", "/", "f", "if", "PTmsiSignature_presence", "is", "1", ":", "g", "=", "PTmsiSignature", "(", "ieiPTS", "=", "0x19", ")", "packet", "=", "packet", "/", "g", "if", "GprsTimer_presence", "is", "1", ":", "h", "=", "GprsTimer", "(", "ieiGT", "=", "0x17", ")", "packet", "=", "packet", "/", "h", "if", "DrxParameter_presence", "is", "1", ":", "i", "=", "DrxParameter", "(", "ieiDP", "=", "0x27", ")", "packet", "=", "packet", "/", "i", "if", "TmsiStatus_presence", "is", "1", ":", "j", "=", "TmsiStatus", "(", "ieiTS", "=", "0x9", ")", "packet", "=", "packet", "/", "j", "return", "packet" ]
ROUTING AREA UPDATE REQUEST Section 9.4.14
[ "ROUTING", "AREA", "UPDATE", "REQUEST", "Section", "9", ".", "4", ".", "14" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2511-L2534
4,418
phaethon/kamene
kamene/contrib/gsm_um.py
routingAreaUpdateAccept
def routingAreaUpdateAccept(PTmsiSignature_presence=0, MobileId_presence=0, MobileId_presence1=0, ReceiveNpduNumbersList_presence=0, GprsTimer_presence=0, GmmCause_presence=0): """ROUTING AREA UPDATE ACCEPT Section 9.4.15""" a = TpPd(pd=0x3) b = MessageType(mesType=0x9) # 00001001 c = ForceToStandbyAndUpdateResult() e = GprsTimer() f = RoutingAreaIdentification() packet = a / b / c / e / f if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g if MobileId_presence is 1: h = MobileIdHdr(ieiMI=0x18, eightBitMI=0x0) packet = packet / h if MobileId_presence1 is 1: i = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0) packet = packet / i if ReceiveNpduNumbersList_presence is 1: j = ReceiveNpduNumbersList(ieiRNNL=0x26) packet = packet / j if GprsTimer_presence is 1: k = GprsTimer(ieiGT=0x17) packet = packet / k if GmmCause_presence is 1: l = GmmCause(ieiGC=0x25) packet = packet / l return packet
python
def routingAreaUpdateAccept(PTmsiSignature_presence=0, MobileId_presence=0, MobileId_presence1=0, ReceiveNpduNumbersList_presence=0, GprsTimer_presence=0, GmmCause_presence=0): """ROUTING AREA UPDATE ACCEPT Section 9.4.15""" a = TpPd(pd=0x3) b = MessageType(mesType=0x9) # 00001001 c = ForceToStandbyAndUpdateResult() e = GprsTimer() f = RoutingAreaIdentification() packet = a / b / c / e / f if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g if MobileId_presence is 1: h = MobileIdHdr(ieiMI=0x18, eightBitMI=0x0) packet = packet / h if MobileId_presence1 is 1: i = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0) packet = packet / i if ReceiveNpduNumbersList_presence is 1: j = ReceiveNpduNumbersList(ieiRNNL=0x26) packet = packet / j if GprsTimer_presence is 1: k = GprsTimer(ieiGT=0x17) packet = packet / k if GmmCause_presence is 1: l = GmmCause(ieiGC=0x25) packet = packet / l return packet
[ "def", "routingAreaUpdateAccept", "(", "PTmsiSignature_presence", "=", "0", ",", "MobileId_presence", "=", "0", ",", "MobileId_presence1", "=", "0", ",", "ReceiveNpduNumbersList_presence", "=", "0", ",", "GprsTimer_presence", "=", "0", ",", "GmmCause_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x9", ")", "# 00001001", "c", "=", "ForceToStandbyAndUpdateResult", "(", ")", "e", "=", "GprsTimer", "(", ")", "f", "=", "RoutingAreaIdentification", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "e", "/", "f", "if", "PTmsiSignature_presence", "is", "1", ":", "g", "=", "PTmsiSignature", "(", "ieiPTS", "=", "0x19", ")", "packet", "=", "packet", "/", "g", "if", "MobileId_presence", "is", "1", ":", "h", "=", "MobileIdHdr", "(", "ieiMI", "=", "0x18", ",", "eightBitMI", "=", "0x0", ")", "packet", "=", "packet", "/", "h", "if", "MobileId_presence1", "is", "1", ":", "i", "=", "MobileIdHdr", "(", "ieiMI", "=", "0x23", ",", "eightBitMI", "=", "0x0", ")", "packet", "=", "packet", "/", "i", "if", "ReceiveNpduNumbersList_presence", "is", "1", ":", "j", "=", "ReceiveNpduNumbersList", "(", "ieiRNNL", "=", "0x26", ")", "packet", "=", "packet", "/", "j", "if", "GprsTimer_presence", "is", "1", ":", "k", "=", "GprsTimer", "(", "ieiGT", "=", "0x17", ")", "packet", "=", "packet", "/", "k", "if", "GmmCause_presence", "is", "1", ":", "l", "=", "GmmCause", "(", "ieiGC", "=", "0x25", ")", "packet", "=", "packet", "/", "l", "return", "packet" ]
ROUTING AREA UPDATE ACCEPT Section 9.4.15
[ "ROUTING", "AREA", "UPDATE", "ACCEPT", "Section", "9", ".", "4", ".", "15" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2537-L2566
4,419
phaethon/kamene
kamene/contrib/gsm_um.py
routingAreaUpdateComplete
def routingAreaUpdateComplete(ReceiveNpduNumbersList_presence=0): """ROUTING AREA UPDATE COMPLETE Section 9.4.16""" a = TpPd(pd=0x3) b = MessageType(mesType=0xa) # 00001010 packet = a / b if ReceiveNpduNumbersList_presence is 1: c = ReceiveNpduNumbersList(ieiRNNL=0x26) packet = packet / c return packet
python
def routingAreaUpdateComplete(ReceiveNpduNumbersList_presence=0): """ROUTING AREA UPDATE COMPLETE Section 9.4.16""" a = TpPd(pd=0x3) b = MessageType(mesType=0xa) # 00001010 packet = a / b if ReceiveNpduNumbersList_presence is 1: c = ReceiveNpduNumbersList(ieiRNNL=0x26) packet = packet / c return packet
[ "def", "routingAreaUpdateComplete", "(", "ReceiveNpduNumbersList_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0xa", ")", "# 00001010", "packet", "=", "a", "/", "b", "if", "ReceiveNpduNumbersList_presence", "is", "1", ":", "c", "=", "ReceiveNpduNumbersList", "(", "ieiRNNL", "=", "0x26", ")", "packet", "=", "packet", "/", "c", "return", "packet" ]
ROUTING AREA UPDATE COMPLETE Section 9.4.16
[ "ROUTING", "AREA", "UPDATE", "COMPLETE", "Section", "9", ".", "4", ".", "16" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2569-L2577
4,420
phaethon/kamene
kamene/contrib/gsm_um.py
routingAreaUpdateReject
def routingAreaUpdateReject(): """ROUTING AREA UPDATE REJECT Section 9.4.17""" a = TpPd(pd=0x3) b = MessageType(mesType=0xb) # 00001011 c = GmmCause() d = ForceToStandbyAndSpareHalfOctets() packet = a / b / c / d return packet
python
def routingAreaUpdateReject(): """ROUTING AREA UPDATE REJECT Section 9.4.17""" a = TpPd(pd=0x3) b = MessageType(mesType=0xb) # 00001011 c = GmmCause() d = ForceToStandbyAndSpareHalfOctets() packet = a / b / c / d return packet
[ "def", "routingAreaUpdateReject", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0xb", ")", "# 00001011", "c", "=", "GmmCause", "(", ")", "d", "=", "ForceToStandbyAndSpareHalfOctets", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "return", "packet" ]
ROUTING AREA UPDATE REJECT Section 9.4.17
[ "ROUTING", "AREA", "UPDATE", "REJECT", "Section", "9", ".", "4", ".", "17" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2580-L2587
4,421
phaethon/kamene
kamene/contrib/gsm_um.py
gmmStatus
def gmmStatus(): """GMM STATUS Section 9.4.18""" a = TpPd(pd=0x3) b = MessageType(mesType=0x20) # 00100000 c = GmmCause() packet = a / b / c return packet
python
def gmmStatus(): """GMM STATUS Section 9.4.18""" a = TpPd(pd=0x3) b = MessageType(mesType=0x20) # 00100000 c = GmmCause() packet = a / b / c return packet
[ "def", "gmmStatus", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x20", ")", "# 00100000", "c", "=", "GmmCause", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "return", "packet" ]
GMM STATUS Section 9.4.18
[ "GMM", "STATUS", "Section", "9", ".", "4", ".", "18" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2590-L2596
4,422
phaethon/kamene
kamene/contrib/gsm_um.py
activatePdpContextRequest
def activatePdpContextRequest(AccessPointName_presence=0, ProtocolConfigurationOptions_presence=0): """ACTIVATE PDP CONTEXT REQUEST Section 9.5.1""" a = TpPd(pd=0x8) b = MessageType(mesType=0x41) # 01000001 c = NetworkServiceAccessPointIdentifier() d = LlcServiceAccessPointIdentifier() e = QualityOfService() f = PacketDataProtocolAddress() packet = a / b / c / d / e / f if AccessPointName_presence is 1: g = AccessPointName(ieiAPN=0x28) packet = packet / g if ProtocolConfigurationOptions_presence is 1: h = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / h return packet
python
def activatePdpContextRequest(AccessPointName_presence=0, ProtocolConfigurationOptions_presence=0): """ACTIVATE PDP CONTEXT REQUEST Section 9.5.1""" a = TpPd(pd=0x8) b = MessageType(mesType=0x41) # 01000001 c = NetworkServiceAccessPointIdentifier() d = LlcServiceAccessPointIdentifier() e = QualityOfService() f = PacketDataProtocolAddress() packet = a / b / c / d / e / f if AccessPointName_presence is 1: g = AccessPointName(ieiAPN=0x28) packet = packet / g if ProtocolConfigurationOptions_presence is 1: h = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / h return packet
[ "def", "activatePdpContextRequest", "(", "AccessPointName_presence", "=", "0", ",", "ProtocolConfigurationOptions_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x41", ")", "# 01000001", "c", "=", "NetworkServiceAccessPointIdentifier", "(", ")", "d", "=", "LlcServiceAccessPointIdentifier", "(", ")", "e", "=", "QualityOfService", "(", ")", "f", "=", "PacketDataProtocolAddress", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "/", "e", "/", "f", "if", "AccessPointName_presence", "is", "1", ":", "g", "=", "AccessPointName", "(", "ieiAPN", "=", "0x28", ")", "packet", "=", "packet", "/", "g", "if", "ProtocolConfigurationOptions_presence", "is", "1", ":", "h", "=", "ProtocolConfigurationOptions", "(", "ieiPCO", "=", "0x27", ")", "packet", "=", "packet", "/", "h", "return", "packet" ]
ACTIVATE PDP CONTEXT REQUEST Section 9.5.1
[ "ACTIVATE", "PDP", "CONTEXT", "REQUEST", "Section", "9", ".", "5", ".", "1" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2628-L2644
4,423
phaethon/kamene
kamene/contrib/gsm_um.py
activatePdpContextAccept
def activatePdpContextAccept(PacketDataProtocolAddress_presence=0, ProtocolConfigurationOptions_presence=0): """ACTIVATE PDP CONTEXT ACCEPT Section 9.5.2""" a = TpPd(pd=0x8) b = MessageType(mesType=0x42) # 01000010 c = LlcServiceAccessPointIdentifier() d = QualityOfService() e = RadioPriorityAndSpareHalfOctets() packet = a / b / c / d / e if PacketDataProtocolAddress_presence is 1: f = PacketDataProtocolAddress(ieiPDPA=0x2B) packet = packet / f if ProtocolConfigurationOptions_presence is 1: g = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / g return packet
python
def activatePdpContextAccept(PacketDataProtocolAddress_presence=0, ProtocolConfigurationOptions_presence=0): """ACTIVATE PDP CONTEXT ACCEPT Section 9.5.2""" a = TpPd(pd=0x8) b = MessageType(mesType=0x42) # 01000010 c = LlcServiceAccessPointIdentifier() d = QualityOfService() e = RadioPriorityAndSpareHalfOctets() packet = a / b / c / d / e if PacketDataProtocolAddress_presence is 1: f = PacketDataProtocolAddress(ieiPDPA=0x2B) packet = packet / f if ProtocolConfigurationOptions_presence is 1: g = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / g return packet
[ "def", "activatePdpContextAccept", "(", "PacketDataProtocolAddress_presence", "=", "0", ",", "ProtocolConfigurationOptions_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x42", ")", "# 01000010", "c", "=", "LlcServiceAccessPointIdentifier", "(", ")", "d", "=", "QualityOfService", "(", ")", "e", "=", "RadioPriorityAndSpareHalfOctets", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "/", "e", "if", "PacketDataProtocolAddress_presence", "is", "1", ":", "f", "=", "PacketDataProtocolAddress", "(", "ieiPDPA", "=", "0x2B", ")", "packet", "=", "packet", "/", "f", "if", "ProtocolConfigurationOptions_presence", "is", "1", ":", "g", "=", "ProtocolConfigurationOptions", "(", "ieiPCO", "=", "0x27", ")", "packet", "=", "packet", "/", "g", "return", "packet" ]
ACTIVATE PDP CONTEXT ACCEPT Section 9.5.2
[ "ACTIVATE", "PDP", "CONTEXT", "ACCEPT", "Section", "9", ".", "5", ".", "2" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2647-L2662
4,424
phaethon/kamene
kamene/contrib/gsm_um.py
requestPdpContextActivation
def requestPdpContextActivation(AccessPointName_presence=0): """REQUEST PDP CONTEXT ACTIVATION Section 9.5.4""" a = TpPd(pd=0x8) b = MessageType(mesType=0x44) # 01000100 c = PacketDataProtocolAddress() packet = a / b / c if AccessPointName_presence is 1: d = AccessPointName(ieiAPN=0x28) packet = packet / d return packet
python
def requestPdpContextActivation(AccessPointName_presence=0): """REQUEST PDP CONTEXT ACTIVATION Section 9.5.4""" a = TpPd(pd=0x8) b = MessageType(mesType=0x44) # 01000100 c = PacketDataProtocolAddress() packet = a / b / c if AccessPointName_presence is 1: d = AccessPointName(ieiAPN=0x28) packet = packet / d return packet
[ "def", "requestPdpContextActivation", "(", "AccessPointName_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x44", ")", "# 01000100", "c", "=", "PacketDataProtocolAddress", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "if", "AccessPointName_presence", "is", "1", ":", "d", "=", "AccessPointName", "(", "ieiAPN", "=", "0x28", ")", "packet", "=", "packet", "/", "d", "return", "packet" ]
REQUEST PDP CONTEXT ACTIVATION Section 9.5.4
[ "REQUEST", "PDP", "CONTEXT", "ACTIVATION", "Section", "9", ".", "5", ".", "4" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2677-L2686
4,425
phaethon/kamene
kamene/contrib/gsm_um.py
requestPdpContextActivationReject
def requestPdpContextActivationReject(): """REQUEST PDP CONTEXT ACTIVATION REJECT Section 9.5.5""" a = TpPd(pd=0x8) b = MessageType(mesType=0x45) # 01000101 c = SmCause() packet = a / b / c return packet
python
def requestPdpContextActivationReject(): """REQUEST PDP CONTEXT ACTIVATION REJECT Section 9.5.5""" a = TpPd(pd=0x8) b = MessageType(mesType=0x45) # 01000101 c = SmCause() packet = a / b / c return packet
[ "def", "requestPdpContextActivationReject", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x45", ")", "# 01000101", "c", "=", "SmCause", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "return", "packet" ]
REQUEST PDP CONTEXT ACTIVATION REJECT Section 9.5.5
[ "REQUEST", "PDP", "CONTEXT", "ACTIVATION", "REJECT", "Section", "9", ".", "5", ".", "5" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2689-L2695
4,426
phaethon/kamene
kamene/contrib/gsm_um.py
modifyPdpContextRequest
def modifyPdpContextRequest(): """MODIFY PDP CONTEXT REQUEST Section 9.5.6""" a = TpPd(pd=0x8) b = MessageType(mesType=0x48) # 01001000 c = RadioPriorityAndSpareHalfOctets() d = LlcServiceAccessPointIdentifier() e = QualityOfService() packet = a / b / c / d / e return packet
python
def modifyPdpContextRequest(): """MODIFY PDP CONTEXT REQUEST Section 9.5.6""" a = TpPd(pd=0x8) b = MessageType(mesType=0x48) # 01001000 c = RadioPriorityAndSpareHalfOctets() d = LlcServiceAccessPointIdentifier() e = QualityOfService() packet = a / b / c / d / e return packet
[ "def", "modifyPdpContextRequest", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x48", ")", "# 01001000", "c", "=", "RadioPriorityAndSpareHalfOctets", "(", ")", "d", "=", "LlcServiceAccessPointIdentifier", "(", ")", "e", "=", "QualityOfService", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "/", "e", "return", "packet" ]
MODIFY PDP CONTEXT REQUEST Section 9.5.6
[ "MODIFY", "PDP", "CONTEXT", "REQUEST", "Section", "9", ".", "5", ".", "6" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2698-L2706
4,427
phaethon/kamene
kamene/contrib/gsm_um.py
modifyPdpContextAccept
def modifyPdpContextAccept(): """MODIFY PDP CONTEXT ACCEPT Section 9.5.7""" a = TpPd(pd=0x8) b = MessageType(mesType=0x45) # 01000101 packet = a / b return packet
python
def modifyPdpContextAccept(): """MODIFY PDP CONTEXT ACCEPT Section 9.5.7""" a = TpPd(pd=0x8) b = MessageType(mesType=0x45) # 01000101 packet = a / b return packet
[ "def", "modifyPdpContextAccept", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x45", ")", "# 01000101", "packet", "=", "a", "/", "b", "return", "packet" ]
MODIFY PDP CONTEXT ACCEPT Section 9.5.7
[ "MODIFY", "PDP", "CONTEXT", "ACCEPT", "Section", "9", ".", "5", ".", "7" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2709-L2714
4,428
phaethon/kamene
kamene/contrib/gsm_um.py
deactivatePdpContextAccept
def deactivatePdpContextAccept(): """DEACTIVATE PDP CONTEXT ACCEPT Section 9.5.9""" a = TpPd(pd=0x8) b = MessageType(mesType=0x47) # 01000111 packet = a / b return packet
python
def deactivatePdpContextAccept(): """DEACTIVATE PDP CONTEXT ACCEPT Section 9.5.9""" a = TpPd(pd=0x8) b = MessageType(mesType=0x47) # 01000111 packet = a / b return packet
[ "def", "deactivatePdpContextAccept", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x47", ")", "# 01000111", "packet", "=", "a", "/", "b", "return", "packet" ]
DEACTIVATE PDP CONTEXT ACCEPT Section 9.5.9
[ "DEACTIVATE", "PDP", "CONTEXT", "ACCEPT", "Section", "9", ".", "5", ".", "9" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2726-L2731
4,429
phaethon/kamene
kamene/contrib/gsm_um.py
activateAaPdpContextRequest
def activateAaPdpContextRequest(AccessPointName_presence=0, ProtocolConfigurationOptions_presence=0, GprsTimer_presence=0): """ACTIVATE AA PDP CONTEXT REQUEST Section 9.5.10""" a = TpPd(pd=0x8) b = MessageType(mesType=0x50) # 01010000 c = NetworkServiceAccessPointIdentifier() d = LlcServiceAccessPointIdentifier() e = QualityOfService() f = PacketDataProtocolAddress() packet = a / b / c / d / e / f if AccessPointName_presence is 1: g = AccessPointName(ieiAPN=0x28) packet = packet / g if ProtocolConfigurationOptions_presence is 1: h = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / h if GprsTimer_presence is 1: i = GprsTimer(ieiGT=0x29) packet = packet / i return packet
python
def activateAaPdpContextRequest(AccessPointName_presence=0, ProtocolConfigurationOptions_presence=0, GprsTimer_presence=0): """ACTIVATE AA PDP CONTEXT REQUEST Section 9.5.10""" a = TpPd(pd=0x8) b = MessageType(mesType=0x50) # 01010000 c = NetworkServiceAccessPointIdentifier() d = LlcServiceAccessPointIdentifier() e = QualityOfService() f = PacketDataProtocolAddress() packet = a / b / c / d / e / f if AccessPointName_presence is 1: g = AccessPointName(ieiAPN=0x28) packet = packet / g if ProtocolConfigurationOptions_presence is 1: h = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / h if GprsTimer_presence is 1: i = GprsTimer(ieiGT=0x29) packet = packet / i return packet
[ "def", "activateAaPdpContextRequest", "(", "AccessPointName_presence", "=", "0", ",", "ProtocolConfigurationOptions_presence", "=", "0", ",", "GprsTimer_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x50", ")", "# 01010000", "c", "=", "NetworkServiceAccessPointIdentifier", "(", ")", "d", "=", "LlcServiceAccessPointIdentifier", "(", ")", "e", "=", "QualityOfService", "(", ")", "f", "=", "PacketDataProtocolAddress", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "/", "e", "/", "f", "if", "AccessPointName_presence", "is", "1", ":", "g", "=", "AccessPointName", "(", "ieiAPN", "=", "0x28", ")", "packet", "=", "packet", "/", "g", "if", "ProtocolConfigurationOptions_presence", "is", "1", ":", "h", "=", "ProtocolConfigurationOptions", "(", "ieiPCO", "=", "0x27", ")", "packet", "=", "packet", "/", "h", "if", "GprsTimer_presence", "is", "1", ":", "i", "=", "GprsTimer", "(", "ieiGT", "=", "0x29", ")", "packet", "=", "packet", "/", "i", "return", "packet" ]
ACTIVATE AA PDP CONTEXT REQUEST Section 9.5.10
[ "ACTIVATE", "AA", "PDP", "CONTEXT", "REQUEST", "Section", "9", ".", "5", ".", "10" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2734-L2754
4,430
phaethon/kamene
kamene/contrib/gsm_um.py
activateAaPdpContextAccept
def activateAaPdpContextAccept(ProtocolConfigurationOptions_presence=0, GprsTimer_presence=0): """ACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.11""" a = TpPd(pd=0x8) b = MessageType(mesType=0x51) # 01010001 c = LlcServiceAccessPointIdentifier() d = QualityOfService() e = MobileId() f = PacketDataProtocolAddress() g = RadioPriorityAndSpareHalfOctets() packet = a / b / c / d / e / f / g if ProtocolConfigurationOptions_presence is 1: i = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / i if GprsTimer_presence is 1: j = GprsTimer(ieiGT=0x29) packet = packet / j return packet
python
def activateAaPdpContextAccept(ProtocolConfigurationOptions_presence=0, GprsTimer_presence=0): """ACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.11""" a = TpPd(pd=0x8) b = MessageType(mesType=0x51) # 01010001 c = LlcServiceAccessPointIdentifier() d = QualityOfService() e = MobileId() f = PacketDataProtocolAddress() g = RadioPriorityAndSpareHalfOctets() packet = a / b / c / d / e / f / g if ProtocolConfigurationOptions_presence is 1: i = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / i if GprsTimer_presence is 1: j = GprsTimer(ieiGT=0x29) packet = packet / j return packet
[ "def", "activateAaPdpContextAccept", "(", "ProtocolConfigurationOptions_presence", "=", "0", ",", "GprsTimer_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x51", ")", "# 01010001", "c", "=", "LlcServiceAccessPointIdentifier", "(", ")", "d", "=", "QualityOfService", "(", ")", "e", "=", "MobileId", "(", ")", "f", "=", "PacketDataProtocolAddress", "(", ")", "g", "=", "RadioPriorityAndSpareHalfOctets", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "/", "d", "/", "e", "/", "f", "/", "g", "if", "ProtocolConfigurationOptions_presence", "is", "1", ":", "i", "=", "ProtocolConfigurationOptions", "(", "ieiPCO", "=", "0x27", ")", "packet", "=", "packet", "/", "i", "if", "GprsTimer_presence", "is", "1", ":", "j", "=", "GprsTimer", "(", "ieiGT", "=", "0x29", ")", "packet", "=", "packet", "/", "j", "return", "packet" ]
ACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.11
[ "ACTIVATE", "AA", "PDP", "CONTEXT", "ACCEPT", "Section", "9", ".", "5", ".", "11" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2757-L2774
4,431
phaethon/kamene
kamene/contrib/gsm_um.py
activateAaPdpContextReject
def activateAaPdpContextReject(ProtocolConfigurationOptions_presence=0): """ACTIVATE AA PDP CONTEXT REJECT Section 9.5.12""" a = TpPd(pd=0x8) b = MessageType(mesType=0x52) # 01010010 c = SmCause() packet = a / b / c if ProtocolConfigurationOptions_presence is 1: d = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / d return packet
python
def activateAaPdpContextReject(ProtocolConfigurationOptions_presence=0): """ACTIVATE AA PDP CONTEXT REJECT Section 9.5.12""" a = TpPd(pd=0x8) b = MessageType(mesType=0x52) # 01010010 c = SmCause() packet = a / b / c if ProtocolConfigurationOptions_presence is 1: d = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / d return packet
[ "def", "activateAaPdpContextReject", "(", "ProtocolConfigurationOptions_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x52", ")", "# 01010010", "c", "=", "SmCause", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "if", "ProtocolConfigurationOptions_presence", "is", "1", ":", "d", "=", "ProtocolConfigurationOptions", "(", "ieiPCO", "=", "0x27", ")", "packet", "=", "packet", "/", "d", "return", "packet" ]
ACTIVATE AA PDP CONTEXT REJECT Section 9.5.12
[ "ACTIVATE", "AA", "PDP", "CONTEXT", "REJECT", "Section", "9", ".", "5", ".", "12" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2777-L2786
4,432
phaethon/kamene
kamene/contrib/gsm_um.py
deactivateAaPdpContextRequest
def deactivateAaPdpContextRequest(): """DEACTIVATE AA PDP CONTEXT REQUEST Section 9.5.13""" a = TpPd(pd=0x8) b = MessageType(mesType=0x53) # 01010011 c = AaDeactivationCauseAndSpareHalfOctets() packet = a / b / c return packet
python
def deactivateAaPdpContextRequest(): """DEACTIVATE AA PDP CONTEXT REQUEST Section 9.5.13""" a = TpPd(pd=0x8) b = MessageType(mesType=0x53) # 01010011 c = AaDeactivationCauseAndSpareHalfOctets() packet = a / b / c return packet
[ "def", "deactivateAaPdpContextRequest", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x53", ")", "# 01010011", "c", "=", "AaDeactivationCauseAndSpareHalfOctets", "(", ")", "packet", "=", "a", "/", "b", "/", "c", "return", "packet" ]
DEACTIVATE AA PDP CONTEXT REQUEST Section 9.5.13
[ "DEACTIVATE", "AA", "PDP", "CONTEXT", "REQUEST", "Section", "9", ".", "5", ".", "13" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2789-L2795
4,433
phaethon/kamene
kamene/contrib/gsm_um.py
deactivateAaPdpContextAccept
def deactivateAaPdpContextAccept(): """DEACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.14""" a = TpPd(pd=0x8) b = MessageType(mesType=0x54) # 01010100 packet = a / b return packet
python
def deactivateAaPdpContextAccept(): """DEACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.14""" a = TpPd(pd=0x8) b = MessageType(mesType=0x54) # 01010100 packet = a / b return packet
[ "def", "deactivateAaPdpContextAccept", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x54", ")", "# 01010100", "packet", "=", "a", "/", "b", "return", "packet" ]
DEACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.14
[ "DEACTIVATE", "AA", "PDP", "CONTEXT", "ACCEPT", "Section", "9", ".", "5", ".", "14" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2798-L2803
4,434
phaethon/kamene
kamene/packet.py
ls
def ls(obj=None): """List available layers, or infos on a given layer""" if obj is None: import builtins all = builtins.__dict__.copy() all.update(globals()) objlst = sorted(conf.layers, key=lambda x:x.__name__) for o in objlst: print("%-10s : %s" %(o.__name__,o.name)) else: if isinstance(obj, type) and issubclass(obj, Packet): for f in obj.fields_desc: print("%-10s : %-20s = (%s)" % (f.name, f.__class__.__name__, repr(f.default))) elif isinstance(obj, Packet): for f in obj.fields_desc: print("%-10s : %-20s = %-15s (%s)" % (f.name, f.__class__.__name__, repr(getattr(obj,f.name)), repr(f.default))) if not isinstance(obj.payload, NoPayload): print("--") ls(obj.payload) else: print("Not a packet class. Type 'ls()' to list packet classes.")
python
def ls(obj=None): """List available layers, or infos on a given layer""" if obj is None: import builtins all = builtins.__dict__.copy() all.update(globals()) objlst = sorted(conf.layers, key=lambda x:x.__name__) for o in objlst: print("%-10s : %s" %(o.__name__,o.name)) else: if isinstance(obj, type) and issubclass(obj, Packet): for f in obj.fields_desc: print("%-10s : %-20s = (%s)" % (f.name, f.__class__.__name__, repr(f.default))) elif isinstance(obj, Packet): for f in obj.fields_desc: print("%-10s : %-20s = %-15s (%s)" % (f.name, f.__class__.__name__, repr(getattr(obj,f.name)), repr(f.default))) if not isinstance(obj.payload, NoPayload): print("--") ls(obj.payload) else: print("Not a packet class. Type 'ls()' to list packet classes.")
[ "def", "ls", "(", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "import", "builtins", "all", "=", "builtins", ".", "__dict__", ".", "copy", "(", ")", "all", ".", "update", "(", "globals", "(", ")", ")", "objlst", "=", "sorted", "(", "conf", ".", "layers", ",", "key", "=", "lambda", "x", ":", "x", ".", "__name__", ")", "for", "o", "in", "objlst", ":", "print", "(", "\"%-10s : %s\"", "%", "(", "o", ".", "__name__", ",", "o", ".", "name", ")", ")", "else", ":", "if", "isinstance", "(", "obj", ",", "type", ")", "and", "issubclass", "(", "obj", ",", "Packet", ")", ":", "for", "f", "in", "obj", ".", "fields_desc", ":", "print", "(", "\"%-10s : %-20s = (%s)\"", "%", "(", "f", ".", "name", ",", "f", ".", "__class__", ".", "__name__", ",", "repr", "(", "f", ".", "default", ")", ")", ")", "elif", "isinstance", "(", "obj", ",", "Packet", ")", ":", "for", "f", "in", "obj", ".", "fields_desc", ":", "print", "(", "\"%-10s : %-20s = %-15s (%s)\"", "%", "(", "f", ".", "name", ",", "f", ".", "__class__", ".", "__name__", ",", "repr", "(", "getattr", "(", "obj", ",", "f", ".", "name", ")", ")", ",", "repr", "(", "f", ".", "default", ")", ")", ")", "if", "not", "isinstance", "(", "obj", ".", "payload", ",", "NoPayload", ")", ":", "print", "(", "\"--\"", ")", "ls", "(", "obj", ".", "payload", ")", "else", ":", "print", "(", "\"Not a packet class. Type 'ls()' to list packet classes.\"", ")" ]
List available layers, or infos on a given layer
[ "List", "available", "layers", "or", "infos", "on", "a", "given", "layer" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/packet.py#L1250-L1273
4,435
phaethon/kamene
kamene/packet.py
Packet.haslayer
def haslayer(self, cls): """true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.""" if self.__class__ == cls or self.__class__.__name__ == cls: return 1 for f in self.packetfields: fvalue_gen = self.getfieldval(f.name) if fvalue_gen is None: continue if not f.islist: fvalue_gen = SetGen(fvalue_gen,_iterpacket=0) for fvalue in fvalue_gen: if isinstance(fvalue, Packet): ret = fvalue.haslayer(cls) if ret: return ret return self.payload.haslayer(cls)
python
def haslayer(self, cls): """true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.""" if self.__class__ == cls or self.__class__.__name__ == cls: return 1 for f in self.packetfields: fvalue_gen = self.getfieldval(f.name) if fvalue_gen is None: continue if not f.islist: fvalue_gen = SetGen(fvalue_gen,_iterpacket=0) for fvalue in fvalue_gen: if isinstance(fvalue, Packet): ret = fvalue.haslayer(cls) if ret: return ret return self.payload.haslayer(cls)
[ "def", "haslayer", "(", "self", ",", "cls", ")", ":", "if", "self", ".", "__class__", "==", "cls", "or", "self", ".", "__class__", ".", "__name__", "==", "cls", ":", "return", "1", "for", "f", "in", "self", ".", "packetfields", ":", "fvalue_gen", "=", "self", ".", "getfieldval", "(", "f", ".", "name", ")", "if", "fvalue_gen", "is", "None", ":", "continue", "if", "not", "f", ".", "islist", ":", "fvalue_gen", "=", "SetGen", "(", "fvalue_gen", ",", "_iterpacket", "=", "0", ")", "for", "fvalue", "in", "fvalue_gen", ":", "if", "isinstance", "(", "fvalue", ",", "Packet", ")", ":", "ret", "=", "fvalue", ".", "haslayer", "(", "cls", ")", "if", "ret", ":", "return", "ret", "return", "self", ".", "payload", ".", "haslayer", "(", "cls", ")" ]
true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.
[ "true", "if", "self", "has", "a", "layer", "that", "is", "an", "instance", "of", "cls", ".", "Superseded", "by", "cls", "in", "self", "syntax", "." ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/packet.py#L749-L764
4,436
phaethon/kamene
kamene/packet.py
Packet.getlayer
def getlayer(self, cls, nb=1, _track=None): """Return the nb^th layer that is an instance of cls.""" if type(cls) is int: nb = cls+1 cls = None if type(cls) is str and "." in cls: ccls,fld = cls.split(".",1) else: ccls,fld = cls,None if cls is None or self.__class__ == cls or self.__class__.name == ccls: if nb == 1: if fld is None: return self else: return self.getfieldval(fld) else: nb -=1 for f in self.packetfields: fvalue_gen = self.getfieldval(f.name) if fvalue_gen is None: continue if not f.islist: fvalue_gen = SetGen(fvalue_gen,_iterpacket=0) for fvalue in fvalue_gen: if isinstance(fvalue, Packet): track=[] ret = fvalue.getlayer(cls, nb, _track=track) if ret is not None: return ret nb = track[0] return self.payload.getlayer(cls,nb,_track=_track)
python
def getlayer(self, cls, nb=1, _track=None): """Return the nb^th layer that is an instance of cls.""" if type(cls) is int: nb = cls+1 cls = None if type(cls) is str and "." in cls: ccls,fld = cls.split(".",1) else: ccls,fld = cls,None if cls is None or self.__class__ == cls or self.__class__.name == ccls: if nb == 1: if fld is None: return self else: return self.getfieldval(fld) else: nb -=1 for f in self.packetfields: fvalue_gen = self.getfieldval(f.name) if fvalue_gen is None: continue if not f.islist: fvalue_gen = SetGen(fvalue_gen,_iterpacket=0) for fvalue in fvalue_gen: if isinstance(fvalue, Packet): track=[] ret = fvalue.getlayer(cls, nb, _track=track) if ret is not None: return ret nb = track[0] return self.payload.getlayer(cls,nb,_track=_track)
[ "def", "getlayer", "(", "self", ",", "cls", ",", "nb", "=", "1", ",", "_track", "=", "None", ")", ":", "if", "type", "(", "cls", ")", "is", "int", ":", "nb", "=", "cls", "+", "1", "cls", "=", "None", "if", "type", "(", "cls", ")", "is", "str", "and", "\".\"", "in", "cls", ":", "ccls", ",", "fld", "=", "cls", ".", "split", "(", "\".\"", ",", "1", ")", "else", ":", "ccls", ",", "fld", "=", "cls", ",", "None", "if", "cls", "is", "None", "or", "self", ".", "__class__", "==", "cls", "or", "self", ".", "__class__", ".", "name", "==", "ccls", ":", "if", "nb", "==", "1", ":", "if", "fld", "is", "None", ":", "return", "self", "else", ":", "return", "self", ".", "getfieldval", "(", "fld", ")", "else", ":", "nb", "-=", "1", "for", "f", "in", "self", ".", "packetfields", ":", "fvalue_gen", "=", "self", ".", "getfieldval", "(", "f", ".", "name", ")", "if", "fvalue_gen", "is", "None", ":", "continue", "if", "not", "f", ".", "islist", ":", "fvalue_gen", "=", "SetGen", "(", "fvalue_gen", ",", "_iterpacket", "=", "0", ")", "for", "fvalue", "in", "fvalue_gen", ":", "if", "isinstance", "(", "fvalue", ",", "Packet", ")", ":", "track", "=", "[", "]", "ret", "=", "fvalue", ".", "getlayer", "(", "cls", ",", "nb", ",", "_track", "=", "track", ")", "if", "ret", "is", "not", "None", ":", "return", "ret", "nb", "=", "track", "[", "0", "]", "return", "self", ".", "payload", ".", "getlayer", "(", "cls", ",", "nb", ",", "_track", "=", "_track", ")" ]
Return the nb^th layer that is an instance of cls.
[ "Return", "the", "nb^th", "layer", "that", "is", "an", "instance", "of", "cls", "." ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/packet.py#L765-L795
4,437
phaethon/kamene
kamene/packet.py
Packet.show
def show(self, indent=3, lvl="", label_lvl=""): """Prints a hierarchical view of the packet. "indent" gives the size of indentation for each layer.""" ct = conf.color_theme print("%s%s %s %s" % (label_lvl, ct.punct("###["), ct.layer_name(self.name), ct.punct("]###"))) for f in self.fields_desc: if isinstance(f, ConditionalField) and not f._evalcond(self): continue if isinstance(f, Emph) or f in conf.emph: ncol = ct.emph_field_name vcol = ct.emph_field_value else: ncol = ct.field_name vcol = ct.field_value fvalue = self.getfieldval(f.name) if isinstance(fvalue, Packet) or (f.islist and f.holds_packets and type(fvalue) is list): print("%s \\%-10s\\" % (label_lvl+lvl, ncol(f.name))) fvalue_gen = SetGen(fvalue,_iterpacket=0) for fvalue in fvalue_gen: fvalue.show(indent=indent, label_lvl=label_lvl+lvl+" |") else: begn = "%s %-10s%s " % (label_lvl+lvl, ncol(f.name), ct.punct("="),) reprval = f.i2repr(self,fvalue) if type(reprval) is str: reprval = reprval.replace("\n", "\n"+" "*(len(label_lvl) +len(lvl) +len(f.name) +4)) print("%s%s" % (begn,vcol(reprval))) self.payload.show(indent=indent, lvl=lvl+(" "*indent*self.show_indent), label_lvl=label_lvl)
python
def show(self, indent=3, lvl="", label_lvl=""): """Prints a hierarchical view of the packet. "indent" gives the size of indentation for each layer.""" ct = conf.color_theme print("%s%s %s %s" % (label_lvl, ct.punct("###["), ct.layer_name(self.name), ct.punct("]###"))) for f in self.fields_desc: if isinstance(f, ConditionalField) and not f._evalcond(self): continue if isinstance(f, Emph) or f in conf.emph: ncol = ct.emph_field_name vcol = ct.emph_field_value else: ncol = ct.field_name vcol = ct.field_value fvalue = self.getfieldval(f.name) if isinstance(fvalue, Packet) or (f.islist and f.holds_packets and type(fvalue) is list): print("%s \\%-10s\\" % (label_lvl+lvl, ncol(f.name))) fvalue_gen = SetGen(fvalue,_iterpacket=0) for fvalue in fvalue_gen: fvalue.show(indent=indent, label_lvl=label_lvl+lvl+" |") else: begn = "%s %-10s%s " % (label_lvl+lvl, ncol(f.name), ct.punct("="),) reprval = f.i2repr(self,fvalue) if type(reprval) is str: reprval = reprval.replace("\n", "\n"+" "*(len(label_lvl) +len(lvl) +len(f.name) +4)) print("%s%s" % (begn,vcol(reprval))) self.payload.show(indent=indent, lvl=lvl+(" "*indent*self.show_indent), label_lvl=label_lvl)
[ "def", "show", "(", "self", ",", "indent", "=", "3", ",", "lvl", "=", "\"\"", ",", "label_lvl", "=", "\"\"", ")", ":", "ct", "=", "conf", ".", "color_theme", "print", "(", "\"%s%s %s %s\"", "%", "(", "label_lvl", ",", "ct", ".", "punct", "(", "\"###[\"", ")", ",", "ct", ".", "layer_name", "(", "self", ".", "name", ")", ",", "ct", ".", "punct", "(", "\"]###\"", ")", ")", ")", "for", "f", "in", "self", ".", "fields_desc", ":", "if", "isinstance", "(", "f", ",", "ConditionalField", ")", "and", "not", "f", ".", "_evalcond", "(", "self", ")", ":", "continue", "if", "isinstance", "(", "f", ",", "Emph", ")", "or", "f", "in", "conf", ".", "emph", ":", "ncol", "=", "ct", ".", "emph_field_name", "vcol", "=", "ct", ".", "emph_field_value", "else", ":", "ncol", "=", "ct", ".", "field_name", "vcol", "=", "ct", ".", "field_value", "fvalue", "=", "self", ".", "getfieldval", "(", "f", ".", "name", ")", "if", "isinstance", "(", "fvalue", ",", "Packet", ")", "or", "(", "f", ".", "islist", "and", "f", ".", "holds_packets", "and", "type", "(", "fvalue", ")", "is", "list", ")", ":", "print", "(", "\"%s \\\\%-10s\\\\\"", "%", "(", "label_lvl", "+", "lvl", ",", "ncol", "(", "f", ".", "name", ")", ")", ")", "fvalue_gen", "=", "SetGen", "(", "fvalue", ",", "_iterpacket", "=", "0", ")", "for", "fvalue", "in", "fvalue_gen", ":", "fvalue", ".", "show", "(", "indent", "=", "indent", ",", "label_lvl", "=", "label_lvl", "+", "lvl", "+", "\" |\"", ")", "else", ":", "begn", "=", "\"%s %-10s%s \"", "%", "(", "label_lvl", "+", "lvl", ",", "ncol", "(", "f", ".", "name", ")", ",", "ct", ".", "punct", "(", "\"=\"", ")", ",", ")", "reprval", "=", "f", ".", "i2repr", "(", "self", ",", "fvalue", ")", "if", "type", "(", "reprval", ")", "is", "str", ":", "reprval", "=", "reprval", ".", "replace", "(", "\"\\n\"", ",", "\"\\n\"", "+", "\" \"", "*", "(", "len", "(", "label_lvl", ")", "+", "len", "(", "lvl", ")", "+", "len", "(", "f", ".", "name", ")", "+", "4", ")", ")", "print", "(", "\"%s%s\"", "%", "(", "begn", ",", "vcol", "(", "reprval", ")", ")", ")", "self", ".", "payload", ".", "show", "(", "indent", "=", "indent", ",", "lvl", "=", "lvl", "+", "(", "\" \"", "*", "indent", "*", "self", ".", "show_indent", ")", ",", "label_lvl", "=", "label_lvl", ")" ]
Prints a hierarchical view of the packet. "indent" gives the size of indentation for each layer.
[ "Prints", "a", "hierarchical", "view", "of", "the", "packet", ".", "indent", "gives", "the", "size", "of", "indentation", "for", "each", "layer", "." ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/packet.py#L843-L876
4,438
phaethon/kamene
kamene/packet.py
Packet.decode_payload_as
def decode_payload_as(self,cls): """Reassembles the payload and decode it using another packet class""" s = bytes(self.payload) self.payload = cls(s, _internal=1, _underlayer=self) pp = self while pp.underlayer is not None: pp = pp.underlayer self.payload.dissection_done(pp)
python
def decode_payload_as(self,cls): """Reassembles the payload and decode it using another packet class""" s = bytes(self.payload) self.payload = cls(s, _internal=1, _underlayer=self) pp = self while pp.underlayer is not None: pp = pp.underlayer self.payload.dissection_done(pp)
[ "def", "decode_payload_as", "(", "self", ",", "cls", ")", ":", "s", "=", "bytes", "(", "self", ".", "payload", ")", "self", ".", "payload", "=", "cls", "(", "s", ",", "_internal", "=", "1", ",", "_underlayer", "=", "self", ")", "pp", "=", "self", "while", "pp", ".", "underlayer", "is", "not", "None", ":", "pp", "=", "pp", ".", "underlayer", "self", ".", "payload", ".", "dissection_done", "(", "pp", ")" ]
Reassembles the payload and decode it using another packet class
[ "Reassembles", "the", "payload", "and", "decode", "it", "using", "another", "packet", "class" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/packet.py#L1026-L1033
4,439
phaethon/kamene
kamene/packet.py
Packet.libnet
def libnet(self): """Not ready yet. Should give the necessary C code that interfaces with libnet to recreate the packet""" print("libnet_build_%s(" % self.__class__.name.lower()) det = self.__class__(str(self)) for f in self.fields_desc: val = det.getfieldval(f.name) if val is None: val = 0 elif type(val) is int: val = str(val) else: val = '"%s"' % str(val) print("\t%s, \t\t/* %s */" % (val,f.name)) print(");")
python
def libnet(self): """Not ready yet. Should give the necessary C code that interfaces with libnet to recreate the packet""" print("libnet_build_%s(" % self.__class__.name.lower()) det = self.__class__(str(self)) for f in self.fields_desc: val = det.getfieldval(f.name) if val is None: val = 0 elif type(val) is int: val = str(val) else: val = '"%s"' % str(val) print("\t%s, \t\t/* %s */" % (val,f.name)) print(");")
[ "def", "libnet", "(", "self", ")", ":", "print", "(", "\"libnet_build_%s(\"", "%", "self", ".", "__class__", ".", "name", ".", "lower", "(", ")", ")", "det", "=", "self", ".", "__class__", "(", "str", "(", "self", ")", ")", "for", "f", "in", "self", ".", "fields_desc", ":", "val", "=", "det", ".", "getfieldval", "(", "f", ".", "name", ")", "if", "val", "is", "None", ":", "val", "=", "0", "elif", "type", "(", "val", ")", "is", "int", ":", "val", "=", "str", "(", "val", ")", "else", ":", "val", "=", "'\"%s\"'", "%", "str", "(", "val", ")", "print", "(", "\"\\t%s, \\t\\t/* %s */\"", "%", "(", "val", ",", "f", ".", "name", ")", ")", "print", "(", "\");\"", ")" ]
Not ready yet. Should give the necessary C code that interfaces with libnet to recreate the packet
[ "Not", "ready", "yet", ".", "Should", "give", "the", "necessary", "C", "code", "that", "interfaces", "with", "libnet", "to", "recreate", "the", "packet" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/packet.py#L1035-L1048
4,440
phaethon/kamene
kamene/contrib/doip.py
DoIPRawPacket.dissect
def dissect(self, b): """ Dissect an incoming DoIP packet. :param b: bytes to dissect :type b: bytes :raises: ValueError """ if len(b) < 8: raise ValueError("given packet too short") return super(DoIPRawPacket, self).dissect(b)
python
def dissect(self, b): """ Dissect an incoming DoIP packet. :param b: bytes to dissect :type b: bytes :raises: ValueError """ if len(b) < 8: raise ValueError("given packet too short") return super(DoIPRawPacket, self).dissect(b)
[ "def", "dissect", "(", "self", ",", "b", ")", ":", "if", "len", "(", "b", ")", "<", "8", ":", "raise", "ValueError", "(", "\"given packet too short\"", ")", "return", "super", "(", "DoIPRawPacket", ",", "self", ")", ".", "dissect", "(", "b", ")" ]
Dissect an incoming DoIP packet. :param b: bytes to dissect :type b: bytes :raises: ValueError
[ "Dissect", "an", "incoming", "DoIP", "packet", "." ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/doip.py#L69-L79
4,441
phaethon/kamene
kamene/pton_ntop.py
inet_pton
def inet_pton(af, addr): """Convert an IP address from text representation into binary form""" print('hello') if af == socket.AF_INET: return inet_aton(addr) elif af == socket.AF_INET6: # IPv6: The use of "::" indicates one or more groups of 16 bits of zeros. # We deal with this form of wildcard using a special marker. JOKER = b"*" while b"::" in addr: addr = addr.replace(b"::", b":" + JOKER + b":") joker_pos = None # The last part of an IPv6 address can be an IPv4 address ipv4_addr = None if b"." in addr: ipv4_addr = addr.split(b":")[-1] result = b"" parts = addr.split(b":") for part in parts: if part == JOKER: # Wildcard is only allowed once if joker_pos is None: joker_pos = len(result) else: raise Exception("Illegal syntax for IP address") elif part == ipv4_addr: # FIXME: Make sure IPv4 can only be last part # FIXME: inet_aton allows IPv4 addresses with less than 4 octets result += socket.inet_aton(ipv4_addr) else: # Each part must be 16bit. Add missing zeroes before decoding. try: result += part.rjust(4, b"0").decode("hex") except TypeError: raise Exception("Illegal syntax for IP address") # If there's a wildcard, fill up with zeros to reach 128bit (16 bytes) if JOKER in addr: result = (result[:joker_pos] + b"\x00" * (16 - len(result)) + result[joker_pos:]) if len(result) != 16: raise Exception("Illegal syntax for IP address") return result else: raise Exception("Address family not supported")
python
def inet_pton(af, addr): """Convert an IP address from text representation into binary form""" print('hello') if af == socket.AF_INET: return inet_aton(addr) elif af == socket.AF_INET6: # IPv6: The use of "::" indicates one or more groups of 16 bits of zeros. # We deal with this form of wildcard using a special marker. JOKER = b"*" while b"::" in addr: addr = addr.replace(b"::", b":" + JOKER + b":") joker_pos = None # The last part of an IPv6 address can be an IPv4 address ipv4_addr = None if b"." in addr: ipv4_addr = addr.split(b":")[-1] result = b"" parts = addr.split(b":") for part in parts: if part == JOKER: # Wildcard is only allowed once if joker_pos is None: joker_pos = len(result) else: raise Exception("Illegal syntax for IP address") elif part == ipv4_addr: # FIXME: Make sure IPv4 can only be last part # FIXME: inet_aton allows IPv4 addresses with less than 4 octets result += socket.inet_aton(ipv4_addr) else: # Each part must be 16bit. Add missing zeroes before decoding. try: result += part.rjust(4, b"0").decode("hex") except TypeError: raise Exception("Illegal syntax for IP address") # If there's a wildcard, fill up with zeros to reach 128bit (16 bytes) if JOKER in addr: result = (result[:joker_pos] + b"\x00" * (16 - len(result)) + result[joker_pos:]) if len(result) != 16: raise Exception("Illegal syntax for IP address") return result else: raise Exception("Address family not supported")
[ "def", "inet_pton", "(", "af", ",", "addr", ")", ":", "print", "(", "'hello'", ")", "if", "af", "==", "socket", ".", "AF_INET", ":", "return", "inet_aton", "(", "addr", ")", "elif", "af", "==", "socket", ".", "AF_INET6", ":", "# IPv6: The use of \"::\" indicates one or more groups of 16 bits of zeros.", "# We deal with this form of wildcard using a special marker. ", "JOKER", "=", "b\"*\"", "while", "b\"::\"", "in", "addr", ":", "addr", "=", "addr", ".", "replace", "(", "b\"::\"", ",", "b\":\"", "+", "JOKER", "+", "b\":\"", ")", "joker_pos", "=", "None", "# The last part of an IPv6 address can be an IPv4 address", "ipv4_addr", "=", "None", "if", "b\".\"", "in", "addr", ":", "ipv4_addr", "=", "addr", ".", "split", "(", "b\":\"", ")", "[", "-", "1", "]", "result", "=", "b\"\"", "parts", "=", "addr", ".", "split", "(", "b\":\"", ")", "for", "part", "in", "parts", ":", "if", "part", "==", "JOKER", ":", "# Wildcard is only allowed once", "if", "joker_pos", "is", "None", ":", "joker_pos", "=", "len", "(", "result", ")", "else", ":", "raise", "Exception", "(", "\"Illegal syntax for IP address\"", ")", "elif", "part", "==", "ipv4_addr", ":", "# FIXME: Make sure IPv4 can only be last part", "# FIXME: inet_aton allows IPv4 addresses with less than 4 octets ", "result", "+=", "socket", ".", "inet_aton", "(", "ipv4_addr", ")", "else", ":", "# Each part must be 16bit. Add missing zeroes before decoding. ", "try", ":", "result", "+=", "part", ".", "rjust", "(", "4", ",", "b\"0\"", ")", ".", "decode", "(", "\"hex\"", ")", "except", "TypeError", ":", "raise", "Exception", "(", "\"Illegal syntax for IP address\"", ")", "# If there's a wildcard, fill up with zeros to reach 128bit (16 bytes) ", "if", "JOKER", "in", "addr", ":", "result", "=", "(", "result", "[", ":", "joker_pos", "]", "+", "b\"\\x00\"", "*", "(", "16", "-", "len", "(", "result", ")", ")", "+", "result", "[", "joker_pos", ":", "]", ")", "if", "len", "(", "result", ")", "!=", "16", ":", "raise", "Exception", "(", "\"Illegal syntax for IP address\"", ")", "return", "result", "else", ":", "raise", "Exception", "(", "\"Address family not supported\"", ")" ]
Convert an IP address from text representation into binary form
[ "Convert", "an", "IP", "address", "from", "text", "representation", "into", "binary", "form" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/pton_ntop.py#L15-L61
4,442
phaethon/kamene
kamene/pton_ntop.py
inet_ntop
def inet_ntop(af, addr): """Convert an IP address from binary form into text represenation""" if af == socket.AF_INET: return inet_ntoa(addr) elif af == socket.AF_INET6: # IPv6 addresses have 128bits (16 bytes) if len(addr) != 16: raise Exception("Illegal syntax for IP address") parts = [] for left in [0, 2, 4, 6, 8, 10, 12, 14]: try: value = struct.unpack("!H", addr[left:left+2])[0] hexstr = hex(value)[2:] except TypeError: raise Exception("Illegal syntax for IP address") parts.append(hexstr.lstrip("0").lower()) result = b":".join(parts) while b":::" in result: result = result.replace(b":::", b"::") # Leaving out leading and trailing zeros is only allowed with :: if result.endswith(b":") and not result.endswith(b"::"): result = result + b"0" if result.startswith(b":") and not result.startswith(b"::"): result = b"0" + result return result else: raise Exception("Address family not supported yet")
python
def inet_ntop(af, addr): """Convert an IP address from binary form into text represenation""" if af == socket.AF_INET: return inet_ntoa(addr) elif af == socket.AF_INET6: # IPv6 addresses have 128bits (16 bytes) if len(addr) != 16: raise Exception("Illegal syntax for IP address") parts = [] for left in [0, 2, 4, 6, 8, 10, 12, 14]: try: value = struct.unpack("!H", addr[left:left+2])[0] hexstr = hex(value)[2:] except TypeError: raise Exception("Illegal syntax for IP address") parts.append(hexstr.lstrip("0").lower()) result = b":".join(parts) while b":::" in result: result = result.replace(b":::", b"::") # Leaving out leading and trailing zeros is only allowed with :: if result.endswith(b":") and not result.endswith(b"::"): result = result + b"0" if result.startswith(b":") and not result.startswith(b"::"): result = b"0" + result return result else: raise Exception("Address family not supported yet")
[ "def", "inet_ntop", "(", "af", ",", "addr", ")", ":", "if", "af", "==", "socket", ".", "AF_INET", ":", "return", "inet_ntoa", "(", "addr", ")", "elif", "af", "==", "socket", ".", "AF_INET6", ":", "# IPv6 addresses have 128bits (16 bytes)", "if", "len", "(", "addr", ")", "!=", "16", ":", "raise", "Exception", "(", "\"Illegal syntax for IP address\"", ")", "parts", "=", "[", "]", "for", "left", "in", "[", "0", ",", "2", ",", "4", ",", "6", ",", "8", ",", "10", ",", "12", ",", "14", "]", ":", "try", ":", "value", "=", "struct", ".", "unpack", "(", "\"!H\"", ",", "addr", "[", "left", ":", "left", "+", "2", "]", ")", "[", "0", "]", "hexstr", "=", "hex", "(", "value", ")", "[", "2", ":", "]", "except", "TypeError", ":", "raise", "Exception", "(", "\"Illegal syntax for IP address\"", ")", "parts", ".", "append", "(", "hexstr", ".", "lstrip", "(", "\"0\"", ")", ".", "lower", "(", ")", ")", "result", "=", "b\":\"", ".", "join", "(", "parts", ")", "while", "b\":::\"", "in", "result", ":", "result", "=", "result", ".", "replace", "(", "b\":::\"", ",", "b\"::\"", ")", "# Leaving out leading and trailing zeros is only allowed with ::", "if", "result", ".", "endswith", "(", "b\":\"", ")", "and", "not", "result", ".", "endswith", "(", "b\"::\"", ")", ":", "result", "=", "result", "+", "b\"0\"", "if", "result", ".", "startswith", "(", "b\":\"", ")", "and", "not", "result", ".", "startswith", "(", "b\"::\"", ")", ":", "result", "=", "b\"0\"", "+", "result", "return", "result", "else", ":", "raise", "Exception", "(", "\"Address family not supported yet\"", ")" ]
Convert an IP address from binary form into text represenation
[ "Convert", "an", "IP", "address", "from", "binary", "form", "into", "text", "represenation" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/pton_ntop.py#L64-L90
4,443
phaethon/kamene
kamene/crypto/cert.py
strand
def strand(s1, s2): """ Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2 must be of same length. """ return "".join(map(lambda x,y:chr(ord(x)&ord(y)), s1, s2))
python
def strand(s1, s2): """ Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2 must be of same length. """ return "".join(map(lambda x,y:chr(ord(x)&ord(y)), s1, s2))
[ "def", "strand", "(", "s1", ",", "s2", ")", ":", "return", "\"\"", ".", "join", "(", "map", "(", "lambda", "x", ",", "y", ":", "chr", "(", "ord", "(", "x", ")", "&", "ord", "(", "y", ")", ")", ",", "s1", ",", "s2", ")", ")" ]
Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2 must be of same length.
[ "Returns", "the", "binary", "AND", "of", "the", "2", "provided", "strings", "s1", "and", "s2", ".", "s1", "and", "s2", "must", "be", "of", "same", "length", "." ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/crypto/cert.py#L57-L62
4,444
phaethon/kamene
kamene/crypto/cert.py
pkcs_mgf1
def pkcs_mgf1(mgfSeed, maskLen, h): """ Implements generic MGF1 Mask Generation function as described in Appendix B.2.1 of RFC 3447. The hash function is passed by name. valid values are 'md2', 'md4', 'md5', 'sha1', 'tls, 'sha256', 'sha384' and 'sha512'. Returns None on error. Input: mgfSeed: seed from which mask is generated, an octet string maskLen: intended length in octets of the mask, at most 2^32 * hLen hLen (see below) h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls', 'sha256', 'sha384'). hLen denotes the length in octets of the hash function output. Output: an octet string of length maskLen """ # steps are those of Appendix B.2.1 if not h in _hashFuncParams: warning("pkcs_mgf1: invalid hash (%s) provided") return None hLen = _hashFuncParams[h][0] hFunc = _hashFuncParams[h][1] if maskLen > 2**32 * hLen: # 1) warning("pkcs_mgf1: maskLen > 2**32 * hLen") return None T = "" # 2) maxCounter = math.ceil(float(maskLen) / float(hLen)) # 3) counter = 0 while counter < maxCounter: C = pkcs_i2osp(counter, 4) T += hFunc(mgfSeed + C) counter += 1 return T[:maskLen]
python
def pkcs_mgf1(mgfSeed, maskLen, h): """ Implements generic MGF1 Mask Generation function as described in Appendix B.2.1 of RFC 3447. The hash function is passed by name. valid values are 'md2', 'md4', 'md5', 'sha1', 'tls, 'sha256', 'sha384' and 'sha512'. Returns None on error. Input: mgfSeed: seed from which mask is generated, an octet string maskLen: intended length in octets of the mask, at most 2^32 * hLen hLen (see below) h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls', 'sha256', 'sha384'). hLen denotes the length in octets of the hash function output. Output: an octet string of length maskLen """ # steps are those of Appendix B.2.1 if not h in _hashFuncParams: warning("pkcs_mgf1: invalid hash (%s) provided") return None hLen = _hashFuncParams[h][0] hFunc = _hashFuncParams[h][1] if maskLen > 2**32 * hLen: # 1) warning("pkcs_mgf1: maskLen > 2**32 * hLen") return None T = "" # 2) maxCounter = math.ceil(float(maskLen) / float(hLen)) # 3) counter = 0 while counter < maxCounter: C = pkcs_i2osp(counter, 4) T += hFunc(mgfSeed + C) counter += 1 return T[:maskLen]
[ "def", "pkcs_mgf1", "(", "mgfSeed", ",", "maskLen", ",", "h", ")", ":", "# steps are those of Appendix B.2.1", "if", "not", "h", "in", "_hashFuncParams", ":", "warning", "(", "\"pkcs_mgf1: invalid hash (%s) provided\"", ")", "return", "None", "hLen", "=", "_hashFuncParams", "[", "h", "]", "[", "0", "]", "hFunc", "=", "_hashFuncParams", "[", "h", "]", "[", "1", "]", "if", "maskLen", ">", "2", "**", "32", "*", "hLen", ":", "# 1)", "warning", "(", "\"pkcs_mgf1: maskLen > 2**32 * hLen\"", ")", "return", "None", "T", "=", "\"\"", "# 2)", "maxCounter", "=", "math", ".", "ceil", "(", "float", "(", "maskLen", ")", "/", "float", "(", "hLen", ")", ")", "# 3)", "counter", "=", "0", "while", "counter", "<", "maxCounter", ":", "C", "=", "pkcs_i2osp", "(", "counter", ",", "4", ")", "T", "+=", "hFunc", "(", "mgfSeed", "+", "C", ")", "counter", "+=", "1", "return", "T", "[", ":", "maskLen", "]" ]
Implements generic MGF1 Mask Generation function as described in Appendix B.2.1 of RFC 3447. The hash function is passed by name. valid values are 'md2', 'md4', 'md5', 'sha1', 'tls, 'sha256', 'sha384' and 'sha512'. Returns None on error. Input: mgfSeed: seed from which mask is generated, an octet string maskLen: intended length in octets of the mask, at most 2^32 * hLen hLen (see below) h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls', 'sha256', 'sha384'). hLen denotes the length in octets of the hash function output. Output: an octet string of length maskLen
[ "Implements", "generic", "MGF1", "Mask", "Generation", "function", "as", "described", "in", "Appendix", "B", ".", "2", ".", "1", "of", "RFC", "3447", ".", "The", "hash", "function", "is", "passed", "by", "name", ".", "valid", "values", "are", "md2", "md4", "md5", "sha1", "tls", "sha256", "sha384", "and", "sha512", ".", "Returns", "None", "on", "error", "." ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/crypto/cert.py#L160-L195
4,445
phaethon/kamene
kamene/crypto/cert.py
create_temporary_ca_path
def create_temporary_ca_path(anchor_list, folder): """ Create a CA path folder as defined in OpenSSL terminology, by storing all certificates in 'anchor_list' list in PEM format under provided 'folder' and then creating the associated links using the hash as usually done by c_rehash. Note that you can also include CRL in 'anchor_list'. In that case, they will also be stored under 'folder' and associated links will be created. In folder, the files are created with names of the form 0...ZZ.pem. If you provide an empty list, folder will be created if it does not already exist, but that's all. The number of certificates written to folder is returned on success, None on error. """ # We should probably avoid writing duplicate anchors and also # check if they are all certs. try: if not os.path.isdir(folder): os.makedirs(folder) except: return None l = len(anchor_list) if l == 0: return None fmtstr = "%%0%sd.pem" % math.ceil(math.log(l, 10)) i = 0 try: for a in anchor_list: fname = os.path.join(folder, fmtstr % i) f = open(fname, "w") s = a.output(fmt="PEM") f.write(s) f.close() i += 1 except: return None r,w,e=popen3(["c_rehash", folder]) r.close(); w.close(); e.close() return l
python
def create_temporary_ca_path(anchor_list, folder): """ Create a CA path folder as defined in OpenSSL terminology, by storing all certificates in 'anchor_list' list in PEM format under provided 'folder' and then creating the associated links using the hash as usually done by c_rehash. Note that you can also include CRL in 'anchor_list'. In that case, they will also be stored under 'folder' and associated links will be created. In folder, the files are created with names of the form 0...ZZ.pem. If you provide an empty list, folder will be created if it does not already exist, but that's all. The number of certificates written to folder is returned on success, None on error. """ # We should probably avoid writing duplicate anchors and also # check if they are all certs. try: if not os.path.isdir(folder): os.makedirs(folder) except: return None l = len(anchor_list) if l == 0: return None fmtstr = "%%0%sd.pem" % math.ceil(math.log(l, 10)) i = 0 try: for a in anchor_list: fname = os.path.join(folder, fmtstr % i) f = open(fname, "w") s = a.output(fmt="PEM") f.write(s) f.close() i += 1 except: return None r,w,e=popen3(["c_rehash", folder]) r.close(); w.close(); e.close() return l
[ "def", "create_temporary_ca_path", "(", "anchor_list", ",", "folder", ")", ":", "# We should probably avoid writing duplicate anchors and also", "# check if they are all certs.", "try", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "os", ".", "makedirs", "(", "folder", ")", "except", ":", "return", "None", "l", "=", "len", "(", "anchor_list", ")", "if", "l", "==", "0", ":", "return", "None", "fmtstr", "=", "\"%%0%sd.pem\"", "%", "math", ".", "ceil", "(", "math", ".", "log", "(", "l", ",", "10", ")", ")", "i", "=", "0", "try", ":", "for", "a", "in", "anchor_list", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "fmtstr", "%", "i", ")", "f", "=", "open", "(", "fname", ",", "\"w\"", ")", "s", "=", "a", ".", "output", "(", "fmt", "=", "\"PEM\"", ")", "f", ".", "write", "(", "s", ")", "f", ".", "close", "(", ")", "i", "+=", "1", "except", ":", "return", "None", "r", ",", "w", ",", "e", "=", "popen3", "(", "[", "\"c_rehash\"", ",", "folder", "]", ")", "r", ".", "close", "(", ")", "w", ".", "close", "(", ")", "e", ".", "close", "(", ")", "return", "l" ]
Create a CA path folder as defined in OpenSSL terminology, by storing all certificates in 'anchor_list' list in PEM format under provided 'folder' and then creating the associated links using the hash as usually done by c_rehash. Note that you can also include CRL in 'anchor_list'. In that case, they will also be stored under 'folder' and associated links will be created. In folder, the files are created with names of the form 0...ZZ.pem. If you provide an empty list, folder will be created if it does not already exist, but that's all. The number of certificates written to folder is returned on success, None on error.
[ "Create", "a", "CA", "path", "folder", "as", "defined", "in", "OpenSSL", "terminology", "by", "storing", "all", "certificates", "in", "anchor_list", "list", "in", "PEM", "format", "under", "provided", "folder", "and", "then", "creating", "the", "associated", "links", "using", "the", "hash", "as", "usually", "done", "by", "c_rehash", "." ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/crypto/cert.py#L382-L427
4,446
phaethon/kamene
kamene/crypto/cert.py
_DecryptAndSignMethods._rsadp
def _rsadp(self, c): """ Internal method providing raw RSA decryption, i.e. simple modular exponentiation of the given ciphertext representative 'c', a long between 0 and n-1. This is the decryption primitive RSADP described in PKCS#1 v2.1, i.e. RFC 3447 Sect. 5.1.2. Input: c: ciphertest representative, a long between 0 and n-1, where n is the key modulus. Output: ciphertext representative, a long between 0 and n-1 Not intended to be used directly. Please, see encrypt() method. """ n = self.modulus if type(c) is int: c = long(c) if type(c) is not long or c > n-1: warning("Key._rsaep() expects a long between 0 and n-1") return None return self.key.decrypt(c)
python
def _rsadp(self, c): """ Internal method providing raw RSA decryption, i.e. simple modular exponentiation of the given ciphertext representative 'c', a long between 0 and n-1. This is the decryption primitive RSADP described in PKCS#1 v2.1, i.e. RFC 3447 Sect. 5.1.2. Input: c: ciphertest representative, a long between 0 and n-1, where n is the key modulus. Output: ciphertext representative, a long between 0 and n-1 Not intended to be used directly. Please, see encrypt() method. """ n = self.modulus if type(c) is int: c = long(c) if type(c) is not long or c > n-1: warning("Key._rsaep() expects a long between 0 and n-1") return None return self.key.decrypt(c)
[ "def", "_rsadp", "(", "self", ",", "c", ")", ":", "n", "=", "self", ".", "modulus", "if", "type", "(", "c", ")", "is", "int", ":", "c", "=", "long", "(", "c", ")", "if", "type", "(", "c", ")", "is", "not", "long", "or", "c", ">", "n", "-", "1", ":", "warning", "(", "\"Key._rsaep() expects a long between 0 and n-1\"", ")", "return", "None", "return", "self", ".", "key", ".", "decrypt", "(", "c", ")" ]
Internal method providing raw RSA decryption, i.e. simple modular exponentiation of the given ciphertext representative 'c', a long between 0 and n-1. This is the decryption primitive RSADP described in PKCS#1 v2.1, i.e. RFC 3447 Sect. 5.1.2. Input: c: ciphertest representative, a long between 0 and n-1, where n is the key modulus. Output: ciphertext representative, a long between 0 and n-1 Not intended to be used directly. Please, see encrypt() method.
[ "Internal", "method", "providing", "raw", "RSA", "decryption", "i", ".", "e", ".", "simple", "modular", "exponentiation", "of", "the", "given", "ciphertext", "representative", "c", "a", "long", "between", "0", "and", "n", "-", "1", "." ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/crypto/cert.py#L576-L602
4,447
phaethon/kamene
kamene/layers/inet.py
fragment
def fragment(pkt, fragsize=1480): """Fragment a big IP datagram""" fragsize = (fragsize + 7) // 8 * 8 lst = [] for p in pkt: s = bytes(p[IP].payload) nb = (len(s) + fragsize - 1) // fragsize for i in range(nb): q = p.copy() del q[IP].payload del q[IP].chksum del q[IP].len if i == nb - 1: q[IP].flags &= ~1 else: q[IP].flags |= 1 q[IP].frag = i * fragsize // 8 r = conf.raw_layer(load=s[i * fragsize:(i + 1) * fragsize]) r.overload_fields = p[IP].payload.overload_fields.copy() q.add_payload(r) lst.append(q) return lst
python
def fragment(pkt, fragsize=1480): """Fragment a big IP datagram""" fragsize = (fragsize + 7) // 8 * 8 lst = [] for p in pkt: s = bytes(p[IP].payload) nb = (len(s) + fragsize - 1) // fragsize for i in range(nb): q = p.copy() del q[IP].payload del q[IP].chksum del q[IP].len if i == nb - 1: q[IP].flags &= ~1 else: q[IP].flags |= 1 q[IP].frag = i * fragsize // 8 r = conf.raw_layer(load=s[i * fragsize:(i + 1) * fragsize]) r.overload_fields = p[IP].payload.overload_fields.copy() q.add_payload(r) lst.append(q) return lst
[ "def", "fragment", "(", "pkt", ",", "fragsize", "=", "1480", ")", ":", "fragsize", "=", "(", "fragsize", "+", "7", ")", "//", "8", "*", "8", "lst", "=", "[", "]", "for", "p", "in", "pkt", ":", "s", "=", "bytes", "(", "p", "[", "IP", "]", ".", "payload", ")", "nb", "=", "(", "len", "(", "s", ")", "+", "fragsize", "-", "1", ")", "//", "fragsize", "for", "i", "in", "range", "(", "nb", ")", ":", "q", "=", "p", ".", "copy", "(", ")", "del", "q", "[", "IP", "]", ".", "payload", "del", "q", "[", "IP", "]", ".", "chksum", "del", "q", "[", "IP", "]", ".", "len", "if", "i", "==", "nb", "-", "1", ":", "q", "[", "IP", "]", ".", "flags", "&=", "~", "1", "else", ":", "q", "[", "IP", "]", ".", "flags", "|=", "1", "q", "[", "IP", "]", ".", "frag", "=", "i", "*", "fragsize", "//", "8", "r", "=", "conf", ".", "raw_layer", "(", "load", "=", "s", "[", "i", "*", "fragsize", ":", "(", "i", "+", "1", ")", "*", "fragsize", "]", ")", "r", ".", "overload_fields", "=", "p", "[", "IP", "]", ".", "payload", ".", "overload_fields", ".", "copy", "(", ")", "q", ".", "add_payload", "(", "r", ")", "lst", ".", "append", "(", "q", ")", "return", "lst" ]
Fragment a big IP datagram
[ "Fragment", "a", "big", "IP", "datagram" ]
11d4064844f4f68ac5d7546f5633ac7d02082914
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/layers/inet.py#L864-L885
4,448
twitterdev/search-tweets-python
setup.py
parse_version
def parse_version(str_): """ Parses the program's version from a python variable declaration. """ v = re.findall(r"\d+.\d+.\d+", str_) if v: return v[0] else: print("cannot parse string {}".format(str_)) raise KeyError
python
def parse_version(str_): """ Parses the program's version from a python variable declaration. """ v = re.findall(r"\d+.\d+.\d+", str_) if v: return v[0] else: print("cannot parse string {}".format(str_)) raise KeyError
[ "def", "parse_version", "(", "str_", ")", ":", "v", "=", "re", ".", "findall", "(", "r\"\\d+.\\d+.\\d+\"", ",", "str_", ")", "if", "v", ":", "return", "v", "[", "0", "]", "else", ":", "print", "(", "\"cannot parse string {}\"", ".", "format", "(", "str_", ")", ")", "raise", "KeyError" ]
Parses the program's version from a python variable declaration.
[ "Parses", "the", "program", "s", "version", "from", "a", "python", "variable", "declaration", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/setup.py#L8-L17
4,449
twitterdev/search-tweets-python
searchtweets/result_stream.py
make_session
def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None): """Creates a Requests Session for use. Accepts a bearer token for premiums users and will override username and password information if present. Args: username (str): username for the session password (str): password for the user bearer_token (str): token for a premium API user. """ if password is None and bearer_token is None: logger.error("No authentication information provided; " "please check your object") raise KeyError session = requests.Session() session.trust_env = False headers = {'Accept-encoding': 'gzip', 'User-Agent': 'twitterdev-search-tweets-python/' + VERSION} if bearer_token: logger.info("using bearer token for authentication") headers['Authorization'] = "Bearer {}".format(bearer_token) session.headers = headers else: logger.info("using username and password for authentication") session.auth = username, password session.headers = headers if extra_headers_dict: headers.update(extra_headers_dict) return session
python
def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None): """Creates a Requests Session for use. Accepts a bearer token for premiums users and will override username and password information if present. Args: username (str): username for the session password (str): password for the user bearer_token (str): token for a premium API user. """ if password is None and bearer_token is None: logger.error("No authentication information provided; " "please check your object") raise KeyError session = requests.Session() session.trust_env = False headers = {'Accept-encoding': 'gzip', 'User-Agent': 'twitterdev-search-tweets-python/' + VERSION} if bearer_token: logger.info("using bearer token for authentication") headers['Authorization'] = "Bearer {}".format(bearer_token) session.headers = headers else: logger.info("using username and password for authentication") session.auth = username, password session.headers = headers if extra_headers_dict: headers.update(extra_headers_dict) return session
[ "def", "make_session", "(", "username", "=", "None", ",", "password", "=", "None", ",", "bearer_token", "=", "None", ",", "extra_headers_dict", "=", "None", ")", ":", "if", "password", "is", "None", "and", "bearer_token", "is", "None", ":", "logger", ".", "error", "(", "\"No authentication information provided; \"", "\"please check your object\"", ")", "raise", "KeyError", "session", "=", "requests", ".", "Session", "(", ")", "session", ".", "trust_env", "=", "False", "headers", "=", "{", "'Accept-encoding'", ":", "'gzip'", ",", "'User-Agent'", ":", "'twitterdev-search-tweets-python/'", "+", "VERSION", "}", "if", "bearer_token", ":", "logger", ".", "info", "(", "\"using bearer token for authentication\"", ")", "headers", "[", "'Authorization'", "]", "=", "\"Bearer {}\"", ".", "format", "(", "bearer_token", ")", "session", ".", "headers", "=", "headers", "else", ":", "logger", ".", "info", "(", "\"using username and password for authentication\"", ")", "session", ".", "auth", "=", "username", ",", "password", "session", ".", "headers", "=", "headers", "if", "extra_headers_dict", ":", "headers", ".", "update", "(", "extra_headers_dict", ")", "return", "session" ]
Creates a Requests Session for use. Accepts a bearer token for premiums users and will override username and password information if present. Args: username (str): username for the session password (str): password for the user bearer_token (str): token for a premium API user.
[ "Creates", "a", "Requests", "Session", "for", "use", ".", "Accepts", "a", "bearer", "token", "for", "premiums", "users", "and", "will", "override", "username", "and", "password", "information", "if", "present", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L31-L61
4,450
twitterdev/search-tweets-python
searchtweets/result_stream.py
retry
def retry(func): """ Decorator to handle API retries and exceptions. Defaults to three retries. Args: func (function): function for decoration Returns: decorated function """ def retried_func(*args, **kwargs): max_tries = 3 tries = 0 while True: try: resp = func(*args, **kwargs) except requests.exceptions.ConnectionError as exc: exc.msg = "Connection error for session; exiting" raise exc except requests.exceptions.HTTPError as exc: exc.msg = "HTTP error for session; exiting" raise exc if resp.status_code != 200 and tries < max_tries: logger.warning("retrying request; current status code: {}" .format(resp.status_code)) tries += 1 # mini exponential backoff here. time.sleep(tries ** 2) continue break if resp.status_code != 200: error_message = resp.json()["error"]["message"] logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message)) logger.error("Rule payload: {}".format(kwargs["rule_payload"])) raise requests.exceptions.HTTPError return resp return retried_func
python
def retry(func): """ Decorator to handle API retries and exceptions. Defaults to three retries. Args: func (function): function for decoration Returns: decorated function """ def retried_func(*args, **kwargs): max_tries = 3 tries = 0 while True: try: resp = func(*args, **kwargs) except requests.exceptions.ConnectionError as exc: exc.msg = "Connection error for session; exiting" raise exc except requests.exceptions.HTTPError as exc: exc.msg = "HTTP error for session; exiting" raise exc if resp.status_code != 200 and tries < max_tries: logger.warning("retrying request; current status code: {}" .format(resp.status_code)) tries += 1 # mini exponential backoff here. time.sleep(tries ** 2) continue break if resp.status_code != 200: error_message = resp.json()["error"]["message"] logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message)) logger.error("Rule payload: {}".format(kwargs["rule_payload"])) raise requests.exceptions.HTTPError return resp return retried_func
[ "def", "retry", "(", "func", ")", ":", "def", "retried_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "max_tries", "=", "3", "tries", "=", "0", "while", "True", ":", "try", ":", "resp", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "exc", ":", "exc", ".", "msg", "=", "\"Connection error for session; exiting\"", "raise", "exc", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "exc", ":", "exc", ".", "msg", "=", "\"HTTP error for session; exiting\"", "raise", "exc", "if", "resp", ".", "status_code", "!=", "200", "and", "tries", "<", "max_tries", ":", "logger", ".", "warning", "(", "\"retrying request; current status code: {}\"", ".", "format", "(", "resp", ".", "status_code", ")", ")", "tries", "+=", "1", "# mini exponential backoff here.", "time", ".", "sleep", "(", "tries", "**", "2", ")", "continue", "break", "if", "resp", ".", "status_code", "!=", "200", ":", "error_message", "=", "resp", ".", "json", "(", ")", "[", "\"error\"", "]", "[", "\"message\"", "]", "logger", ".", "error", "(", "\"HTTP Error code: {}: {}\"", ".", "format", "(", "resp", ".", "status_code", ",", "error_message", ")", ")", "logger", ".", "error", "(", "\"Rule payload: {}\"", ".", "format", "(", "kwargs", "[", "\"rule_payload\"", "]", ")", ")", "raise", "requests", ".", "exceptions", ".", "HTTPError", "return", "resp", "return", "retried_func" ]
Decorator to handle API retries and exceptions. Defaults to three retries. Args: func (function): function for decoration Returns: decorated function
[ "Decorator", "to", "handle", "API", "retries", "and", "exceptions", ".", "Defaults", "to", "three", "retries", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L64-L108
4,451
twitterdev/search-tweets-python
searchtweets/result_stream.py
request
def request(session, url, rule_payload, **kwargs): """ Executes a request with the given payload and arguments. Args: session (requests.Session): the valid session object url (str): Valid API endpoint rule_payload (str or dict): rule package for the POST. If you pass a dictionary, it will be converted into JSON. """ if isinstance(rule_payload, dict): rule_payload = json.dumps(rule_payload) logger.debug("sending request") result = session.post(url, data=rule_payload, **kwargs) return result
python
def request(session, url, rule_payload, **kwargs): """ Executes a request with the given payload and arguments. Args: session (requests.Session): the valid session object url (str): Valid API endpoint rule_payload (str or dict): rule package for the POST. If you pass a dictionary, it will be converted into JSON. """ if isinstance(rule_payload, dict): rule_payload = json.dumps(rule_payload) logger.debug("sending request") result = session.post(url, data=rule_payload, **kwargs) return result
[ "def", "request", "(", "session", ",", "url", ",", "rule_payload", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "rule_payload", ",", "dict", ")", ":", "rule_payload", "=", "json", ".", "dumps", "(", "rule_payload", ")", "logger", ".", "debug", "(", "\"sending request\"", ")", "result", "=", "session", ".", "post", "(", "url", ",", "data", "=", "rule_payload", ",", "*", "*", "kwargs", ")", "return", "result" ]
Executes a request with the given payload and arguments. Args: session (requests.Session): the valid session object url (str): Valid API endpoint rule_payload (str or dict): rule package for the POST. If you pass a dictionary, it will be converted into JSON.
[ "Executes", "a", "request", "with", "the", "given", "payload", "and", "arguments", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L112-L126
4,452
twitterdev/search-tweets-python
searchtweets/result_stream.py
collect_results
def collect_results(rule, max_results=500, result_stream_args=None): """ Utility function to quickly get a list of tweets from a ``ResultStream`` without keeping the object around. Requires your args to be configured prior to using. Args: rule (str): valid powertrack rule for your account, preferably generated by the `gen_rule_payload` function. max_results (int): maximum number of tweets or counts to return from the API / underlying ``ResultStream`` object. result_stream_args (dict): configuration dict that has connection information for a ``ResultStream`` object. Returns: list of results Example: >>> from searchtweets import collect_results >>> tweets = collect_results(rule, max_results=500, result_stream_args=search_args) """ if result_stream_args is None: logger.error("This function requires a configuration dict for the " "inner ResultStream object.") raise KeyError rs = ResultStream(rule_payload=rule, max_results=max_results, **result_stream_args) return list(rs.stream())
python
def collect_results(rule, max_results=500, result_stream_args=None): """ Utility function to quickly get a list of tweets from a ``ResultStream`` without keeping the object around. Requires your args to be configured prior to using. Args: rule (str): valid powertrack rule for your account, preferably generated by the `gen_rule_payload` function. max_results (int): maximum number of tweets or counts to return from the API / underlying ``ResultStream`` object. result_stream_args (dict): configuration dict that has connection information for a ``ResultStream`` object. Returns: list of results Example: >>> from searchtweets import collect_results >>> tweets = collect_results(rule, max_results=500, result_stream_args=search_args) """ if result_stream_args is None: logger.error("This function requires a configuration dict for the " "inner ResultStream object.") raise KeyError rs = ResultStream(rule_payload=rule, max_results=max_results, **result_stream_args) return list(rs.stream())
[ "def", "collect_results", "(", "rule", ",", "max_results", "=", "500", ",", "result_stream_args", "=", "None", ")", ":", "if", "result_stream_args", "is", "None", ":", "logger", ".", "error", "(", "\"This function requires a configuration dict for the \"", "\"inner ResultStream object.\"", ")", "raise", "KeyError", "rs", "=", "ResultStream", "(", "rule_payload", "=", "rule", ",", "max_results", "=", "max_results", ",", "*", "*", "result_stream_args", ")", "return", "list", "(", "rs", ".", "stream", "(", ")", ")" ]
Utility function to quickly get a list of tweets from a ``ResultStream`` without keeping the object around. Requires your args to be configured prior to using. Args: rule (str): valid powertrack rule for your account, preferably generated by the `gen_rule_payload` function. max_results (int): maximum number of tweets or counts to return from the API / underlying ``ResultStream`` object. result_stream_args (dict): configuration dict that has connection information for a ``ResultStream`` object. Returns: list of results Example: >>> from searchtweets import collect_results >>> tweets = collect_results(rule, max_results=500, result_stream_args=search_args)
[ "Utility", "function", "to", "quickly", "get", "a", "list", "of", "tweets", "from", "a", "ResultStream", "without", "keeping", "the", "object", "around", ".", "Requires", "your", "args", "to", "be", "configured", "prior", "to", "using", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L276-L308
4,453
twitterdev/search-tweets-python
searchtweets/result_stream.py
ResultStream.stream
def stream(self): """ Main entry point for the data from the API. Will automatically paginate through the results via the ``next`` token and return up to ``max_results`` tweets or up to ``max_requests`` API calls, whichever is lower. Usage: >>> result_stream = ResultStream(**kwargs) >>> stream = result_stream.stream() >>> results = list(stream) >>> # or for faster usage... >>> results = list(ResultStream(**kwargs).stream()) """ self.init_session() self.check_counts() self.execute_request() self.stream_started = True while True: for tweet in self.current_tweets: if self.total_results >= self.max_results: break yield self._tweet_func(tweet) self.total_results += 1 if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests: self.rule_payload = merge_dicts(self.rule_payload, {"next": self.next_token}) logger.info("paging; total requests read so far: {}" .format(self.n_requests)) self.execute_request() else: break logger.info("ending stream at {} tweets".format(self.total_results)) self.current_tweets = None self.session.close()
python
def stream(self): """ Main entry point for the data from the API. Will automatically paginate through the results via the ``next`` token and return up to ``max_results`` tweets or up to ``max_requests`` API calls, whichever is lower. Usage: >>> result_stream = ResultStream(**kwargs) >>> stream = result_stream.stream() >>> results = list(stream) >>> # or for faster usage... >>> results = list(ResultStream(**kwargs).stream()) """ self.init_session() self.check_counts() self.execute_request() self.stream_started = True while True: for tweet in self.current_tweets: if self.total_results >= self.max_results: break yield self._tweet_func(tweet) self.total_results += 1 if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests: self.rule_payload = merge_dicts(self.rule_payload, {"next": self.next_token}) logger.info("paging; total requests read so far: {}" .format(self.n_requests)) self.execute_request() else: break logger.info("ending stream at {} tweets".format(self.total_results)) self.current_tweets = None self.session.close()
[ "def", "stream", "(", "self", ")", ":", "self", ".", "init_session", "(", ")", "self", ".", "check_counts", "(", ")", "self", ".", "execute_request", "(", ")", "self", ".", "stream_started", "=", "True", "while", "True", ":", "for", "tweet", "in", "self", ".", "current_tweets", ":", "if", "self", ".", "total_results", ">=", "self", ".", "max_results", ":", "break", "yield", "self", ".", "_tweet_func", "(", "tweet", ")", "self", ".", "total_results", "+=", "1", "if", "self", ".", "next_token", "and", "self", ".", "total_results", "<", "self", ".", "max_results", "and", "self", ".", "n_requests", "<=", "self", ".", "max_requests", ":", "self", ".", "rule_payload", "=", "merge_dicts", "(", "self", ".", "rule_payload", ",", "{", "\"next\"", ":", "self", ".", "next_token", "}", ")", "logger", ".", "info", "(", "\"paging; total requests read so far: {}\"", ".", "format", "(", "self", ".", "n_requests", ")", ")", "self", ".", "execute_request", "(", ")", "else", ":", "break", "logger", ".", "info", "(", "\"ending stream at {} tweets\"", ".", "format", "(", "self", ".", "total_results", ")", ")", "self", ".", "current_tweets", "=", "None", "self", ".", "session", ".", "close", "(", ")" ]
Main entry point for the data from the API. Will automatically paginate through the results via the ``next`` token and return up to ``max_results`` tweets or up to ``max_requests`` API calls, whichever is lower. Usage: >>> result_stream = ResultStream(**kwargs) >>> stream = result_stream.stream() >>> results = list(stream) >>> # or for faster usage... >>> results = list(ResultStream(**kwargs).stream())
[ "Main", "entry", "point", "for", "the", "data", "from", "the", "API", ".", "Will", "automatically", "paginate", "through", "the", "results", "via", "the", "next", "token", "and", "return", "up", "to", "max_results", "tweets", "or", "up", "to", "max_requests", "API", "calls", "whichever", "is", "lower", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L193-L227
4,454
twitterdev/search-tweets-python
searchtweets/result_stream.py
ResultStream.init_session
def init_session(self): """ Defines a session object for passing requests. """ if self.session: self.session.close() self.session = make_session(self.username, self.password, self.bearer_token, self.extra_headers_dict)
python
def init_session(self): """ Defines a session object for passing requests. """ if self.session: self.session.close() self.session = make_session(self.username, self.password, self.bearer_token, self.extra_headers_dict)
[ "def", "init_session", "(", "self", ")", ":", "if", "self", ".", "session", ":", "self", ".", "session", ".", "close", "(", ")", "self", ".", "session", "=", "make_session", "(", "self", ".", "username", ",", "self", ".", "password", ",", "self", ".", "bearer_token", ",", "self", ".", "extra_headers_dict", ")" ]
Defines a session object for passing requests.
[ "Defines", "a", "session", "object", "for", "passing", "requests", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L229-L238
4,455
twitterdev/search-tweets-python
searchtweets/result_stream.py
ResultStream.check_counts
def check_counts(self): """ Disables tweet parsing if the count API is used. """ if "counts" in re.split("[/.]", self.endpoint): logger.info("disabling tweet parsing due to counts API usage") self._tweet_func = lambda x: x
python
def check_counts(self): """ Disables tweet parsing if the count API is used. """ if "counts" in re.split("[/.]", self.endpoint): logger.info("disabling tweet parsing due to counts API usage") self._tweet_func = lambda x: x
[ "def", "check_counts", "(", "self", ")", ":", "if", "\"counts\"", "in", "re", ".", "split", "(", "\"[/.]\"", ",", "self", ".", "endpoint", ")", ":", "logger", ".", "info", "(", "\"disabling tweet parsing due to counts API usage\"", ")", "self", ".", "_tweet_func", "=", "lambda", "x", ":", "x" ]
Disables tweet parsing if the count API is used.
[ "Disables", "tweet", "parsing", "if", "the", "count", "API", "is", "used", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L240-L246
4,456
twitterdev/search-tweets-python
searchtweets/result_stream.py
ResultStream.execute_request
def execute_request(self): """ Sends the request to the API and parses the json response. Makes some assumptions about the session length and sets the presence of a "next" token. """ if self.n_requests % 20 == 0 and self.n_requests > 1: logger.info("refreshing session") self.init_session() resp = request(session=self.session, url=self.endpoint, rule_payload=self.rule_payload) self.n_requests += 1 ResultStream.session_request_counter += 1 resp = json.loads(resp.content.decode(resp.encoding)) self.next_token = resp.get("next", None) self.current_tweets = resp["results"]
python
def execute_request(self): """ Sends the request to the API and parses the json response. Makes some assumptions about the session length and sets the presence of a "next" token. """ if self.n_requests % 20 == 0 and self.n_requests > 1: logger.info("refreshing session") self.init_session() resp = request(session=self.session, url=self.endpoint, rule_payload=self.rule_payload) self.n_requests += 1 ResultStream.session_request_counter += 1 resp = json.loads(resp.content.decode(resp.encoding)) self.next_token = resp.get("next", None) self.current_tweets = resp["results"]
[ "def", "execute_request", "(", "self", ")", ":", "if", "self", ".", "n_requests", "%", "20", "==", "0", "and", "self", ".", "n_requests", ">", "1", ":", "logger", ".", "info", "(", "\"refreshing session\"", ")", "self", ".", "init_session", "(", ")", "resp", "=", "request", "(", "session", "=", "self", ".", "session", ",", "url", "=", "self", ".", "endpoint", ",", "rule_payload", "=", "self", ".", "rule_payload", ")", "self", ".", "n_requests", "+=", "1", "ResultStream", ".", "session_request_counter", "+=", "1", "resp", "=", "json", ".", "loads", "(", "resp", ".", "content", ".", "decode", "(", "resp", ".", "encoding", ")", ")", "self", ".", "next_token", "=", "resp", ".", "get", "(", "\"next\"", ",", "None", ")", "self", ".", "current_tweets", "=", "resp", "[", "\"results\"", "]" ]
Sends the request to the API and parses the json response. Makes some assumptions about the session length and sets the presence of a "next" token.
[ "Sends", "the", "request", "to", "the", "API", "and", "parses", "the", "json", "response", ".", "Makes", "some", "assumptions", "about", "the", "session", "length", "and", "sets", "the", "presence", "of", "a", "next", "token", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L248-L265
4,457
twitterdev/search-tweets-python
searchtweets/api_utils.py
gen_rule_payload
def gen_rule_payload(pt_rule, results_per_call=None, from_date=None, to_date=None, count_bucket=None, tag=None, stringify=True): """ Generates the dict or json payload for a PowerTrack rule. Args: pt_rule (str): The string version of a powertrack rule, e.g., "beyonce has:geo". Accepts multi-line strings for ease of entry. results_per_call (int): number of tweets or counts returned per API call. This maps to the ``maxResults`` search API parameter. Defaults to 500 to reduce API call usage. from_date (str or None): Date format as specified by `convert_utc_time` for the starting time of your search. to_date (str or None): date format as specified by `convert_utc_time` for the end time of your search. count_bucket (str or None): If using the counts api endpoint, will define the count bucket for which tweets are aggregated. stringify (bool): specifies the return type, `dict` or json-formatted `str`. Example: >>> from searchtweets.utils import gen_rule_payload >>> gen_rule_payload("beyonce has:geo", ... from_date="2017-08-21", ... to_date="2017-08-22") '{"query":"beyonce has:geo","maxResults":100,"toDate":"201708220000","fromDate":"201708210000"}' """ pt_rule = ' '.join(pt_rule.split()) # allows multi-line strings payload = {"query": pt_rule} if results_per_call is not None and isinstance(results_per_call, int) is True: payload["maxResults"] = results_per_call if to_date: payload["toDate"] = convert_utc_time(to_date) if from_date: payload["fromDate"] = convert_utc_time(from_date) if count_bucket: if set(["day", "hour", "minute"]) & set([count_bucket]): payload["bucket"] = count_bucket del payload["maxResults"] else: logger.error("invalid count bucket: provided {}" .format(count_bucket)) raise ValueError if tag: payload["tag"] = tag return json.dumps(payload) if stringify else payload
python
def gen_rule_payload(pt_rule, results_per_call=None, from_date=None, to_date=None, count_bucket=None, tag=None, stringify=True): """ Generates the dict or json payload for a PowerTrack rule. Args: pt_rule (str): The string version of a powertrack rule, e.g., "beyonce has:geo". Accepts multi-line strings for ease of entry. results_per_call (int): number of tweets or counts returned per API call. This maps to the ``maxResults`` search API parameter. Defaults to 500 to reduce API call usage. from_date (str or None): Date format as specified by `convert_utc_time` for the starting time of your search. to_date (str or None): date format as specified by `convert_utc_time` for the end time of your search. count_bucket (str or None): If using the counts api endpoint, will define the count bucket for which tweets are aggregated. stringify (bool): specifies the return type, `dict` or json-formatted `str`. Example: >>> from searchtweets.utils import gen_rule_payload >>> gen_rule_payload("beyonce has:geo", ... from_date="2017-08-21", ... to_date="2017-08-22") '{"query":"beyonce has:geo","maxResults":100,"toDate":"201708220000","fromDate":"201708210000"}' """ pt_rule = ' '.join(pt_rule.split()) # allows multi-line strings payload = {"query": pt_rule} if results_per_call is not None and isinstance(results_per_call, int) is True: payload["maxResults"] = results_per_call if to_date: payload["toDate"] = convert_utc_time(to_date) if from_date: payload["fromDate"] = convert_utc_time(from_date) if count_bucket: if set(["day", "hour", "minute"]) & set([count_bucket]): payload["bucket"] = count_bucket del payload["maxResults"] else: logger.error("invalid count bucket: provided {}" .format(count_bucket)) raise ValueError if tag: payload["tag"] = tag return json.dumps(payload) if stringify else payload
[ "def", "gen_rule_payload", "(", "pt_rule", ",", "results_per_call", "=", "None", ",", "from_date", "=", "None", ",", "to_date", "=", "None", ",", "count_bucket", "=", "None", ",", "tag", "=", "None", ",", "stringify", "=", "True", ")", ":", "pt_rule", "=", "' '", ".", "join", "(", "pt_rule", ".", "split", "(", ")", ")", "# allows multi-line strings", "payload", "=", "{", "\"query\"", ":", "pt_rule", "}", "if", "results_per_call", "is", "not", "None", "and", "isinstance", "(", "results_per_call", ",", "int", ")", "is", "True", ":", "payload", "[", "\"maxResults\"", "]", "=", "results_per_call", "if", "to_date", ":", "payload", "[", "\"toDate\"", "]", "=", "convert_utc_time", "(", "to_date", ")", "if", "from_date", ":", "payload", "[", "\"fromDate\"", "]", "=", "convert_utc_time", "(", "from_date", ")", "if", "count_bucket", ":", "if", "set", "(", "[", "\"day\"", ",", "\"hour\"", ",", "\"minute\"", "]", ")", "&", "set", "(", "[", "count_bucket", "]", ")", ":", "payload", "[", "\"bucket\"", "]", "=", "count_bucket", "del", "payload", "[", "\"maxResults\"", "]", "else", ":", "logger", ".", "error", "(", "\"invalid count bucket: provided {}\"", ".", "format", "(", "count_bucket", ")", ")", "raise", "ValueError", "if", "tag", ":", "payload", "[", "\"tag\"", "]", "=", "tag", "return", "json", ".", "dumps", "(", "payload", ")", "if", "stringify", "else", "payload" ]
Generates the dict or json payload for a PowerTrack rule. Args: pt_rule (str): The string version of a powertrack rule, e.g., "beyonce has:geo". Accepts multi-line strings for ease of entry. results_per_call (int): number of tweets or counts returned per API call. This maps to the ``maxResults`` search API parameter. Defaults to 500 to reduce API call usage. from_date (str or None): Date format as specified by `convert_utc_time` for the starting time of your search. to_date (str or None): date format as specified by `convert_utc_time` for the end time of your search. count_bucket (str or None): If using the counts api endpoint, will define the count bucket for which tweets are aggregated. stringify (bool): specifies the return type, `dict` or json-formatted `str`. Example: >>> from searchtweets.utils import gen_rule_payload >>> gen_rule_payload("beyonce has:geo", ... from_date="2017-08-21", ... to_date="2017-08-22") '{"query":"beyonce has:geo","maxResults":100,"toDate":"201708220000","fromDate":"201708210000"}'
[ "Generates", "the", "dict", "or", "json", "payload", "for", "a", "PowerTrack", "rule", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L86-L138
4,458
twitterdev/search-tweets-python
searchtweets/api_utils.py
gen_params_from_config
def gen_params_from_config(config_dict): """ Generates parameters for a ResultStream from a dictionary. """ if config_dict.get("count_bucket"): logger.warning("change your endpoint to the count endpoint; this is " "default behavior when the count bucket " "field is defined") endpoint = change_to_count_endpoint(config_dict.get("endpoint")) else: endpoint = config_dict.get("endpoint") def intify(arg): if not isinstance(arg, int) and arg is not None: return int(arg) else: return arg # this parameter comes in as a string when it's parsed results_per_call = intify(config_dict.get("results_per_call", None)) rule = gen_rule_payload(pt_rule=config_dict["pt_rule"], from_date=config_dict.get("from_date", None), to_date=config_dict.get("to_date", None), results_per_call=results_per_call, count_bucket=config_dict.get("count_bucket", None)) _dict = {"endpoint": endpoint, "username": config_dict.get("username"), "password": config_dict.get("password"), "bearer_token": config_dict.get("bearer_token"), "extra_headers_dict": config_dict.get("extra_headers_dict",None), "rule_payload": rule, "results_per_file": intify(config_dict.get("results_per_file")), "max_results": intify(config_dict.get("max_results")), "max_pages": intify(config_dict.get("max_pages", None))} return _dict
python
def gen_params_from_config(config_dict): """ Generates parameters for a ResultStream from a dictionary. """ if config_dict.get("count_bucket"): logger.warning("change your endpoint to the count endpoint; this is " "default behavior when the count bucket " "field is defined") endpoint = change_to_count_endpoint(config_dict.get("endpoint")) else: endpoint = config_dict.get("endpoint") def intify(arg): if not isinstance(arg, int) and arg is not None: return int(arg) else: return arg # this parameter comes in as a string when it's parsed results_per_call = intify(config_dict.get("results_per_call", None)) rule = gen_rule_payload(pt_rule=config_dict["pt_rule"], from_date=config_dict.get("from_date", None), to_date=config_dict.get("to_date", None), results_per_call=results_per_call, count_bucket=config_dict.get("count_bucket", None)) _dict = {"endpoint": endpoint, "username": config_dict.get("username"), "password": config_dict.get("password"), "bearer_token": config_dict.get("bearer_token"), "extra_headers_dict": config_dict.get("extra_headers_dict",None), "rule_payload": rule, "results_per_file": intify(config_dict.get("results_per_file")), "max_results": intify(config_dict.get("max_results")), "max_pages": intify(config_dict.get("max_pages", None))} return _dict
[ "def", "gen_params_from_config", "(", "config_dict", ")", ":", "if", "config_dict", ".", "get", "(", "\"count_bucket\"", ")", ":", "logger", ".", "warning", "(", "\"change your endpoint to the count endpoint; this is \"", "\"default behavior when the count bucket \"", "\"field is defined\"", ")", "endpoint", "=", "change_to_count_endpoint", "(", "config_dict", ".", "get", "(", "\"endpoint\"", ")", ")", "else", ":", "endpoint", "=", "config_dict", ".", "get", "(", "\"endpoint\"", ")", "def", "intify", "(", "arg", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "int", ")", "and", "arg", "is", "not", "None", ":", "return", "int", "(", "arg", ")", "else", ":", "return", "arg", "# this parameter comes in as a string when it's parsed", "results_per_call", "=", "intify", "(", "config_dict", ".", "get", "(", "\"results_per_call\"", ",", "None", ")", ")", "rule", "=", "gen_rule_payload", "(", "pt_rule", "=", "config_dict", "[", "\"pt_rule\"", "]", ",", "from_date", "=", "config_dict", ".", "get", "(", "\"from_date\"", ",", "None", ")", ",", "to_date", "=", "config_dict", ".", "get", "(", "\"to_date\"", ",", "None", ")", ",", "results_per_call", "=", "results_per_call", ",", "count_bucket", "=", "config_dict", ".", "get", "(", "\"count_bucket\"", ",", "None", ")", ")", "_dict", "=", "{", "\"endpoint\"", ":", "endpoint", ",", "\"username\"", ":", "config_dict", ".", "get", "(", "\"username\"", ")", ",", "\"password\"", ":", "config_dict", ".", "get", "(", "\"password\"", ")", ",", "\"bearer_token\"", ":", "config_dict", ".", "get", "(", "\"bearer_token\"", ")", ",", "\"extra_headers_dict\"", ":", "config_dict", ".", "get", "(", "\"extra_headers_dict\"", ",", "None", ")", ",", "\"rule_payload\"", ":", "rule", ",", "\"results_per_file\"", ":", "intify", "(", "config_dict", ".", "get", "(", "\"results_per_file\"", ")", ")", ",", "\"max_results\"", ":", "intify", "(", "config_dict", ".", "get", "(", "\"max_results\"", ")", ")", ",", "\"max_pages\"", ":", "intify", "(", "config_dict", ".", "get", "(", "\"max_pages\"", ",", "None", ")", ")", "}", "return", "_dict" ]
Generates parameters for a ResultStream from a dictionary.
[ "Generates", "parameters", "for", "a", "ResultStream", "from", "a", "dictionary", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L141-L179
4,459
twitterdev/search-tweets-python
searchtweets/api_utils.py
infer_endpoint
def infer_endpoint(rule_payload): """ Infer which endpoint should be used for a given rule payload. """ bucket = (rule_payload if isinstance(rule_payload, dict) else json.loads(rule_payload)).get("bucket") return "counts" if bucket else "search"
python
def infer_endpoint(rule_payload): """ Infer which endpoint should be used for a given rule payload. """ bucket = (rule_payload if isinstance(rule_payload, dict) else json.loads(rule_payload)).get("bucket") return "counts" if bucket else "search"
[ "def", "infer_endpoint", "(", "rule_payload", ")", ":", "bucket", "=", "(", "rule_payload", "if", "isinstance", "(", "rule_payload", ",", "dict", ")", "else", "json", ".", "loads", "(", "rule_payload", ")", ")", ".", "get", "(", "\"bucket\"", ")", "return", "\"counts\"", "if", "bucket", "else", "\"search\"" ]
Infer which endpoint should be used for a given rule payload.
[ "Infer", "which", "endpoint", "should", "be", "used", "for", "a", "given", "rule", "payload", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L182-L188
4,460
twitterdev/search-tweets-python
searchtweets/api_utils.py
validate_count_api
def validate_count_api(rule_payload, endpoint): """ Ensures that the counts api is set correctly in a payload. """ rule = (rule_payload if isinstance(rule_payload, dict) else json.loads(rule_payload)) bucket = rule.get('bucket') counts = set(endpoint.split("/")) & {"counts.json"} if len(counts) == 0: if bucket is not None: msg = ("""There is a count bucket present in your payload, but you are using not using the counts API. Please check your endpoints and try again""") logger.error(msg) raise ValueError
python
def validate_count_api(rule_payload, endpoint): """ Ensures that the counts api is set correctly in a payload. """ rule = (rule_payload if isinstance(rule_payload, dict) else json.loads(rule_payload)) bucket = rule.get('bucket') counts = set(endpoint.split("/")) & {"counts.json"} if len(counts) == 0: if bucket is not None: msg = ("""There is a count bucket present in your payload, but you are using not using the counts API. Please check your endpoints and try again""") logger.error(msg) raise ValueError
[ "def", "validate_count_api", "(", "rule_payload", ",", "endpoint", ")", ":", "rule", "=", "(", "rule_payload", "if", "isinstance", "(", "rule_payload", ",", "dict", ")", "else", "json", ".", "loads", "(", "rule_payload", ")", ")", "bucket", "=", "rule", ".", "get", "(", "'bucket'", ")", "counts", "=", "set", "(", "endpoint", ".", "split", "(", "\"/\"", ")", ")", "&", "{", "\"counts.json\"", "}", "if", "len", "(", "counts", ")", "==", "0", ":", "if", "bucket", "is", "not", "None", ":", "msg", "=", "(", "\"\"\"There is a count bucket present in your payload,\n but you are using not using the counts API.\n Please check your endpoints and try again\"\"\"", ")", "logger", ".", "error", "(", "msg", ")", "raise", "ValueError" ]
Ensures that the counts api is set correctly in a payload.
[ "Ensures", "that", "the", "counts", "api", "is", "set", "correctly", "in", "a", "payload", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L191-L205
4,461
twitterdev/search-tweets-python
searchtweets/utils.py
partition
def partition(iterable, chunk_size, pad_none=False): """adapted from Toolz. Breaks an iterable into n iterables up to the certain chunk size, padding with Nones if availble. Example: >>> from searchtweets.utils import partition >>> iter_ = range(10) >>> list(partition(iter_, 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] >>> list(partition(iter_, 3, pad_none=True)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)] """ args = [iter(iterable)] * chunk_size if not pad_none: return zip(*args) else: return it.zip_longest(*args)
python
def partition(iterable, chunk_size, pad_none=False): """adapted from Toolz. Breaks an iterable into n iterables up to the certain chunk size, padding with Nones if availble. Example: >>> from searchtweets.utils import partition >>> iter_ = range(10) >>> list(partition(iter_, 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] >>> list(partition(iter_, 3, pad_none=True)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)] """ args = [iter(iterable)] * chunk_size if not pad_none: return zip(*args) else: return it.zip_longest(*args)
[ "def", "partition", "(", "iterable", ",", "chunk_size", ",", "pad_none", "=", "False", ")", ":", "args", "=", "[", "iter", "(", "iterable", ")", "]", "*", "chunk_size", "if", "not", "pad_none", ":", "return", "zip", "(", "*", "args", ")", "else", ":", "return", "it", ".", "zip_longest", "(", "*", "args", ")" ]
adapted from Toolz. Breaks an iterable into n iterables up to the certain chunk size, padding with Nones if availble. Example: >>> from searchtweets.utils import partition >>> iter_ = range(10) >>> list(partition(iter_, 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] >>> list(partition(iter_, 3, pad_none=True)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
[ "adapted", "from", "Toolz", ".", "Breaks", "an", "iterable", "into", "n", "iterables", "up", "to", "the", "certain", "chunk", "size", "padding", "with", "Nones", "if", "availble", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/utils.py#L41-L57
4,462
twitterdev/search-tweets-python
searchtweets/utils.py
write_ndjson
def write_ndjson(filename, data_iterable, append=False, **kwargs): """ Generator that writes newline-delimited json to a file and returns items from an iterable. """ write_mode = "ab" if append else "wb" logger.info("writing to file {}".format(filename)) with codecs.open(filename, write_mode, "utf-8") as outfile: for item in data_iterable: outfile.write(json.dumps(item) + "\n") yield item
python
def write_ndjson(filename, data_iterable, append=False, **kwargs): """ Generator that writes newline-delimited json to a file and returns items from an iterable. """ write_mode = "ab" if append else "wb" logger.info("writing to file {}".format(filename)) with codecs.open(filename, write_mode, "utf-8") as outfile: for item in data_iterable: outfile.write(json.dumps(item) + "\n") yield item
[ "def", "write_ndjson", "(", "filename", ",", "data_iterable", ",", "append", "=", "False", ",", "*", "*", "kwargs", ")", ":", "write_mode", "=", "\"ab\"", "if", "append", "else", "\"wb\"", "logger", ".", "info", "(", "\"writing to file {}\"", ".", "format", "(", "filename", ")", ")", "with", "codecs", ".", "open", "(", "filename", ",", "write_mode", ",", "\"utf-8\"", ")", "as", "outfile", ":", "for", "item", "in", "data_iterable", ":", "outfile", ".", "write", "(", "json", ".", "dumps", "(", "item", ")", "+", "\"\\n\"", ")", "yield", "item" ]
Generator that writes newline-delimited json to a file and returns items from an iterable.
[ "Generator", "that", "writes", "newline", "-", "delimited", "json", "to", "a", "file", "and", "returns", "items", "from", "an", "iterable", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/utils.py#L87-L97
4,463
twitterdev/search-tweets-python
searchtweets/utils.py
write_result_stream
def write_result_stream(result_stream, filename_prefix=None, results_per_file=None, **kwargs): """ Wraps a ``ResultStream`` object to save it to a file. This function will still return all data from the result stream as a generator that wraps the ``write_ndjson`` method. Args: result_stream (ResultStream): the unstarted ResultStream object filename_prefix (str or None): the base name for file writing results_per_file (int or None): the maximum number of tweets to write per file. Defaults to having no max, which means one file. Multiple files will be named by datetime, according to ``<prefix>_YYY-mm-ddTHH_MM_SS.json``. """ if isinstance(result_stream, types.GeneratorType): stream = result_stream else: stream = result_stream.stream() file_time_formatter = "%Y-%m-%dT%H_%M_%S" if filename_prefix is None: filename_prefix = "twitter_search_results" if results_per_file: logger.info("chunking result stream to files with {} tweets per file" .format(results_per_file)) chunked_stream = partition(stream, results_per_file, pad_none=True) for chunk in chunked_stream: chunk = filter(lambda x: x is not None, chunk) curr_datetime = (datetime.datetime.utcnow() .strftime(file_time_formatter)) _filename = "{}_{}.json".format(filename_prefix, curr_datetime) yield from write_ndjson(_filename, chunk) else: curr_datetime = (datetime.datetime.utcnow() .strftime(file_time_formatter)) _filename = "{}.json".format(filename_prefix) yield from write_ndjson(_filename, stream)
python
def write_result_stream(result_stream, filename_prefix=None, results_per_file=None, **kwargs): """ Wraps a ``ResultStream`` object to save it to a file. This function will still return all data from the result stream as a generator that wraps the ``write_ndjson`` method. Args: result_stream (ResultStream): the unstarted ResultStream object filename_prefix (str or None): the base name for file writing results_per_file (int or None): the maximum number of tweets to write per file. Defaults to having no max, which means one file. Multiple files will be named by datetime, according to ``<prefix>_YYY-mm-ddTHH_MM_SS.json``. """ if isinstance(result_stream, types.GeneratorType): stream = result_stream else: stream = result_stream.stream() file_time_formatter = "%Y-%m-%dT%H_%M_%S" if filename_prefix is None: filename_prefix = "twitter_search_results" if results_per_file: logger.info("chunking result stream to files with {} tweets per file" .format(results_per_file)) chunked_stream = partition(stream, results_per_file, pad_none=True) for chunk in chunked_stream: chunk = filter(lambda x: x is not None, chunk) curr_datetime = (datetime.datetime.utcnow() .strftime(file_time_formatter)) _filename = "{}_{}.json".format(filename_prefix, curr_datetime) yield from write_ndjson(_filename, chunk) else: curr_datetime = (datetime.datetime.utcnow() .strftime(file_time_formatter)) _filename = "{}.json".format(filename_prefix) yield from write_ndjson(_filename, stream)
[ "def", "write_result_stream", "(", "result_stream", ",", "filename_prefix", "=", "None", ",", "results_per_file", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "result_stream", ",", "types", ".", "GeneratorType", ")", ":", "stream", "=", "result_stream", "else", ":", "stream", "=", "result_stream", ".", "stream", "(", ")", "file_time_formatter", "=", "\"%Y-%m-%dT%H_%M_%S\"", "if", "filename_prefix", "is", "None", ":", "filename_prefix", "=", "\"twitter_search_results\"", "if", "results_per_file", ":", "logger", ".", "info", "(", "\"chunking result stream to files with {} tweets per file\"", ".", "format", "(", "results_per_file", ")", ")", "chunked_stream", "=", "partition", "(", "stream", ",", "results_per_file", ",", "pad_none", "=", "True", ")", "for", "chunk", "in", "chunked_stream", ":", "chunk", "=", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "chunk", ")", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}_{}.json\"", ".", "format", "(", "filename_prefix", ",", "curr_datetime", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "chunk", ")", "else", ":", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}.json\"", ".", "format", "(", "filename_prefix", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "stream", ")" ]
Wraps a ``ResultStream`` object to save it to a file. This function will still return all data from the result stream as a generator that wraps the ``write_ndjson`` method. Args: result_stream (ResultStream): the unstarted ResultStream object filename_prefix (str or None): the base name for file writing results_per_file (int or None): the maximum number of tweets to write per file. Defaults to having no max, which means one file. Multiple files will be named by datetime, according to ``<prefix>_YYY-mm-ddTHH_MM_SS.json``.
[ "Wraps", "a", "ResultStream", "object", "to", "save", "it", "to", "a", "file", ".", "This", "function", "will", "still", "return", "all", "data", "from", "the", "result", "stream", "as", "a", "generator", "that", "wraps", "the", "write_ndjson", "method", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/utils.py#L100-L140
4,464
twitterdev/search-tweets-python
searchtweets/credentials.py
_load_yaml_credentials
def _load_yaml_credentials(filename=None, yaml_key=None): """Loads and parses credentials in a YAML file. Catches common exceptions and returns an empty dict on error, which will be handled downstream. Returns: dict: parsed credentials or {} """ try: with open(os.path.expanduser(filename)) as f: search_creds = yaml.safe_load(f)[yaml_key] except FileNotFoundError: logger.error("cannot read file {}".format(filename)) search_creds = {} except KeyError: logger.error("{} is missing the provided key: {}" .format(filename, yaml_key)) search_creds = {} return search_creds
python
def _load_yaml_credentials(filename=None, yaml_key=None): """Loads and parses credentials in a YAML file. Catches common exceptions and returns an empty dict on error, which will be handled downstream. Returns: dict: parsed credentials or {} """ try: with open(os.path.expanduser(filename)) as f: search_creds = yaml.safe_load(f)[yaml_key] except FileNotFoundError: logger.error("cannot read file {}".format(filename)) search_creds = {} except KeyError: logger.error("{} is missing the provided key: {}" .format(filename, yaml_key)) search_creds = {} return search_creds
[ "def", "_load_yaml_credentials", "(", "filename", "=", "None", ",", "yaml_key", "=", "None", ")", ":", "try", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "filename", ")", ")", "as", "f", ":", "search_creds", "=", "yaml", ".", "safe_load", "(", "f", ")", "[", "yaml_key", "]", "except", "FileNotFoundError", ":", "logger", ".", "error", "(", "\"cannot read file {}\"", ".", "format", "(", "filename", ")", ")", "search_creds", "=", "{", "}", "except", "KeyError", ":", "logger", ".", "error", "(", "\"{} is missing the provided key: {}\"", ".", "format", "(", "filename", ",", "yaml_key", ")", ")", "search_creds", "=", "{", "}", "return", "search_creds" ]
Loads and parses credentials in a YAML file. Catches common exceptions and returns an empty dict on error, which will be handled downstream. Returns: dict: parsed credentials or {}
[ "Loads", "and", "parses", "credentials", "in", "a", "YAML", "file", ".", "Catches", "common", "exceptions", "and", "returns", "an", "empty", "dict", "on", "error", "which", "will", "be", "handled", "downstream", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/credentials.py#L25-L43
4,465
twitterdev/search-tweets-python
searchtweets/credentials.py
_generate_bearer_token
def _generate_bearer_token(consumer_key, consumer_secret): """ Return the bearer token for a given pair of consumer key and secret values. """ data = [('grant_type', 'client_credentials')] resp = requests.post(OAUTH_ENDPOINT, data=data, auth=(consumer_key, consumer_secret)) logger.warning("Grabbing bearer token from OAUTH") if resp.status_code >= 400: logger.error(resp.text) resp.raise_for_status() return resp.json()['access_token']
python
def _generate_bearer_token(consumer_key, consumer_secret): """ Return the bearer token for a given pair of consumer key and secret values. """ data = [('grant_type', 'client_credentials')] resp = requests.post(OAUTH_ENDPOINT, data=data, auth=(consumer_key, consumer_secret)) logger.warning("Grabbing bearer token from OAUTH") if resp.status_code >= 400: logger.error(resp.text) resp.raise_for_status() return resp.json()['access_token']
[ "def", "_generate_bearer_token", "(", "consumer_key", ",", "consumer_secret", ")", ":", "data", "=", "[", "(", "'grant_type'", ",", "'client_credentials'", ")", "]", "resp", "=", "requests", ".", "post", "(", "OAUTH_ENDPOINT", ",", "data", "=", "data", ",", "auth", "=", "(", "consumer_key", ",", "consumer_secret", ")", ")", "logger", ".", "warning", "(", "\"Grabbing bearer token from OAUTH\"", ")", "if", "resp", ".", "status_code", ">=", "400", ":", "logger", ".", "error", "(", "resp", ".", "text", ")", "resp", ".", "raise_for_status", "(", ")", "return", "resp", ".", "json", "(", ")", "[", "'access_token'", "]" ]
Return the bearer token for a given pair of consumer key and secret values.
[ "Return", "the", "bearer", "token", "for", "a", "given", "pair", "of", "consumer", "key", "and", "secret", "values", "." ]
7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/credentials.py#L193-L206
4,466
kvesteri/validators
validators/i18n/fi.py
fi_business_id
def fi_business_id(business_id): """ Validate a Finnish Business ID. Each company in Finland has a distinct business id. For more information see `Finnish Trade Register`_ .. _Finnish Trade Register: http://en.wikipedia.org/wiki/Finnish_Trade_Register Examples:: >>> fi_business_id('0112038-9') # Fast Monkeys Ltd True >>> fi_business_id('1234567-8') # Bogus ID ValidationFailure(func=fi_business_id, ...) .. versionadded:: 0.4 .. versionchanged:: 0.5 Method renamed from ``finnish_business_id`` to ``fi_business_id`` :param business_id: business_id to validate """ if not business_id or not re.match(business_id_pattern, business_id): return False factors = [7, 9, 10, 5, 8, 4, 2] numbers = map(int, business_id[:7]) checksum = int(business_id[8]) sum_ = sum(f * n for f, n in zip(factors, numbers)) modulo = sum_ % 11 return (11 - modulo == checksum) or (modulo == 0 and checksum == 0)
python
def fi_business_id(business_id): """ Validate a Finnish Business ID. Each company in Finland has a distinct business id. For more information see `Finnish Trade Register`_ .. _Finnish Trade Register: http://en.wikipedia.org/wiki/Finnish_Trade_Register Examples:: >>> fi_business_id('0112038-9') # Fast Monkeys Ltd True >>> fi_business_id('1234567-8') # Bogus ID ValidationFailure(func=fi_business_id, ...) .. versionadded:: 0.4 .. versionchanged:: 0.5 Method renamed from ``finnish_business_id`` to ``fi_business_id`` :param business_id: business_id to validate """ if not business_id or not re.match(business_id_pattern, business_id): return False factors = [7, 9, 10, 5, 8, 4, 2] numbers = map(int, business_id[:7]) checksum = int(business_id[8]) sum_ = sum(f * n for f, n in zip(factors, numbers)) modulo = sum_ % 11 return (11 - modulo == checksum) or (modulo == 0 and checksum == 0)
[ "def", "fi_business_id", "(", "business_id", ")", ":", "if", "not", "business_id", "or", "not", "re", ".", "match", "(", "business_id_pattern", ",", "business_id", ")", ":", "return", "False", "factors", "=", "[", "7", ",", "9", ",", "10", ",", "5", ",", "8", ",", "4", ",", "2", "]", "numbers", "=", "map", "(", "int", ",", "business_id", "[", ":", "7", "]", ")", "checksum", "=", "int", "(", "business_id", "[", "8", "]", ")", "sum_", "=", "sum", "(", "f", "*", "n", "for", "f", ",", "n", "in", "zip", "(", "factors", ",", "numbers", ")", ")", "modulo", "=", "sum_", "%", "11", "return", "(", "11", "-", "modulo", "==", "checksum", ")", "or", "(", "modulo", "==", "0", "and", "checksum", "==", "0", ")" ]
Validate a Finnish Business ID. Each company in Finland has a distinct business id. For more information see `Finnish Trade Register`_ .. _Finnish Trade Register: http://en.wikipedia.org/wiki/Finnish_Trade_Register Examples:: >>> fi_business_id('0112038-9') # Fast Monkeys Ltd True >>> fi_business_id('1234567-8') # Bogus ID ValidationFailure(func=fi_business_id, ...) .. versionadded:: 0.4 .. versionchanged:: 0.5 Method renamed from ``finnish_business_id`` to ``fi_business_id`` :param business_id: business_id to validate
[ "Validate", "a", "Finnish", "Business", "ID", "." ]
34d355e87168241e872b25811d245810df2bd430
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/i18n/fi.py#L20-L51
4,467
kvesteri/validators
validators/i18n/fi.py
fi_ssn
def fi_ssn(ssn, allow_temporal_ssn=True): """ Validate a Finnish Social Security Number. This validator is based on `django-localflavor-fi`_. .. _django-localflavor-fi: https://github.com/django/django-localflavor-fi/ Examples:: >>> fi_ssn('010101-0101') True >>> fi_ssn('101010-0102') ValidationFailure(func=fi_ssn, args=...) .. versionadded:: 0.5 :param ssn: Social Security Number to validate :param allow_temporal_ssn: Whether to accept temporal SSN numbers. Temporal SSN numbers are the ones where the serial is in the range [900-999]. By default temporal SSN numbers are valid. """ if not ssn: return False result = re.match(ssn_pattern, ssn) if not result: return False gd = result.groupdict() checksum = int(gd['date'] + gd['serial']) return ( int(gd['serial']) >= 2 and (allow_temporal_ssn or int(gd['serial']) <= 899) and ssn_checkmarks[checksum % len(ssn_checkmarks)] == gd['checksum'] )
python
def fi_ssn(ssn, allow_temporal_ssn=True): """ Validate a Finnish Social Security Number. This validator is based on `django-localflavor-fi`_. .. _django-localflavor-fi: https://github.com/django/django-localflavor-fi/ Examples:: >>> fi_ssn('010101-0101') True >>> fi_ssn('101010-0102') ValidationFailure(func=fi_ssn, args=...) .. versionadded:: 0.5 :param ssn: Social Security Number to validate :param allow_temporal_ssn: Whether to accept temporal SSN numbers. Temporal SSN numbers are the ones where the serial is in the range [900-999]. By default temporal SSN numbers are valid. """ if not ssn: return False result = re.match(ssn_pattern, ssn) if not result: return False gd = result.groupdict() checksum = int(gd['date'] + gd['serial']) return ( int(gd['serial']) >= 2 and (allow_temporal_ssn or int(gd['serial']) <= 899) and ssn_checkmarks[checksum % len(ssn_checkmarks)] == gd['checksum'] )
[ "def", "fi_ssn", "(", "ssn", ",", "allow_temporal_ssn", "=", "True", ")", ":", "if", "not", "ssn", ":", "return", "False", "result", "=", "re", ".", "match", "(", "ssn_pattern", ",", "ssn", ")", "if", "not", "result", ":", "return", "False", "gd", "=", "result", ".", "groupdict", "(", ")", "checksum", "=", "int", "(", "gd", "[", "'date'", "]", "+", "gd", "[", "'serial'", "]", ")", "return", "(", "int", "(", "gd", "[", "'serial'", "]", ")", ">=", "2", "and", "(", "allow_temporal_ssn", "or", "int", "(", "gd", "[", "'serial'", "]", ")", "<=", "899", ")", "and", "ssn_checkmarks", "[", "checksum", "%", "len", "(", "ssn_checkmarks", ")", "]", "==", "gd", "[", "'checksum'", "]", ")" ]
Validate a Finnish Social Security Number. This validator is based on `django-localflavor-fi`_. .. _django-localflavor-fi: https://github.com/django/django-localflavor-fi/ Examples:: >>> fi_ssn('010101-0101') True >>> fi_ssn('101010-0102') ValidationFailure(func=fi_ssn, args=...) .. versionadded:: 0.5 :param ssn: Social Security Number to validate :param allow_temporal_ssn: Whether to accept temporal SSN numbers. Temporal SSN numbers are the ones where the serial is in the range [900-999]. By default temporal SSN numbers are valid.
[ "Validate", "a", "Finnish", "Social", "Security", "Number", "." ]
34d355e87168241e872b25811d245810df2bd430
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/i18n/fi.py#L55-L94
4,468
kvesteri/validators
validators/iban.py
modcheck
def modcheck(value): """Check if the value string passes the mod97-test. """ # move country code and check numbers to end rearranged = value[4:] + value[:4] # convert letters to numbers converted = [char_value(char) for char in rearranged] # interpret as integer integerized = int(''.join([str(i) for i in converted])) return (integerized % 97 == 1)
python
def modcheck(value): """Check if the value string passes the mod97-test. """ # move country code and check numbers to end rearranged = value[4:] + value[:4] # convert letters to numbers converted = [char_value(char) for char in rearranged] # interpret as integer integerized = int(''.join([str(i) for i in converted])) return (integerized % 97 == 1)
[ "def", "modcheck", "(", "value", ")", ":", "# move country code and check numbers to end", "rearranged", "=", "value", "[", "4", ":", "]", "+", "value", "[", ":", "4", "]", "# convert letters to numbers", "converted", "=", "[", "char_value", "(", "char", ")", "for", "char", "in", "rearranged", "]", "# interpret as integer", "integerized", "=", "int", "(", "''", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "converted", "]", ")", ")", "return", "(", "integerized", "%", "97", "==", "1", ")" ]
Check if the value string passes the mod97-test.
[ "Check", "if", "the", "value", "string", "passes", "the", "mod97", "-", "test", "." ]
34d355e87168241e872b25811d245810df2bd430
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/iban.py#L20-L29
4,469
kvesteri/validators
validators/utils.py
func_args_as_dict
def func_args_as_dict(func, args, kwargs): """ Return given function's positional and key value arguments as an ordered dictionary. """ if six.PY2: _getargspec = inspect.getargspec else: _getargspec = inspect.getfullargspec arg_names = list( OrderedDict.fromkeys( itertools.chain( _getargspec(func)[0], kwargs.keys() ) ) ) return OrderedDict( list(six.moves.zip(arg_names, args)) + list(kwargs.items()) )
python
def func_args_as_dict(func, args, kwargs): """ Return given function's positional and key value arguments as an ordered dictionary. """ if six.PY2: _getargspec = inspect.getargspec else: _getargspec = inspect.getfullargspec arg_names = list( OrderedDict.fromkeys( itertools.chain( _getargspec(func)[0], kwargs.keys() ) ) ) return OrderedDict( list(six.moves.zip(arg_names, args)) + list(kwargs.items()) )
[ "def", "func_args_as_dict", "(", "func", ",", "args", ",", "kwargs", ")", ":", "if", "six", ".", "PY2", ":", "_getargspec", "=", "inspect", ".", "getargspec", "else", ":", "_getargspec", "=", "inspect", ".", "getfullargspec", "arg_names", "=", "list", "(", "OrderedDict", ".", "fromkeys", "(", "itertools", ".", "chain", "(", "_getargspec", "(", "func", ")", "[", "0", "]", ",", "kwargs", ".", "keys", "(", ")", ")", ")", ")", "return", "OrderedDict", "(", "list", "(", "six", ".", "moves", ".", "zip", "(", "arg_names", ",", "args", ")", ")", "+", "list", "(", "kwargs", ".", "items", "(", ")", ")", ")" ]
Return given function's positional and key value arguments as an ordered dictionary.
[ "Return", "given", "function", "s", "positional", "and", "key", "value", "arguments", "as", "an", "ordered", "dictionary", "." ]
34d355e87168241e872b25811d245810df2bd430
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/utils.py#L35-L56
4,470
kvesteri/validators
validators/utils.py
validator
def validator(func, *args, **kwargs): """ A decorator that makes given function validator. Whenever the given function is called and returns ``False`` value this decorator returns :class:`ValidationFailure` object. Example:: >>> @validator ... def even(value): ... return not (value % 2) >>> even(4) True >>> even(5) ValidationFailure(func=even, args={'value': 5}) :param func: function to decorate :param args: positional function arguments :param kwargs: key value function arguments """ def wrapper(func, *args, **kwargs): value = func(*args, **kwargs) if not value: return ValidationFailure( func, func_args_as_dict(func, args, kwargs) ) return True return decorator(wrapper, func)
python
def validator(func, *args, **kwargs): """ A decorator that makes given function validator. Whenever the given function is called and returns ``False`` value this decorator returns :class:`ValidationFailure` object. Example:: >>> @validator ... def even(value): ... return not (value % 2) >>> even(4) True >>> even(5) ValidationFailure(func=even, args={'value': 5}) :param func: function to decorate :param args: positional function arguments :param kwargs: key value function arguments """ def wrapper(func, *args, **kwargs): value = func(*args, **kwargs) if not value: return ValidationFailure( func, func_args_as_dict(func, args, kwargs) ) return True return decorator(wrapper, func)
[ "def", "validator", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "wrapper", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "value", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "value", ":", "return", "ValidationFailure", "(", "func", ",", "func_args_as_dict", "(", "func", ",", "args", ",", "kwargs", ")", ")", "return", "True", "return", "decorator", "(", "wrapper", ",", "func", ")" ]
A decorator that makes given function validator. Whenever the given function is called and returns ``False`` value this decorator returns :class:`ValidationFailure` object. Example:: >>> @validator ... def even(value): ... return not (value % 2) >>> even(4) True >>> even(5) ValidationFailure(func=even, args={'value': 5}) :param func: function to decorate :param args: positional function arguments :param kwargs: key value function arguments
[ "A", "decorator", "that", "makes", "given", "function", "validator", "." ]
34d355e87168241e872b25811d245810df2bd430
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/utils.py#L59-L89
4,471
kvesteri/validators
validators/length.py
length
def length(value, min=None, max=None): """ Return whether or not the length of given string is within a specified range. Examples:: >>> length('something', min=2) True >>> length('something', min=9, max=9) True >>> length('something', max=5) ValidationFailure(func=length, ...) :param value: The string to validate. :param min: The minimum required length of the string. If not provided, minimum length will not be checked. :param max: The maximum length of the string. If not provided, maximum length will not be checked. .. versionadded:: 0.2 """ if (min is not None and min < 0) or (max is not None and max < 0): raise AssertionError( '`min` and `max` need to be greater than zero.' ) return between(len(value), min=min, max=max)
python
def length(value, min=None, max=None): """ Return whether or not the length of given string is within a specified range. Examples:: >>> length('something', min=2) True >>> length('something', min=9, max=9) True >>> length('something', max=5) ValidationFailure(func=length, ...) :param value: The string to validate. :param min: The minimum required length of the string. If not provided, minimum length will not be checked. :param max: The maximum length of the string. If not provided, maximum length will not be checked. .. versionadded:: 0.2 """ if (min is not None and min < 0) or (max is not None and max < 0): raise AssertionError( '`min` and `max` need to be greater than zero.' ) return between(len(value), min=min, max=max)
[ "def", "length", "(", "value", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "if", "(", "min", "is", "not", "None", "and", "min", "<", "0", ")", "or", "(", "max", "is", "not", "None", "and", "max", "<", "0", ")", ":", "raise", "AssertionError", "(", "'`min` and `max` need to be greater than zero.'", ")", "return", "between", "(", "len", "(", "value", ")", ",", "min", "=", "min", ",", "max", "=", "max", ")" ]
Return whether or not the length of given string is within a specified range. Examples:: >>> length('something', min=2) True >>> length('something', min=9, max=9) True >>> length('something', max=5) ValidationFailure(func=length, ...) :param value: The string to validate. :param min: The minimum required length of the string. If not provided, minimum length will not be checked. :param max: The maximum length of the string. If not provided, maximum length will not be checked. .. versionadded:: 0.2
[ "Return", "whether", "or", "not", "the", "length", "of", "given", "string", "is", "within", "a", "specified", "range", "." ]
34d355e87168241e872b25811d245810df2bd430
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/length.py#L6-L37
4,472
kvesteri/validators
validators/url.py
url
def url(value, public=False): """ Return whether or not given value is a valid URL. If the value is valid URL this function returns ``True``, otherwise :class:`~validators.utils.ValidationFailure`. This validator is based on the wonderful `URL validator of dperini`_. .. _URL validator of dperini: https://gist.github.com/dperini/729294 Examples:: >>> url('http://foobar.dk') True >>> url('ftp://foobar.dk') True >>> url('http://10.0.0.1') True >>> url('http://foobar.d') ValidationFailure(func=url, ...) >>> url('http://10.0.0.1', public=True) ValidationFailure(func=url, ...) .. versionadded:: 0.2 .. versionchanged:: 0.10.2 Added support for various exotic URLs and fixed various false positives. .. versionchanged:: 0.10.3 Added ``public`` parameter. .. versionchanged:: 0.11.0 Made the regular expression this function uses case insensitive. .. versionchanged:: 0.11.3 Added support for URLs containing localhost :param value: URL address string to validate :param public: (default=False) Set True to only allow a public IP address """ result = pattern.match(value) if not public: return result return result and not any( (result.groupdict().get(key) for key in ('private_ip', 'private_host')) )
python
def url(value, public=False): """ Return whether or not given value is a valid URL. If the value is valid URL this function returns ``True``, otherwise :class:`~validators.utils.ValidationFailure`. This validator is based on the wonderful `URL validator of dperini`_. .. _URL validator of dperini: https://gist.github.com/dperini/729294 Examples:: >>> url('http://foobar.dk') True >>> url('ftp://foobar.dk') True >>> url('http://10.0.0.1') True >>> url('http://foobar.d') ValidationFailure(func=url, ...) >>> url('http://10.0.0.1', public=True) ValidationFailure(func=url, ...) .. versionadded:: 0.2 .. versionchanged:: 0.10.2 Added support for various exotic URLs and fixed various false positives. .. versionchanged:: 0.10.3 Added ``public`` parameter. .. versionchanged:: 0.11.0 Made the regular expression this function uses case insensitive. .. versionchanged:: 0.11.3 Added support for URLs containing localhost :param value: URL address string to validate :param public: (default=False) Set True to only allow a public IP address """ result = pattern.match(value) if not public: return result return result and not any( (result.groupdict().get(key) for key in ('private_ip', 'private_host')) )
[ "def", "url", "(", "value", ",", "public", "=", "False", ")", ":", "result", "=", "pattern", ".", "match", "(", "value", ")", "if", "not", "public", ":", "return", "result", "return", "result", "and", "not", "any", "(", "(", "result", ".", "groupdict", "(", ")", ".", "get", "(", "key", ")", "for", "key", "in", "(", "'private_ip'", ",", "'private_host'", ")", ")", ")" ]
Return whether or not given value is a valid URL. If the value is valid URL this function returns ``True``, otherwise :class:`~validators.utils.ValidationFailure`. This validator is based on the wonderful `URL validator of dperini`_. .. _URL validator of dperini: https://gist.github.com/dperini/729294 Examples:: >>> url('http://foobar.dk') True >>> url('ftp://foobar.dk') True >>> url('http://10.0.0.1') True >>> url('http://foobar.d') ValidationFailure(func=url, ...) >>> url('http://10.0.0.1', public=True) ValidationFailure(func=url, ...) .. versionadded:: 0.2 .. versionchanged:: 0.10.2 Added support for various exotic URLs and fixed various false positives. .. versionchanged:: 0.10.3 Added ``public`` parameter. .. versionchanged:: 0.11.0 Made the regular expression this function uses case insensitive. .. versionchanged:: 0.11.3 Added support for URLs containing localhost :param value: URL address string to validate :param public: (default=False) Set True to only allow a public IP address
[ "Return", "whether", "or", "not", "given", "value", "is", "a", "valid", "URL", "." ]
34d355e87168241e872b25811d245810df2bd430
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/url.py#L94-L151
4,473
kvesteri/validators
validators/ip_address.py
ipv4
def ipv4(value): """ Return whether or not given value is a valid IP version 4 address. This validator is based on `WTForms IPAddress validator`_ .. _WTForms IPAddress validator: https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py Examples:: >>> ipv4('123.0.0.7') True >>> ipv4('900.80.70.11') ValidationFailure(func=ipv4, args={'value': '900.80.70.11'}) .. versionadded:: 0.2 :param value: IP address string to validate """ groups = value.split('.') if len(groups) != 4 or any(not x.isdigit() for x in groups): return False return all(0 <= int(part) < 256 for part in groups)
python
def ipv4(value): """ Return whether or not given value is a valid IP version 4 address. This validator is based on `WTForms IPAddress validator`_ .. _WTForms IPAddress validator: https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py Examples:: >>> ipv4('123.0.0.7') True >>> ipv4('900.80.70.11') ValidationFailure(func=ipv4, args={'value': '900.80.70.11'}) .. versionadded:: 0.2 :param value: IP address string to validate """ groups = value.split('.') if len(groups) != 4 or any(not x.isdigit() for x in groups): return False return all(0 <= int(part) < 256 for part in groups)
[ "def", "ipv4", "(", "value", ")", ":", "groups", "=", "value", ".", "split", "(", "'.'", ")", "if", "len", "(", "groups", ")", "!=", "4", "or", "any", "(", "not", "x", ".", "isdigit", "(", ")", "for", "x", "in", "groups", ")", ":", "return", "False", "return", "all", "(", "0", "<=", "int", "(", "part", ")", "<", "256", "for", "part", "in", "groups", ")" ]
Return whether or not given value is a valid IP version 4 address. This validator is based on `WTForms IPAddress validator`_ .. _WTForms IPAddress validator: https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py Examples:: >>> ipv4('123.0.0.7') True >>> ipv4('900.80.70.11') ValidationFailure(func=ipv4, args={'value': '900.80.70.11'}) .. versionadded:: 0.2 :param value: IP address string to validate
[ "Return", "whether", "or", "not", "given", "value", "is", "a", "valid", "IP", "version", "4", "address", "." ]
34d355e87168241e872b25811d245810df2bd430
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/ip_address.py#L5-L29
4,474
eddyxu/cpp-coveralls
cpp_coveralls/report.py
post_report
def post_report(coverage, args): """Post coverage report to coveralls.io.""" response = requests.post(URL, files={'json_file': json.dumps(coverage)}, verify=(not args.skip_ssl_verify)) try: result = response.json() except ValueError: result = {'error': 'Failure to submit data. ' 'Response [%(status)s]: %(text)s' % { 'status': response.status_code, 'text': response.text}} print(result) if 'error' in result: return result['error'] return 0
python
def post_report(coverage, args): """Post coverage report to coveralls.io.""" response = requests.post(URL, files={'json_file': json.dumps(coverage)}, verify=(not args.skip_ssl_verify)) try: result = response.json() except ValueError: result = {'error': 'Failure to submit data. ' 'Response [%(status)s]: %(text)s' % { 'status': response.status_code, 'text': response.text}} print(result) if 'error' in result: return result['error'] return 0
[ "def", "post_report", "(", "coverage", ",", "args", ")", ":", "response", "=", "requests", ".", "post", "(", "URL", ",", "files", "=", "{", "'json_file'", ":", "json", ".", "dumps", "(", "coverage", ")", "}", ",", "verify", "=", "(", "not", "args", ".", "skip_ssl_verify", ")", ")", "try", ":", "result", "=", "response", ".", "json", "(", ")", "except", "ValueError", ":", "result", "=", "{", "'error'", ":", "'Failure to submit data. '", "'Response [%(status)s]: %(text)s'", "%", "{", "'status'", ":", "response", ".", "status_code", ",", "'text'", ":", "response", ".", "text", "}", "}", "print", "(", "result", ")", "if", "'error'", "in", "result", ":", "return", "result", "[", "'error'", "]", "return", "0" ]
Post coverage report to coveralls.io.
[ "Post", "coverage", "report", "to", "coveralls", ".", "io", "." ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/report.py#L10-L24
4,475
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
is_source_file
def is_source_file(args, filepath): """Returns true if it is a C++ source file.""" if args.extension: return os.path.splitext(filepath)[1] in args.extension else: return os.path.splitext(filepath)[1] in _CPP_EXTENSIONS
python
def is_source_file(args, filepath): """Returns true if it is a C++ source file.""" if args.extension: return os.path.splitext(filepath)[1] in args.extension else: return os.path.splitext(filepath)[1] in _CPP_EXTENSIONS
[ "def", "is_source_file", "(", "args", ",", "filepath", ")", ":", "if", "args", ".", "extension", ":", "return", "os", ".", "path", ".", "splitext", "(", "filepath", ")", "[", "1", "]", "in", "args", ".", "extension", "else", ":", "return", "os", ".", "path", ".", "splitext", "(", "filepath", ")", "[", "1", "]", "in", "_CPP_EXTENSIONS" ]
Returns true if it is a C++ source file.
[ "Returns", "true", "if", "it", "is", "a", "C", "++", "source", "file", "." ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L93-L98
4,476
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
exclude_paths
def exclude_paths(args): """Returns the absolute paths for excluded path.""" results = [] if args.exclude: for excl_path in args.exclude: results.append(os.path.abspath(os.path.join(args.root, excl_path))) return results
python
def exclude_paths(args): """Returns the absolute paths for excluded path.""" results = [] if args.exclude: for excl_path in args.exclude: results.append(os.path.abspath(os.path.join(args.root, excl_path))) return results
[ "def", "exclude_paths", "(", "args", ")", ":", "results", "=", "[", "]", "if", "args", ".", "exclude", ":", "for", "excl_path", "in", "args", ".", "exclude", ":", "results", ".", "append", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "args", ".", "root", ",", "excl_path", ")", ")", ")", "return", "results" ]
Returns the absolute paths for excluded path.
[ "Returns", "the", "absolute", "paths", "for", "excluded", "path", "." ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L101-L107
4,477
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
create_exclude_rules
def create_exclude_rules(args): """Creates the exlude rules """ global _cached_exclude_rules if _cached_exclude_rules is not None: return _cached_exclude_rules rules = [] for excl_path in args.exclude: abspath = os.path.abspath(os.path.join(args.root, excl_path)) rules.append((abspath, True)) for incl_path in args.include: abspath = os.path.abspath(os.path.join(args.root, incl_path)) rules.append((abspath, False)) _cached_exclude_rules = sorted(rules, key=lambda p: p[0]) return _cached_exclude_rules
python
def create_exclude_rules(args): """Creates the exlude rules """ global _cached_exclude_rules if _cached_exclude_rules is not None: return _cached_exclude_rules rules = [] for excl_path in args.exclude: abspath = os.path.abspath(os.path.join(args.root, excl_path)) rules.append((abspath, True)) for incl_path in args.include: abspath = os.path.abspath(os.path.join(args.root, incl_path)) rules.append((abspath, False)) _cached_exclude_rules = sorted(rules, key=lambda p: p[0]) return _cached_exclude_rules
[ "def", "create_exclude_rules", "(", "args", ")", ":", "global", "_cached_exclude_rules", "if", "_cached_exclude_rules", "is", "not", "None", ":", "return", "_cached_exclude_rules", "rules", "=", "[", "]", "for", "excl_path", "in", "args", ".", "exclude", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "args", ".", "root", ",", "excl_path", ")", ")", "rules", ".", "append", "(", "(", "abspath", ",", "True", ")", ")", "for", "incl_path", "in", "args", ".", "include", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "args", ".", "root", ",", "incl_path", ")", ")", "rules", ".", "append", "(", "(", "abspath", ",", "False", ")", ")", "_cached_exclude_rules", "=", "sorted", "(", "rules", ",", "key", "=", "lambda", "p", ":", "p", "[", "0", "]", ")", "return", "_cached_exclude_rules" ]
Creates the exlude rules
[ "Creates", "the", "exlude", "rules" ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L113-L127
4,478
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
is_excluded_path
def is_excluded_path(args, filepath): """Returns true if the filepath is under the one of the exclude path.""" # Try regular expressions first. for regexp_exclude_path in args.regexp: if re.match(regexp_exclude_path, filepath): return True abspath = os.path.abspath(filepath) if args.include: # If the file is outside of any include directories. out_of_include_dirs = True for incl_path in args.include: absolute_include_path = os.path.abspath(os.path.join(args.root, incl_path)) if is_child_dir(absolute_include_path, abspath): out_of_include_dirs = False break if out_of_include_dirs: return True excl_rules = create_exclude_rules(args) for i, rule in enumerate(excl_rules): if rule[0] == abspath: return rule[1] if is_child_dir(rule[0], abspath): # continue to try to longest match. last_result = rule[1] for j in range(i + 1, len(excl_rules)): rule_deep = excl_rules[j] if not is_child_dir(rule_deep[0], abspath): break last_result = rule_deep[1] return last_result return False
python
def is_excluded_path(args, filepath): """Returns true if the filepath is under the one of the exclude path.""" # Try regular expressions first. for regexp_exclude_path in args.regexp: if re.match(regexp_exclude_path, filepath): return True abspath = os.path.abspath(filepath) if args.include: # If the file is outside of any include directories. out_of_include_dirs = True for incl_path in args.include: absolute_include_path = os.path.abspath(os.path.join(args.root, incl_path)) if is_child_dir(absolute_include_path, abspath): out_of_include_dirs = False break if out_of_include_dirs: return True excl_rules = create_exclude_rules(args) for i, rule in enumerate(excl_rules): if rule[0] == abspath: return rule[1] if is_child_dir(rule[0], abspath): # continue to try to longest match. last_result = rule[1] for j in range(i + 1, len(excl_rules)): rule_deep = excl_rules[j] if not is_child_dir(rule_deep[0], abspath): break last_result = rule_deep[1] return last_result return False
[ "def", "is_excluded_path", "(", "args", ",", "filepath", ")", ":", "# Try regular expressions first.", "for", "regexp_exclude_path", "in", "args", ".", "regexp", ":", "if", "re", ".", "match", "(", "regexp_exclude_path", ",", "filepath", ")", ":", "return", "True", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "filepath", ")", "if", "args", ".", "include", ":", "# If the file is outside of any include directories.", "out_of_include_dirs", "=", "True", "for", "incl_path", "in", "args", ".", "include", ":", "absolute_include_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "args", ".", "root", ",", "incl_path", ")", ")", "if", "is_child_dir", "(", "absolute_include_path", ",", "abspath", ")", ":", "out_of_include_dirs", "=", "False", "break", "if", "out_of_include_dirs", ":", "return", "True", "excl_rules", "=", "create_exclude_rules", "(", "args", ")", "for", "i", ",", "rule", "in", "enumerate", "(", "excl_rules", ")", ":", "if", "rule", "[", "0", "]", "==", "abspath", ":", "return", "rule", "[", "1", "]", "if", "is_child_dir", "(", "rule", "[", "0", "]", ",", "abspath", ")", ":", "# continue to try to longest match.", "last_result", "=", "rule", "[", "1", "]", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "excl_rules", ")", ")", ":", "rule_deep", "=", "excl_rules", "[", "j", "]", "if", "not", "is_child_dir", "(", "rule_deep", "[", "0", "]", ",", "abspath", ")", ":", "break", "last_result", "=", "rule_deep", "[", "1", "]", "return", "last_result", "return", "False" ]
Returns true if the filepath is under the one of the exclude path.
[ "Returns", "true", "if", "the", "filepath", "is", "under", "the", "one", "of", "the", "exclude", "path", "." ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L135-L166
4,479
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
filter_dirs
def filter_dirs(root, dirs, excl_paths): """Filter directory paths based on the exclusion rules defined in 'excl_paths'. """ filtered_dirs = [] for dirpath in dirs: abspath = os.path.abspath(os.path.join(root, dirpath)) if os.path.basename(abspath) in _SKIP_DIRS: continue if abspath not in excl_paths: filtered_dirs.append(dirpath) return filtered_dirs
python
def filter_dirs(root, dirs, excl_paths): """Filter directory paths based on the exclusion rules defined in 'excl_paths'. """ filtered_dirs = [] for dirpath in dirs: abspath = os.path.abspath(os.path.join(root, dirpath)) if os.path.basename(abspath) in _SKIP_DIRS: continue if abspath not in excl_paths: filtered_dirs.append(dirpath) return filtered_dirs
[ "def", "filter_dirs", "(", "root", ",", "dirs", ",", "excl_paths", ")", ":", "filtered_dirs", "=", "[", "]", "for", "dirpath", "in", "dirs", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "root", ",", "dirpath", ")", ")", "if", "os", ".", "path", ".", "basename", "(", "abspath", ")", "in", "_SKIP_DIRS", ":", "continue", "if", "abspath", "not", "in", "excl_paths", ":", "filtered_dirs", ".", "append", "(", "dirpath", ")", "return", "filtered_dirs" ]
Filter directory paths based on the exclusion rules defined in 'excl_paths'.
[ "Filter", "directory", "paths", "based", "on", "the", "exclusion", "rules", "defined", "in", "excl_paths", "." ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L186-L197
4,480
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
parse_gcov_file
def parse_gcov_file(args, fobj, filename): """Parses the content of .gcov file """ coverage = [] ignoring = False for line in fobj: report_fields = line.decode('utf-8', 'replace').split(':', 2) if len(report_fields) == 1: continue line_num = report_fields[1].strip() if line_num == '': continue cov_num = report_fields[0].strip() line_num = int(line_num) text = report_fields[2] if line_num == 0: continue if re.search(r'\bLCOV_EXCL_START\b', text): if ignoring: sys.stderr.write("Warning: %s:%d: nested LCOV_EXCL_START, " "please fix\n" % (filename, line_num)) ignoring = True elif re.search(r'\bLCOV_EXCL_(STOP|END)\b', text): if not ignoring: sys.stderr.write("Warning: %s:%d: LCOV_EXCL_STOP outside of " "exclusion zone, please fix\n" % (filename, line_num)) if 'LCOV_EXCL_END' in text: sys.stderr.write("Warning: %s:%d: LCOV_EXCL_STOP is the " "correct keyword\n" % (filename, line_num)) ignoring = False if cov_num == '-': coverage.append(None) elif cov_num == '#####': # Avoid false positives. if ( ignoring or any([re.search(pattern, text) for pattern in args.exclude_lines_pattern]) ): coverage.append(None) else: coverage.append(0) elif cov_num == '=====': # This is indicitive of a gcov output parse # error. coverage.append(0) else: coverage.append(int(cov_num.rstrip('*'))) return coverage
python
def parse_gcov_file(args, fobj, filename): """Parses the content of .gcov file """ coverage = [] ignoring = False for line in fobj: report_fields = line.decode('utf-8', 'replace').split(':', 2) if len(report_fields) == 1: continue line_num = report_fields[1].strip() if line_num == '': continue cov_num = report_fields[0].strip() line_num = int(line_num) text = report_fields[2] if line_num == 0: continue if re.search(r'\bLCOV_EXCL_START\b', text): if ignoring: sys.stderr.write("Warning: %s:%d: nested LCOV_EXCL_START, " "please fix\n" % (filename, line_num)) ignoring = True elif re.search(r'\bLCOV_EXCL_(STOP|END)\b', text): if not ignoring: sys.stderr.write("Warning: %s:%d: LCOV_EXCL_STOP outside of " "exclusion zone, please fix\n" % (filename, line_num)) if 'LCOV_EXCL_END' in text: sys.stderr.write("Warning: %s:%d: LCOV_EXCL_STOP is the " "correct keyword\n" % (filename, line_num)) ignoring = False if cov_num == '-': coverage.append(None) elif cov_num == '#####': # Avoid false positives. if ( ignoring or any([re.search(pattern, text) for pattern in args.exclude_lines_pattern]) ): coverage.append(None) else: coverage.append(0) elif cov_num == '=====': # This is indicitive of a gcov output parse # error. coverage.append(0) else: coverage.append(int(cov_num.rstrip('*'))) return coverage
[ "def", "parse_gcov_file", "(", "args", ",", "fobj", ",", "filename", ")", ":", "coverage", "=", "[", "]", "ignoring", "=", "False", "for", "line", "in", "fobj", ":", "report_fields", "=", "line", ".", "decode", "(", "'utf-8'", ",", "'replace'", ")", ".", "split", "(", "':'", ",", "2", ")", "if", "len", "(", "report_fields", ")", "==", "1", ":", "continue", "line_num", "=", "report_fields", "[", "1", "]", ".", "strip", "(", ")", "if", "line_num", "==", "''", ":", "continue", "cov_num", "=", "report_fields", "[", "0", "]", ".", "strip", "(", ")", "line_num", "=", "int", "(", "line_num", ")", "text", "=", "report_fields", "[", "2", "]", "if", "line_num", "==", "0", ":", "continue", "if", "re", ".", "search", "(", "r'\\bLCOV_EXCL_START\\b'", ",", "text", ")", ":", "if", "ignoring", ":", "sys", ".", "stderr", ".", "write", "(", "\"Warning: %s:%d: nested LCOV_EXCL_START, \"", "\"please fix\\n\"", "%", "(", "filename", ",", "line_num", ")", ")", "ignoring", "=", "True", "elif", "re", ".", "search", "(", "r'\\bLCOV_EXCL_(STOP|END)\\b'", ",", "text", ")", ":", "if", "not", "ignoring", ":", "sys", ".", "stderr", ".", "write", "(", "\"Warning: %s:%d: LCOV_EXCL_STOP outside of \"", "\"exclusion zone, please fix\\n\"", "%", "(", "filename", ",", "line_num", ")", ")", "if", "'LCOV_EXCL_END'", "in", "text", ":", "sys", ".", "stderr", ".", "write", "(", "\"Warning: %s:%d: LCOV_EXCL_STOP is the \"", "\"correct keyword\\n\"", "%", "(", "filename", ",", "line_num", ")", ")", "ignoring", "=", "False", "if", "cov_num", "==", "'-'", ":", "coverage", ".", "append", "(", "None", ")", "elif", "cov_num", "==", "'#####'", ":", "# Avoid false positives.", "if", "(", "ignoring", "or", "any", "(", "[", "re", ".", "search", "(", "pattern", ",", "text", ")", "for", "pattern", "in", "args", ".", "exclude_lines_pattern", "]", ")", ")", ":", "coverage", ".", "append", "(", "None", ")", "else", ":", "coverage", ".", "append", "(", "0", ")", "elif", "cov_num", "==", "'====='", ":", "# This is indicitive of a gcov output parse", "# error.", "coverage", ".", "append", "(", "0", ")", "else", ":", "coverage", ".", "append", "(", "int", "(", "cov_num", ".", "rstrip", "(", "'*'", ")", ")", ")", "return", "coverage" ]
Parses the content of .gcov file
[ "Parses", "the", "content", "of", ".", "gcov", "file" ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L247-L296
4,481
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
parse_lcov_file_info
def parse_lcov_file_info(args, filepath, line_iter, line_coverage_re, file_end_string): """ Parse the file content in lcov info file """ coverage = [] lines_covered = [] for line in line_iter: if line != "end_of_record": line_coverage_match = line_coverage_re.match(line) if line_coverage_match: line_no = line_coverage_match.group(1) cov_count = int(line_coverage_match.group(2)) if args.max_cov_count: if cov_count > args.max_cov_count: cov_count = args.max_cov_count + 1 lines_covered.append((line_no, cov_count)) else: break num_code_lines = len([line.rstrip('\n') for line in open(filepath, 'r')]) coverage = [None] * num_code_lines for line_covered in lines_covered: coverage[int(line_covered[0]) - 1] = line_covered[1] return coverage
python
def parse_lcov_file_info(args, filepath, line_iter, line_coverage_re, file_end_string): """ Parse the file content in lcov info file """ coverage = [] lines_covered = [] for line in line_iter: if line != "end_of_record": line_coverage_match = line_coverage_re.match(line) if line_coverage_match: line_no = line_coverage_match.group(1) cov_count = int(line_coverage_match.group(2)) if args.max_cov_count: if cov_count > args.max_cov_count: cov_count = args.max_cov_count + 1 lines_covered.append((line_no, cov_count)) else: break num_code_lines = len([line.rstrip('\n') for line in open(filepath, 'r')]) coverage = [None] * num_code_lines for line_covered in lines_covered: coverage[int(line_covered[0]) - 1] = line_covered[1] return coverage
[ "def", "parse_lcov_file_info", "(", "args", ",", "filepath", ",", "line_iter", ",", "line_coverage_re", ",", "file_end_string", ")", ":", "coverage", "=", "[", "]", "lines_covered", "=", "[", "]", "for", "line", "in", "line_iter", ":", "if", "line", "!=", "\"end_of_record\"", ":", "line_coverage_match", "=", "line_coverage_re", ".", "match", "(", "line", ")", "if", "line_coverage_match", ":", "line_no", "=", "line_coverage_match", ".", "group", "(", "1", ")", "cov_count", "=", "int", "(", "line_coverage_match", ".", "group", "(", "2", ")", ")", "if", "args", ".", "max_cov_count", ":", "if", "cov_count", ">", "args", ".", "max_cov_count", ":", "cov_count", "=", "args", ".", "max_cov_count", "+", "1", "lines_covered", ".", "append", "(", "(", "line_no", ",", "cov_count", ")", ")", "else", ":", "break", "num_code_lines", "=", "len", "(", "[", "line", ".", "rstrip", "(", "'\\n'", ")", "for", "line", "in", "open", "(", "filepath", ",", "'r'", ")", "]", ")", "coverage", "=", "[", "None", "]", "*", "num_code_lines", "for", "line_covered", "in", "lines_covered", ":", "coverage", "[", "int", "(", "line_covered", "[", "0", "]", ")", "-", "1", "]", "=", "line_covered", "[", "1", "]", "return", "coverage" ]
Parse the file content in lcov info file
[ "Parse", "the", "file", "content", "in", "lcov", "info", "file" ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L299-L322
4,482
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
combine_reports
def combine_reports(original, new): """Combines two gcov reports for a file into one by adding the number of hits on each line """ if original is None: return new report = {} report['name'] = original['name'] report['source_digest'] = original['source_digest'] coverage = [] for original_num, new_num in zip(original['coverage'], new['coverage']): if original_num is None: coverage.append(new_num) elif new_num is None: coverage.append(original_num) else: coverage.append(original_num + new_num) report['coverage'] = coverage return report
python
def combine_reports(original, new): """Combines two gcov reports for a file into one by adding the number of hits on each line """ if original is None: return new report = {} report['name'] = original['name'] report['source_digest'] = original['source_digest'] coverage = [] for original_num, new_num in zip(original['coverage'], new['coverage']): if original_num is None: coverage.append(new_num) elif new_num is None: coverage.append(original_num) else: coverage.append(original_num + new_num) report['coverage'] = coverage return report
[ "def", "combine_reports", "(", "original", ",", "new", ")", ":", "if", "original", "is", "None", ":", "return", "new", "report", "=", "{", "}", "report", "[", "'name'", "]", "=", "original", "[", "'name'", "]", "report", "[", "'source_digest'", "]", "=", "original", "[", "'source_digest'", "]", "coverage", "=", "[", "]", "for", "original_num", ",", "new_num", "in", "zip", "(", "original", "[", "'coverage'", "]", ",", "new", "[", "'coverage'", "]", ")", ":", "if", "original_num", "is", "None", ":", "coverage", ".", "append", "(", "new_num", ")", "elif", "new_num", "is", "None", ":", "coverage", ".", "append", "(", "original_num", ")", "else", ":", "coverage", ".", "append", "(", "original_num", "+", "new_num", ")", "report", "[", "'coverage'", "]", "=", "coverage", "return", "report" ]
Combines two gcov reports for a file into one by adding the number of hits on each line
[ "Combines", "two", "gcov", "reports", "for", "a", "file", "into", "one", "by", "adding", "the", "number", "of", "hits", "on", "each", "line" ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L324-L342
4,483
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
collect_non_report_files
def collect_non_report_files(args, discovered_files): """Collects the source files that have no coverage reports. """ excl_paths = exclude_paths(args) abs_root = os.path.abspath(args.root) non_report_files = [] for root, dirs, files in os.walk(args.root, followlinks=args.follow_symlinks): dirs[:] = filter_dirs(root, dirs, excl_paths) for filename in files: if not is_source_file(args, filename): continue abs_filepath = os.path.join(os.path.abspath(root), filename) if is_excluded_path(args, abs_filepath): continue filepath = os.path.relpath(abs_filepath, abs_root) if filepath not in discovered_files: src_report = {} src_report['name'] = posix_path(filepath) coverage = [] with io.open(abs_filepath, mode='rb') as fobj: for _ in fobj: coverage.append(None) fobj.seek(0) src_report['source_digest'] = hashlib.md5(fobj.read()).hexdigest() src_report['coverage'] = coverage non_report_files.append(src_report) return non_report_files
python
def collect_non_report_files(args, discovered_files): """Collects the source files that have no coverage reports. """ excl_paths = exclude_paths(args) abs_root = os.path.abspath(args.root) non_report_files = [] for root, dirs, files in os.walk(args.root, followlinks=args.follow_symlinks): dirs[:] = filter_dirs(root, dirs, excl_paths) for filename in files: if not is_source_file(args, filename): continue abs_filepath = os.path.join(os.path.abspath(root), filename) if is_excluded_path(args, abs_filepath): continue filepath = os.path.relpath(abs_filepath, abs_root) if filepath not in discovered_files: src_report = {} src_report['name'] = posix_path(filepath) coverage = [] with io.open(abs_filepath, mode='rb') as fobj: for _ in fobj: coverage.append(None) fobj.seek(0) src_report['source_digest'] = hashlib.md5(fobj.read()).hexdigest() src_report['coverage'] = coverage non_report_files.append(src_report) return non_report_files
[ "def", "collect_non_report_files", "(", "args", ",", "discovered_files", ")", ":", "excl_paths", "=", "exclude_paths", "(", "args", ")", "abs_root", "=", "os", ".", "path", ".", "abspath", "(", "args", ".", "root", ")", "non_report_files", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "args", ".", "root", ",", "followlinks", "=", "args", ".", "follow_symlinks", ")", ":", "dirs", "[", ":", "]", "=", "filter_dirs", "(", "root", ",", "dirs", ",", "excl_paths", ")", "for", "filename", "in", "files", ":", "if", "not", "is_source_file", "(", "args", ",", "filename", ")", ":", "continue", "abs_filepath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "root", ")", ",", "filename", ")", "if", "is_excluded_path", "(", "args", ",", "abs_filepath", ")", ":", "continue", "filepath", "=", "os", ".", "path", ".", "relpath", "(", "abs_filepath", ",", "abs_root", ")", "if", "filepath", "not", "in", "discovered_files", ":", "src_report", "=", "{", "}", "src_report", "[", "'name'", "]", "=", "posix_path", "(", "filepath", ")", "coverage", "=", "[", "]", "with", "io", ".", "open", "(", "abs_filepath", ",", "mode", "=", "'rb'", ")", "as", "fobj", ":", "for", "_", "in", "fobj", ":", "coverage", ".", "append", "(", "None", ")", "fobj", ".", "seek", "(", "0", ")", "src_report", "[", "'source_digest'", "]", "=", "hashlib", ".", "md5", "(", "fobj", ".", "read", "(", ")", ")", ".", "hexdigest", "(", ")", "src_report", "[", "'coverage'", "]", "=", "coverage", "non_report_files", ".", "append", "(", "src_report", ")", "return", "non_report_files" ]
Collects the source files that have no coverage reports.
[ "Collects", "the", "source", "files", "that", "have", "no", "coverage", "reports", "." ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L344-L371
4,484
eddyxu/cpp-coveralls
cpp_coveralls/__init__.py
parse_yaml_config
def parse_yaml_config(args): """Parse yaml config""" try: import yaml except ImportError: yaml = None yml = {} try: with open(args.coveralls_yaml, 'r') as fp: if not yaml: raise SystemExit('PyYAML is required for parsing configuration') yml = yaml.load(fp) except IOError: pass yml = yml or {} return yml
python
def parse_yaml_config(args): """Parse yaml config""" try: import yaml except ImportError: yaml = None yml = {} try: with open(args.coveralls_yaml, 'r') as fp: if not yaml: raise SystemExit('PyYAML is required for parsing configuration') yml = yaml.load(fp) except IOError: pass yml = yml or {} return yml
[ "def", "parse_yaml_config", "(", "args", ")", ":", "try", ":", "import", "yaml", "except", "ImportError", ":", "yaml", "=", "None", "yml", "=", "{", "}", "try", ":", "with", "open", "(", "args", ".", "coveralls_yaml", ",", "'r'", ")", "as", "fp", ":", "if", "not", "yaml", ":", "raise", "SystemExit", "(", "'PyYAML is required for parsing configuration'", ")", "yml", "=", "yaml", ".", "load", "(", "fp", ")", "except", "IOError", ":", "pass", "yml", "=", "yml", "or", "{", "}", "return", "yml" ]
Parse yaml config
[ "Parse", "yaml", "config" ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/__init__.py#L37-L53
4,485
eddyxu/cpp-coveralls
cpp_coveralls/__init__.py
run
def run(): """Run cpp coverage.""" import json import os import sys from . import coverage, report args = coverage.create_args(sys.argv[1:]) if args.verbose: print('encodings: {}'.format(args.encodings)) yml = parse_yaml_config(args) if not args.repo_token: # try get token from yaml first args.repo_token = yml.get('repo_token', '') if not args.repo_token: # use environment COVERALLS_REPO_TOKEN as a fallback args.repo_token = os.environ.get('COVERALLS_REPO_TOKEN') args.service_name = yml.get('service_name', 'travis-ci') if not args.gcov_options: args.gcov_options = yml.get('gcov_options', '') if not args.root: args.root = yml.get('root', '.') if not args.build_root: args.build_root = yml.get('build_root', '') args.exclude.extend(yml.get('exclude', [])) args.include.extend(yml.get('include', [])) args.exclude_lines_pattern.extend(yml.get('exclude_lines_pattern', [])) args.service_job_id = os.environ.get('TRAVIS_JOB_ID', '') if args.repo_token == '' and args.service_job_id == '': raise ValueError("\nno coveralls.io token specified and no travis job id found\n" "see --help for examples on how to specify a token\n") if not args.no_gcov: coverage.run_gcov(args) cov_report = coverage.collect(args) if args.verbose: print(cov_report) if args.dryrun: return 0 if args.dump: args.dump.write(json.dumps(cov_report)) return 0 return report.post_report(cov_report, args)
python
def run(): """Run cpp coverage.""" import json import os import sys from . import coverage, report args = coverage.create_args(sys.argv[1:]) if args.verbose: print('encodings: {}'.format(args.encodings)) yml = parse_yaml_config(args) if not args.repo_token: # try get token from yaml first args.repo_token = yml.get('repo_token', '') if not args.repo_token: # use environment COVERALLS_REPO_TOKEN as a fallback args.repo_token = os.environ.get('COVERALLS_REPO_TOKEN') args.service_name = yml.get('service_name', 'travis-ci') if not args.gcov_options: args.gcov_options = yml.get('gcov_options', '') if not args.root: args.root = yml.get('root', '.') if not args.build_root: args.build_root = yml.get('build_root', '') args.exclude.extend(yml.get('exclude', [])) args.include.extend(yml.get('include', [])) args.exclude_lines_pattern.extend(yml.get('exclude_lines_pattern', [])) args.service_job_id = os.environ.get('TRAVIS_JOB_ID', '') if args.repo_token == '' and args.service_job_id == '': raise ValueError("\nno coveralls.io token specified and no travis job id found\n" "see --help for examples on how to specify a token\n") if not args.no_gcov: coverage.run_gcov(args) cov_report = coverage.collect(args) if args.verbose: print(cov_report) if args.dryrun: return 0 if args.dump: args.dump.write(json.dumps(cov_report)) return 0 return report.post_report(cov_report, args)
[ "def", "run", "(", ")", ":", "import", "json", "import", "os", "import", "sys", "from", ".", "import", "coverage", ",", "report", "args", "=", "coverage", ".", "create_args", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "if", "args", ".", "verbose", ":", "print", "(", "'encodings: {}'", ".", "format", "(", "args", ".", "encodings", ")", ")", "yml", "=", "parse_yaml_config", "(", "args", ")", "if", "not", "args", ".", "repo_token", ":", "# try get token from yaml first", "args", ".", "repo_token", "=", "yml", ".", "get", "(", "'repo_token'", ",", "''", ")", "if", "not", "args", ".", "repo_token", ":", "# use environment COVERALLS_REPO_TOKEN as a fallback", "args", ".", "repo_token", "=", "os", ".", "environ", ".", "get", "(", "'COVERALLS_REPO_TOKEN'", ")", "args", ".", "service_name", "=", "yml", ".", "get", "(", "'service_name'", ",", "'travis-ci'", ")", "if", "not", "args", ".", "gcov_options", ":", "args", ".", "gcov_options", "=", "yml", ".", "get", "(", "'gcov_options'", ",", "''", ")", "if", "not", "args", ".", "root", ":", "args", ".", "root", "=", "yml", ".", "get", "(", "'root'", ",", "'.'", ")", "if", "not", "args", ".", "build_root", ":", "args", ".", "build_root", "=", "yml", ".", "get", "(", "'build_root'", ",", "''", ")", "args", ".", "exclude", ".", "extend", "(", "yml", ".", "get", "(", "'exclude'", ",", "[", "]", ")", ")", "args", ".", "include", ".", "extend", "(", "yml", ".", "get", "(", "'include'", ",", "[", "]", ")", ")", "args", ".", "exclude_lines_pattern", ".", "extend", "(", "yml", ".", "get", "(", "'exclude_lines_pattern'", ",", "[", "]", ")", ")", "args", ".", "service_job_id", "=", "os", ".", "environ", ".", "get", "(", "'TRAVIS_JOB_ID'", ",", "''", ")", "if", "args", ".", "repo_token", "==", "''", "and", "args", ".", "service_job_id", "==", "''", ":", "raise", "ValueError", "(", "\"\\nno coveralls.io token specified and no travis job id found\\n\"", "\"see --help for examples on how to specify a token\\n\"", ")", "if", "not", "args", ".", "no_gcov", ":", "coverage", ".", "run_gcov", "(", "args", ")", "cov_report", "=", "coverage", ".", "collect", "(", "args", ")", "if", "args", ".", "verbose", ":", "print", "(", "cov_report", ")", "if", "args", ".", "dryrun", ":", "return", "0", "if", "args", ".", "dump", ":", "args", ".", "dump", ".", "write", "(", "json", ".", "dumps", "(", "cov_report", ")", ")", "return", "0", "return", "report", ".", "post_report", "(", "cov_report", ",", "args", ")" ]
Run cpp coverage.
[ "Run", "cpp", "coverage", "." ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/__init__.py#L55-L106
4,486
eddyxu/cpp-coveralls
cpp_coveralls/gitrepo.py
gitrepo
def gitrepo(cwd): """Return hash of Git data that can be used to display more information to users. Example: "git": { "head": { "id": "5e837ce92220be64821128a70f6093f836dd2c05", "author_name": "Wil Gieseler", "author_email": "[email protected]", "committer_name": "Wil Gieseler", "committer_email": "[email protected]", "message": "depend on simplecov >= 0.7" }, "branch": "master", "remotes": [{ "name": "origin", "url": "https://github.com/lemurheavy/coveralls-ruby.git" }] } From https://github.com/coagulant/coveralls-python (with MIT license). """ repo = Repository(cwd) if not repo.valid(): return {} return { 'head': { 'id': repo.gitlog('%H'), 'author_name': repo.gitlog('%aN'), 'author_email': repo.gitlog('%ae'), 'committer_name': repo.gitlog('%cN'), 'committer_email': repo.gitlog('%ce'), 'message': repo.gitlog('%s') }, 'branch': os.environ.get('TRAVIS_BRANCH', os.environ.get('APPVEYOR_REPO_BRANCH', repo.git('rev-parse', '--abbrev-ref', 'HEAD')[1].strip())), 'remotes': [{'name': line.split()[0], 'url': line.split()[1]} for line in repo.git('remote', '-v')[1] if '(fetch)' in line] }
python
def gitrepo(cwd): """Return hash of Git data that can be used to display more information to users. Example: "git": { "head": { "id": "5e837ce92220be64821128a70f6093f836dd2c05", "author_name": "Wil Gieseler", "author_email": "[email protected]", "committer_name": "Wil Gieseler", "committer_email": "[email protected]", "message": "depend on simplecov >= 0.7" }, "branch": "master", "remotes": [{ "name": "origin", "url": "https://github.com/lemurheavy/coveralls-ruby.git" }] } From https://github.com/coagulant/coveralls-python (with MIT license). """ repo = Repository(cwd) if not repo.valid(): return {} return { 'head': { 'id': repo.gitlog('%H'), 'author_name': repo.gitlog('%aN'), 'author_email': repo.gitlog('%ae'), 'committer_name': repo.gitlog('%cN'), 'committer_email': repo.gitlog('%ce'), 'message': repo.gitlog('%s') }, 'branch': os.environ.get('TRAVIS_BRANCH', os.environ.get('APPVEYOR_REPO_BRANCH', repo.git('rev-parse', '--abbrev-ref', 'HEAD')[1].strip())), 'remotes': [{'name': line.split()[0], 'url': line.split()[1]} for line in repo.git('remote', '-v')[1] if '(fetch)' in line] }
[ "def", "gitrepo", "(", "cwd", ")", ":", "repo", "=", "Repository", "(", "cwd", ")", "if", "not", "repo", ".", "valid", "(", ")", ":", "return", "{", "}", "return", "{", "'head'", ":", "{", "'id'", ":", "repo", ".", "gitlog", "(", "'%H'", ")", ",", "'author_name'", ":", "repo", ".", "gitlog", "(", "'%aN'", ")", ",", "'author_email'", ":", "repo", ".", "gitlog", "(", "'%ae'", ")", ",", "'committer_name'", ":", "repo", ".", "gitlog", "(", "'%cN'", ")", ",", "'committer_email'", ":", "repo", ".", "gitlog", "(", "'%ce'", ")", ",", "'message'", ":", "repo", ".", "gitlog", "(", "'%s'", ")", "}", ",", "'branch'", ":", "os", ".", "environ", ".", "get", "(", "'TRAVIS_BRANCH'", ",", "os", ".", "environ", ".", "get", "(", "'APPVEYOR_REPO_BRANCH'", ",", "repo", ".", "git", "(", "'rev-parse'", ",", "'--abbrev-ref'", ",", "'HEAD'", ")", "[", "1", "]", ".", "strip", "(", ")", ")", ")", ",", "'remotes'", ":", "[", "{", "'name'", ":", "line", ".", "split", "(", ")", "[", "0", "]", ",", "'url'", ":", "line", ".", "split", "(", ")", "[", "1", "]", "}", "for", "line", "in", "repo", ".", "git", "(", "'remote'", ",", "'-v'", ")", "[", "1", "]", "if", "'(fetch)'", "in", "line", "]", "}" ]
Return hash of Git data that can be used to display more information to users. Example: "git": { "head": { "id": "5e837ce92220be64821128a70f6093f836dd2c05", "author_name": "Wil Gieseler", "author_email": "[email protected]", "committer_name": "Wil Gieseler", "committer_email": "[email protected]", "message": "depend on simplecov >= 0.7" }, "branch": "master", "remotes": [{ "name": "origin", "url": "https://github.com/lemurheavy/coveralls-ruby.git" }] } From https://github.com/coagulant/coveralls-python (with MIT license).
[ "Return", "hash", "of", "Git", "data", "that", "can", "be", "used", "to", "display", "more", "information", "to", "users", "." ]
ff7af7eea2a23828f6ab2541667ea04f94344dce
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/gitrepo.py#L7-L49
4,487
vitiral/gpio
gpio.py
_verify
def _verify(function): """decorator to ensure pin is properly set up""" # @functools.wraps def wrapped(pin, *args, **kwargs): pin = int(pin) if pin not in _open: ppath = gpiopath(pin) if not os.path.exists(ppath): log.debug("Creating Pin {0}".format(pin)) with _export_lock: with open(pjoin(gpio_root, 'export'), 'w') as f: _write(f, pin) value = open(pjoin(ppath, 'value'), FMODE) direction = open(pjoin(ppath, 'direction'), FMODE) _open[pin] = PinState(value=value, direction=direction) return function(pin, *args, **kwargs) return wrapped
python
def _verify(function): """decorator to ensure pin is properly set up""" # @functools.wraps def wrapped(pin, *args, **kwargs): pin = int(pin) if pin not in _open: ppath = gpiopath(pin) if not os.path.exists(ppath): log.debug("Creating Pin {0}".format(pin)) with _export_lock: with open(pjoin(gpio_root, 'export'), 'w') as f: _write(f, pin) value = open(pjoin(ppath, 'value'), FMODE) direction = open(pjoin(ppath, 'direction'), FMODE) _open[pin] = PinState(value=value, direction=direction) return function(pin, *args, **kwargs) return wrapped
[ "def", "_verify", "(", "function", ")", ":", "# @functools.wraps\r", "def", "wrapped", "(", "pin", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pin", "=", "int", "(", "pin", ")", "if", "pin", "not", "in", "_open", ":", "ppath", "=", "gpiopath", "(", "pin", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "ppath", ")", ":", "log", ".", "debug", "(", "\"Creating Pin {0}\"", ".", "format", "(", "pin", ")", ")", "with", "_export_lock", ":", "with", "open", "(", "pjoin", "(", "gpio_root", ",", "'export'", ")", ",", "'w'", ")", "as", "f", ":", "_write", "(", "f", ",", "pin", ")", "value", "=", "open", "(", "pjoin", "(", "ppath", ",", "'value'", ")", ",", "FMODE", ")", "direction", "=", "open", "(", "pjoin", "(", "ppath", ",", "'direction'", ")", ",", "FMODE", ")", "_open", "[", "pin", "]", "=", "PinState", "(", "value", "=", "value", ",", "direction", "=", "direction", ")", "return", "function", "(", "pin", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapped" ]
decorator to ensure pin is properly set up
[ "decorator", "to", "ensure", "pin", "is", "properly", "set", "up" ]
d4d8bdc6965295b978eca882e2e2e5a1b35e047b
https://github.com/vitiral/gpio/blob/d4d8bdc6965295b978eca882e2e2e5a1b35e047b/gpio.py#L54-L70
4,488
vitiral/gpio
gpio.py
set
def set(pin, value): '''set the pin value to 0 or 1''' if value is LOW: value = 0 value = int(bool(value)) log.debug("Write {0}: {1}".format(pin, value)) f = _open[pin].value _write(f, value)
python
def set(pin, value): '''set the pin value to 0 or 1''' if value is LOW: value = 0 value = int(bool(value)) log.debug("Write {0}: {1}".format(pin, value)) f = _open[pin].value _write(f, value)
[ "def", "set", "(", "pin", ",", "value", ")", ":", "if", "value", "is", "LOW", ":", "value", "=", "0", "value", "=", "int", "(", "bool", "(", "value", ")", ")", "log", ".", "debug", "(", "\"Write {0}: {1}\"", ".", "format", "(", "pin", ",", "value", ")", ")", "f", "=", "_open", "[", "pin", "]", ".", "value", "_write", "(", "f", ",", "value", ")" ]
set the pin value to 0 or 1
[ "set", "the", "pin", "value", "to", "0", "or", "1" ]
d4d8bdc6965295b978eca882e2e2e5a1b35e047b
https://github.com/vitiral/gpio/blob/d4d8bdc6965295b978eca882e2e2e5a1b35e047b/gpio.py#L158-L165
4,489
fhs/pyhdf
pyhdf/V.py
V.end
def end(self): """Close the V interface. Args:: No argument Returns:: None C library equivalent : Vend """ # Note: Vend is just a macro; use 'Vfinish' instead # Note also the the same C function is used to end # the VS interface _checkErr('vend', _C.Vfinish(self._hdf_inst._id), "cannot terminate V interface") self._hdf_inst = None
python
def end(self): """Close the V interface. Args:: No argument Returns:: None C library equivalent : Vend """ # Note: Vend is just a macro; use 'Vfinish' instead # Note also the the same C function is used to end # the VS interface _checkErr('vend', _C.Vfinish(self._hdf_inst._id), "cannot terminate V interface") self._hdf_inst = None
[ "def", "end", "(", "self", ")", ":", "# Note: Vend is just a macro; use 'Vfinish' instead", "# Note also the the same C function is used to end", "# the VS interface", "_checkErr", "(", "'vend'", ",", "_C", ".", "Vfinish", "(", "self", ".", "_hdf_inst", ".", "_id", ")", ",", "\"cannot terminate V interface\"", ")", "self", ".", "_hdf_inst", "=", "None" ]
Close the V interface. Args:: No argument Returns:: None C library equivalent : Vend
[ "Close", "the", "V", "interface", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L704-L723
4,490
fhs/pyhdf
pyhdf/V.py
V.attach
def attach(self, num_name, write=0): """Open an existing vgroup given its name or its reference number, or create a new vgroup, returning a VG instance for that vgroup. Args:: num_name reference number or name of the vgroup to open, or -1 to create a new vgroup; vcreate() can also be called to create and name a new vgroup write set to non-zero to open the vgroup in write mode and to 0 to open it in readonly mode (default) Returns:: VG instance for the vgroup An exception is raised if an attempt is made to open a non-existent vgroup. C library equivalent : Vattach """ if isinstance(num_name, bytes): num = self.find(num_name) else: num = num_name vg_id = _C.Vattach(self._hdf_inst._id, num, write and 'w' or 'r') _checkErr('vattach', vg_id, "cannot attach Vgroup") return VG(self, vg_id)
python
def attach(self, num_name, write=0): """Open an existing vgroup given its name or its reference number, or create a new vgroup, returning a VG instance for that vgroup. Args:: num_name reference number or name of the vgroup to open, or -1 to create a new vgroup; vcreate() can also be called to create and name a new vgroup write set to non-zero to open the vgroup in write mode and to 0 to open it in readonly mode (default) Returns:: VG instance for the vgroup An exception is raised if an attempt is made to open a non-existent vgroup. C library equivalent : Vattach """ if isinstance(num_name, bytes): num = self.find(num_name) else: num = num_name vg_id = _C.Vattach(self._hdf_inst._id, num, write and 'w' or 'r') _checkErr('vattach', vg_id, "cannot attach Vgroup") return VG(self, vg_id)
[ "def", "attach", "(", "self", ",", "num_name", ",", "write", "=", "0", ")", ":", "if", "isinstance", "(", "num_name", ",", "bytes", ")", ":", "num", "=", "self", ".", "find", "(", "num_name", ")", "else", ":", "num", "=", "num_name", "vg_id", "=", "_C", ".", "Vattach", "(", "self", ".", "_hdf_inst", ".", "_id", ",", "num", ",", "write", "and", "'w'", "or", "'r'", ")", "_checkErr", "(", "'vattach'", ",", "vg_id", ",", "\"cannot attach Vgroup\"", ")", "return", "VG", "(", "self", ",", "vg_id", ")" ]
Open an existing vgroup given its name or its reference number, or create a new vgroup, returning a VG instance for that vgroup. Args:: num_name reference number or name of the vgroup to open, or -1 to create a new vgroup; vcreate() can also be called to create and name a new vgroup write set to non-zero to open the vgroup in write mode and to 0 to open it in readonly mode (default) Returns:: VG instance for the vgroup An exception is raised if an attempt is made to open a non-existent vgroup. C library equivalent : Vattach
[ "Open", "an", "existing", "vgroup", "given", "its", "name", "or", "its", "reference", "number", "or", "create", "a", "new", "vgroup", "returning", "a", "VG", "instance", "for", "that", "vgroup", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L725-L755
4,491
fhs/pyhdf
pyhdf/V.py
V.create
def create(self, name): """Create a new vgroup, and assign it a name. Args:: name name to assign to the new vgroup Returns:: VG instance for the new vgroup A create(name) call is equivalent to an attach(-1, 1) call, followed by a call to the setname(name) method of the instance. C library equivalent : no equivalent """ vg = self.attach(-1, 1) vg._name = name return vg
python
def create(self, name): """Create a new vgroup, and assign it a name. Args:: name name to assign to the new vgroup Returns:: VG instance for the new vgroup A create(name) call is equivalent to an attach(-1, 1) call, followed by a call to the setname(name) method of the instance. C library equivalent : no equivalent """ vg = self.attach(-1, 1) vg._name = name return vg
[ "def", "create", "(", "self", ",", "name", ")", ":", "vg", "=", "self", ".", "attach", "(", "-", "1", ",", "1", ")", "vg", ".", "_name", "=", "name", "return", "vg" ]
Create a new vgroup, and assign it a name. Args:: name name to assign to the new vgroup Returns:: VG instance for the new vgroup A create(name) call is equivalent to an attach(-1, 1) call, followed by a call to the setname(name) method of the instance. C library equivalent : no equivalent
[ "Create", "a", "new", "vgroup", "and", "assign", "it", "a", "name", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L757-L776
4,492
fhs/pyhdf
pyhdf/V.py
V.find
def find(self, name): """Find a vgroup given its name, returning its reference number if found. Args:: name name of the vgroup to find Returns:: vgroup reference number An exception is raised if the vgroup is not found. C library equivalent: Vfind """ refnum = _C.Vfind(self._hdf_inst._id, name) if not refnum: raise HDF4Error("vgroup not found") return refnum
python
def find(self, name): """Find a vgroup given its name, returning its reference number if found. Args:: name name of the vgroup to find Returns:: vgroup reference number An exception is raised if the vgroup is not found. C library equivalent: Vfind """ refnum = _C.Vfind(self._hdf_inst._id, name) if not refnum: raise HDF4Error("vgroup not found") return refnum
[ "def", "find", "(", "self", ",", "name", ")", ":", "refnum", "=", "_C", ".", "Vfind", "(", "self", ".", "_hdf_inst", ".", "_id", ",", "name", ")", "if", "not", "refnum", ":", "raise", "HDF4Error", "(", "\"vgroup not found\"", ")", "return", "refnum" ]
Find a vgroup given its name, returning its reference number if found. Args:: name name of the vgroup to find Returns:: vgroup reference number An exception is raised if the vgroup is not found. C library equivalent: Vfind
[ "Find", "a", "vgroup", "given", "its", "name", "returning", "its", "reference", "number", "if", "found", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L778-L798
4,493
fhs/pyhdf
pyhdf/V.py
V.findclass
def findclass(self, name): """Find a vgroup given its class name, returning its reference number if found. Args:: name class name of the vgroup to find Returns:: vgroup reference number An exception is raised if the vgroup is not found. C library equivalent: Vfind """ refnum = _C.Vfindclass(self._hdf_inst._id, name) if not refnum: raise HDF4Error("vgroup not found") return refnum
python
def findclass(self, name): """Find a vgroup given its class name, returning its reference number if found. Args:: name class name of the vgroup to find Returns:: vgroup reference number An exception is raised if the vgroup is not found. C library equivalent: Vfind """ refnum = _C.Vfindclass(self._hdf_inst._id, name) if not refnum: raise HDF4Error("vgroup not found") return refnum
[ "def", "findclass", "(", "self", ",", "name", ")", ":", "refnum", "=", "_C", ".", "Vfindclass", "(", "self", ".", "_hdf_inst", ".", "_id", ",", "name", ")", "if", "not", "refnum", ":", "raise", "HDF4Error", "(", "\"vgroup not found\"", ")", "return", "refnum" ]
Find a vgroup given its class name, returning its reference number if found. Args:: name class name of the vgroup to find Returns:: vgroup reference number An exception is raised if the vgroup is not found. C library equivalent: Vfind
[ "Find", "a", "vgroup", "given", "its", "class", "name", "returning", "its", "reference", "number", "if", "found", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L800-L820
4,494
fhs/pyhdf
pyhdf/V.py
V.delete
def delete(self, num_name): """Delete from the HDF file the vgroup identified by its reference number or its name. Args:: num_name either the reference number or the name of the vgroup to delete Returns:: None C library equivalent : Vdelete """ try: vg = self.attach(num_name, 1) except HDF4Error as msg: raise HDF4Error("delete: no such vgroup") # ATTENTION: The HDF documentation says that the vgroup_id # is passed to Vdelete(). This is wrong. # The vgroup reference number must instead be passed. refnum = vg._refnum vg.detach() _checkErr('delete', _C.Vdelete(self._hdf_inst._id, refnum), "error deleting vgroup")
python
def delete(self, num_name): """Delete from the HDF file the vgroup identified by its reference number or its name. Args:: num_name either the reference number or the name of the vgroup to delete Returns:: None C library equivalent : Vdelete """ try: vg = self.attach(num_name, 1) except HDF4Error as msg: raise HDF4Error("delete: no such vgroup") # ATTENTION: The HDF documentation says that the vgroup_id # is passed to Vdelete(). This is wrong. # The vgroup reference number must instead be passed. refnum = vg._refnum vg.detach() _checkErr('delete', _C.Vdelete(self._hdf_inst._id, refnum), "error deleting vgroup")
[ "def", "delete", "(", "self", ",", "num_name", ")", ":", "try", ":", "vg", "=", "self", ".", "attach", "(", "num_name", ",", "1", ")", "except", "HDF4Error", "as", "msg", ":", "raise", "HDF4Error", "(", "\"delete: no such vgroup\"", ")", "# ATTENTION: The HDF documentation says that the vgroup_id", "# is passed to Vdelete(). This is wrong.", "# The vgroup reference number must instead be passed.", "refnum", "=", "vg", ".", "_refnum", "vg", ".", "detach", "(", ")", "_checkErr", "(", "'delete'", ",", "_C", ".", "Vdelete", "(", "self", ".", "_hdf_inst", ".", "_id", ",", "refnum", ")", ",", "\"error deleting vgroup\"", ")" ]
Delete from the HDF file the vgroup identified by its reference number or its name. Args:: num_name either the reference number or the name of the vgroup to delete Returns:: None C library equivalent : Vdelete
[ "Delete", "from", "the", "HDF", "file", "the", "vgroup", "identified", "by", "its", "reference", "number", "or", "its", "name", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L822-L849
4,495
fhs/pyhdf
pyhdf/V.py
V.getid
def getid(self, ref): """Obtain the reference number of the vgroup following the vgroup with the given reference number . Args:: ref reference number of the vgroup after which to search; set to -1 to start the search at the start of the HDF file Returns:: reference number of the vgroup past the one identified by 'ref' An exception is raised if the end of the vgroup is reached. C library equivalent : Vgetid """ num = _C.Vgetid(self._hdf_inst._id, ref) _checkErr('getid', num, "bad arguments or last vgroup reached") return num
python
def getid(self, ref): """Obtain the reference number of the vgroup following the vgroup with the given reference number . Args:: ref reference number of the vgroup after which to search; set to -1 to start the search at the start of the HDF file Returns:: reference number of the vgroup past the one identified by 'ref' An exception is raised if the end of the vgroup is reached. C library equivalent : Vgetid """ num = _C.Vgetid(self._hdf_inst._id, ref) _checkErr('getid', num, "bad arguments or last vgroup reached") return num
[ "def", "getid", "(", "self", ",", "ref", ")", ":", "num", "=", "_C", ".", "Vgetid", "(", "self", ".", "_hdf_inst", ".", "_id", ",", "ref", ")", "_checkErr", "(", "'getid'", ",", "num", ",", "\"bad arguments or last vgroup reached\"", ")", "return", "num" ]
Obtain the reference number of the vgroup following the vgroup with the given reference number . Args:: ref reference number of the vgroup after which to search; set to -1 to start the search at the start of the HDF file Returns:: reference number of the vgroup past the one identified by 'ref' An exception is raised if the end of the vgroup is reached. C library equivalent : Vgetid
[ "Obtain", "the", "reference", "number", "of", "the", "vgroup", "following", "the", "vgroup", "with", "the", "given", "reference", "number", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L851-L872
4,496
fhs/pyhdf
pyhdf/V.py
VG.insert
def insert(self, inst): """Insert a vdata or a vgroup in the vgroup. Args:: inst vdata or vgroup instance to add Returns:: index of the inserted vdata or vgroup (0 based) C library equivalent : Vinsert """ if isinstance(inst, VD): id = inst._id elif isinstance(inst, VG): id = inst._id else: raise HDF4Error("insrt: bad argument") index = _C.Vinsert(self._id, id) _checkErr('insert', index, "cannot insert in vgroup") return index
python
def insert(self, inst): """Insert a vdata or a vgroup in the vgroup. Args:: inst vdata or vgroup instance to add Returns:: index of the inserted vdata or vgroup (0 based) C library equivalent : Vinsert """ if isinstance(inst, VD): id = inst._id elif isinstance(inst, VG): id = inst._id else: raise HDF4Error("insrt: bad argument") index = _C.Vinsert(self._id, id) _checkErr('insert', index, "cannot insert in vgroup") return index
[ "def", "insert", "(", "self", ",", "inst", ")", ":", "if", "isinstance", "(", "inst", ",", "VD", ")", ":", "id", "=", "inst", ".", "_id", "elif", "isinstance", "(", "inst", ",", "VG", ")", ":", "id", "=", "inst", ".", "_id", "else", ":", "raise", "HDF4Error", "(", "\"insrt: bad argument\"", ")", "index", "=", "_C", ".", "Vinsert", "(", "self", ".", "_id", ",", "id", ")", "_checkErr", "(", "'insert'", ",", "index", ",", "\"cannot insert in vgroup\"", ")", "return", "index" ]
Insert a vdata or a vgroup in the vgroup. Args:: inst vdata or vgroup instance to add Returns:: index of the inserted vdata or vgroup (0 based) C library equivalent : Vinsert
[ "Insert", "a", "vdata", "or", "a", "vgroup", "in", "the", "vgroup", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L994-L1017
4,497
fhs/pyhdf
pyhdf/V.py
VG.add
def add(self, tag, ref): """Add to the vgroup an object identified by its tag and reference number. Args:: tag tag of the object to add ref reference number of the object to add Returns:: total number of objects in the vgroup after the addition C library equivalent : Vaddtagref """ n = _C.Vaddtagref(self._id, tag, ref) _checkErr('addtagref', n, 'invalid arguments') return n
python
def add(self, tag, ref): """Add to the vgroup an object identified by its tag and reference number. Args:: tag tag of the object to add ref reference number of the object to add Returns:: total number of objects in the vgroup after the addition C library equivalent : Vaddtagref """ n = _C.Vaddtagref(self._id, tag, ref) _checkErr('addtagref', n, 'invalid arguments') return n
[ "def", "add", "(", "self", ",", "tag", ",", "ref", ")", ":", "n", "=", "_C", ".", "Vaddtagref", "(", "self", ".", "_id", ",", "tag", ",", "ref", ")", "_checkErr", "(", "'addtagref'", ",", "n", ",", "'invalid arguments'", ")", "return", "n" ]
Add to the vgroup an object identified by its tag and reference number. Args:: tag tag of the object to add ref reference number of the object to add Returns:: total number of objects in the vgroup after the addition C library equivalent : Vaddtagref
[ "Add", "to", "the", "vgroup", "an", "object", "identified", "by", "its", "tag", "and", "reference", "number", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L1019-L1037
4,498
fhs/pyhdf
pyhdf/V.py
VG.delete
def delete(self, tag, ref): """Delete from the vgroup the member identified by its tag and reference number. Args:: tag tag of the member to delete ref reference number of the member to delete Returns:: None Only the link of the member with the vgroup is deleted. The member object is not deleted. C library equivalent : Vdeletatagref """ _checkErr('delete', _C.Vdeletetagref(self._id, tag, ref), "error deleting member")
python
def delete(self, tag, ref): """Delete from the vgroup the member identified by its tag and reference number. Args:: tag tag of the member to delete ref reference number of the member to delete Returns:: None Only the link of the member with the vgroup is deleted. The member object is not deleted. C library equivalent : Vdeletatagref """ _checkErr('delete', _C.Vdeletetagref(self._id, tag, ref), "error deleting member")
[ "def", "delete", "(", "self", ",", "tag", ",", "ref", ")", ":", "_checkErr", "(", "'delete'", ",", "_C", ".", "Vdeletetagref", "(", "self", ".", "_id", ",", "tag", ",", "ref", ")", ",", "\"error deleting member\"", ")" ]
Delete from the vgroup the member identified by its tag and reference number. Args:: tag tag of the member to delete ref reference number of the member to delete Returns:: None Only the link of the member with the vgroup is deleted. The member object is not deleted. C library equivalent : Vdeletatagref
[ "Delete", "from", "the", "vgroup", "the", "member", "identified", "by", "its", "tag", "and", "reference", "number", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L1039-L1059
4,499
fhs/pyhdf
pyhdf/V.py
VG.tagref
def tagref(self, index): """Get the tag and reference number of a vgroup member, given the index number of that member. Args:: index member index (0 based) Returns:: 2-element tuple: - member tag - member reference number C library equivalent : Vgettagref """ status, tag, ref = _C.Vgettagref(self._id, index) _checkErr('tagref', status, "illegal arguments") return tag, ref
python
def tagref(self, index): """Get the tag and reference number of a vgroup member, given the index number of that member. Args:: index member index (0 based) Returns:: 2-element tuple: - member tag - member reference number C library equivalent : Vgettagref """ status, tag, ref = _C.Vgettagref(self._id, index) _checkErr('tagref', status, "illegal arguments") return tag, ref
[ "def", "tagref", "(", "self", ",", "index", ")", ":", "status", ",", "tag", ",", "ref", "=", "_C", ".", "Vgettagref", "(", "self", ".", "_id", ",", "index", ")", "_checkErr", "(", "'tagref'", ",", "status", ",", "\"illegal arguments\"", ")", "return", "tag", ",", "ref" ]
Get the tag and reference number of a vgroup member, given the index number of that member. Args:: index member index (0 based) Returns:: 2-element tuple: - member tag - member reference number C library equivalent : Vgettagref
[ "Get", "the", "tag", "and", "reference", "number", "of", "a", "vgroup", "member", "given", "the", "index", "number", "of", "that", "member", "." ]
dbdc1810a74a38df50dcad81fe903e239d2b388d
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L1079-L1098