INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
strip ( 1 byte ) radiotap. db_antsignal: return: int idx: return: int | def strip_db_antsignal(self, idx):
"""strip(1 byte) radiotap.db_antsignal
:return: int
idx
:return: int
"""
db_antsignal, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, db_antsignal |
strip ( 1 byte ) radiotap. db_antnoise: return: int idx: return: int | def strip_db_antnoise(self, idx):
"""strip(1 byte) radiotap.db_antnoise
:return: int
idx
:return: int
"""
db_antnoise, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, db_antnoise |
strip ( 2 byte ) radiotap. rxflags: idx: int: return: int idx: return: collections. namedtuple | def strip_rx_flags(self, idx):
"""strip(2 byte) radiotap.rxflags
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
rx_flags = collections.namedtuple('rx_flags', ['reserved', 'badplcp'])
idx = Radiotap.align(idx, 2)
flags, = struct... |
strip ( 1 byte ) tx_flags: idx: int: return: int idx: return: int | def strip_tx_flags(self, idx):
"""strip(1 byte) tx_flags
:idx: int
:return: int
idx
:return: int
"""
idx = Radiotap.align(idx, 2)
tx_flags, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, tx_flags |
strip ( 1 byte ) rts_retries: idx: int: return: int idx: return: int | def strip_rts_retries(self, idx):
"""strip(1 byte) rts_retries
:idx: int
:return: int
idx
:return: int
"""
rts_retries, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, rts_retries |
strip ( 1 byte ) data_retries: idx: int: return: int idx: return: int | def strip_data_retries(self, idx):
"""strip(1 byte) data_retries
:idx: int
:return: int
idx
:return: int
"""
data_retries, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, data_retries |
strip ( 7 bytes ) radiotap. xchannel. channel ( 1 byte ) radiotap. xchannel. freq ( 2 bytes ) and radiotap. xchannel. flags ( 4 bytes ): idx: int: return: int idx: return: collections. namedtuple | def strip_xchannel(self, idx):
"""strip(7 bytes) radiotap.xchannel.channel(1 byte),
radiotap.xchannel.freq(2 bytes) and radiotap.xchannel.flags(4 bytes)
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
xchannel = collections.namedtuple(
... |
strip ( 3 byte ) radiotap. mcs which contains 802. 11n bandwidth mcs ( modulation and coding scheme ) and stbc ( space time block coding ) information.: idx: int: return: int idx: return: collections. namedtuple | def strip_mcs(self, idx):
"""strip(3 byte) radiotap.mcs which contains 802.11n bandwidth,
mcs(modulation and coding scheme) and stbc(space time block coding)
information.
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
mcs = coll... |
strip ( 8 byte ) radiotap. ampdu: idx: int: return: int idx: return: collections. namedtuple | def strip_ampdu(self, idx):
"""strip(8 byte) radiotap.ampdu
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
ampdu = collections.namedtuple(
'ampdu', ['reference', 'crc_val', 'reservered', 'flags'])
flags = collections.namedtu... |
strip ( 12 byte ) radiotap. vht: idx: int: return: int idx: return: collections. namedtuple | def strip_vht(self, idx):
"""strip(12 byte) radiotap.vht
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
vht = collections.namedtuple(
'vht', ['known_bits', 'have_stbc', 'have_txop_ps', 'have_gi',
'have_sgi_nsym_d... |
extract 802. 11 protocol from radiotap. channel. flags: return: str protocol name one of below in success [. 11a. 11b. 11g. 11n. 11ac ] None in fail | def extract_protocol(self):
"""extract 802.11 protocol from radiotap.channel.flags
:return: str
protocol name
one of below in success
[.11a, .11b, .11g, .11n, .11ac]
None in fail
"""
if self.present.mcs:
return '.11n'
i... |
get parameters via wireshark syntax. out = x. get_shark_field ( wlan. fc. type ) out = x. get_shark_field ( [ wlan. fc. type wlan. seq ] ): fields: str or str []: return: dict out [ fields [ 0 ]] = val [ 0 ] or None out [ fields [ 1 ]] = val [ 1 ] or None... | def get_shark_field(self, fields):
"""get parameters via wireshark syntax.
out = x.get_shark_field('wlan.fc.type')
out = x.get_shark_field(['wlan.fc.type', 'wlan.seq'])
:fields: str or str[]
:return: dict
out[fields[0]] = val[0] or None
out[fields[1]] = va... |
converts bytes to mac addr format: mac_addr: ctypes. structure: return: str mac addr in format 11: 22: 33: aa: bb: cc | def get_mac_addr(mac_addr):
"""converts bytes to mac addr format
:mac_addr: ctypes.structure
:return: str
mac addr in format
11:22:33:aa:bb:cc
"""
mac_addr = bytearray(mac_addr)
mac = b':'.join([('%02x' % o).encode('ascii') for o in mac_addr])
... |
strip mac address ( each 6 byte ) information. ( wlan. ta wlan. ra wlan. sa wlan. da ) ( transmitter receiver source destination ): return: int index of sequence control: return: int index after mac addresses: return: str source address ( sa ): return: str transmitter address ( ta ): return: str receiver address ( ra )... | def strip_mac_addrs(self):
"""strip mac address(each 6 byte) information.
(wlan.ta, wlan.ra, wlan.sa, wlan.da)
(transmitter, receiver, source, destination)
:return: int
index of sequence control
:return: int
index after mac addresses
:return: str
... |
strip ( 2 byte ) wlan. seq ( 12 bit ) and wlan. fram ( 4 bit ) number information.: seq_cntrl: ctypes. Structure: return: int sequence number: return: int fragment number | def strip_seq_cntrl(self, idx):
"""strip(2 byte) wlan.seq(12 bit) and wlan.fram(4 bit)
number information.
:seq_cntrl: ctypes.Structure
:return: int
sequence number
:return: int
fragment number
"""
seq_cntrl = struct.unpack('H', self._packe... |
strip ( 2 byte ) wlan. qos: idx: int: prot_type: string 802. 11 protocol type (. 11ac. 11a. 11n etc ): return: int number of processed bytes: return: int qos priority: return: int qos bit: return: int qos acknowledgement: return: int amsdupresent ( aggregated mac service data unit ) | def strip_qos_cntrl(self, idx, prot_type):
"""strip(2 byte) wlan.qos
:idx: int
:prot_type: string
802.11 protocol type(.11ac, .11a, .11n, etc)
:return: int
number of processed bytes
:return: int
qos priority
:return: int
qos... |
strip ( 8 byte ) wlan. ccmp. extiv CCMP Extended Initialization Vector: return: int number of processed bytes: return: ctypes. raw ccmp vector | def strip_ccmp(self, idx):
"""strip(8 byte) wlan.ccmp.extiv
CCMP Extended Initialization Vector
:return: int
number of processed bytes
:return: ctypes.raw
ccmp vector
"""
ccmp_extiv = None
if len(self._packet[idx:]) >= 8:
raw_by... |
strip single mac servis data unit ( msdu ) see - > https:// mrncciew. com/ 2014/ 11/ 01/ cwap - 802 - 11 - data - frame - aggregation/: idx: int: return: dict msdu: return: int number of processed bytes | def strip_msdu(self, idx):
"""strip single mac servis data unit(msdu)
see -> https://mrncciew.com/2014/11/01/cwap-802-11-data-frame-aggregation/
:idx: int
:return: dict
msdu
:return: int
number of processed bytes
"""
# length of msdu payloa... |
strip ( 4 or 8 byte ) logical link control headers: return: int number of processed bytes: return: dict llc information see - > http:// www. wildpackets. com/ resources/ compendium/ ethernet/ frame_snap_iee8023 ABBRVS. ssap: source service access point dsap: destination service access point SNAP ( Subnetwork Acess Prot... | def strip_llc(self, idx):
"""strip(4 or 8 byte) logical link control headers
:return: int
number of processed bytes
:return: dict
llc information
see -> http://www.wildpackets.com/resources/compendium/ethernet/frame_snap_iee8023
ABBRVS.
ssap: sourc... |
strip tagged information elements wlan_mgt. tag which has generic type - length - value structure [ type length value ] type ( 1 byte ) length ( 1 byte ) value ( varies ) [ wlan_mgt. tag. number wlan_mgt. tag. length payload ] structured fields.: return: dict [] list of tagged params: return: int 0 in succ 1 for | def parse_tagged_params(raw_tagged_params):
"""strip tagged information elements wlan_mgt.tag
which has generic type-length-value structure
[type, length, value]
type(1 byte), length(1 byte), value(varies)
[wlan_mgt.tag.number, wlan_mgt.tag.length, payload]
structured fie... |
strip ( 2 byte ) wlan_mgt. fixed. capabilities: payload: ctypes. structure 2 byte: return: dict None in error | def get_fixed_capabils(payload):
"""strip(2 byte) wlan_mgt.fixed.capabilities
:payload: ctypes.structure
2 byte
:return: dict
None in error
"""
if len(payload) != 2:
return None
capabils = {}
fix_cap = struct.unpack('H', payload... |
parse vendor specific information element oui - > organizationally unique identifier first 3 bytes of mac addresses see: https:// www. wireshark. org/ tools/ oui - lookup. html strip wlan_mgt. tag. oui ( 3 bytes ) wlan_mgt. tag. vendor. oui. type ( 1 byte ) wlan_mgt. tag. vendor. data ( varies ): payload: ctypes. struc... | def parse_vendor_ie(payload):
"""parse vendor specific information element
oui -> organizationally unique identifier
first 3 bytes of mac addresses
see:https://www.wireshark.org/tools/oui-lookup.html
strip wlan_mgt.tag.oui(3 bytes),
wlan_mgt.tag.vendor.oui.type(1 byte)
... |
strip ( 12 byte ) wlan_mgt. fixed. all: payload: ctypes. structure: return: int timestamp: return: int beacon interval: return: dict capabilities | def strip_fixed_params(payload):
"""strip(12 byte) wlan_mgt.fixed.all
:payload: ctypes.structure
:return: int
timestamp
:return: int
beacon interval
:return: dict
capabilities
"""
if len(payload) != 12:
return None, ... |
checks whether mac block is in format of 00 - 11 - 22 or 00: 11: 22.: return: int | def is_valid_mac_oui(mac_block):
"""checks whether mac block is in format of
00-11-22 or 00:11:22.
:return: int
"""
if len(mac_block) != 8:
return 0
if ':' in mac_block:
if len(mac_block.split(':')) != 3:
return 0
elif '-' i... |
set keys of capabils into fields of object: capabils: dict | def set_fixed_capabils(self, capabils):
"""set keys of capabils into fields of object
:capabils: dict
"""
self.ess = capabils['ess']
self.ibss = capabils['ibss']
self.priv = capabils['priv']
self.short_preamble = capabils['short_preamble']
self.pbcc = capa... |
vendor information element querying: mac_block: str first 3 bytes of mac addresses in format of 00 - 11 - 22 or 00: 11: 22 or 001122: oui_type: int vendors ie type: return: int is valid mac_block format - 1 is unknown: return: dict [] list of oui information elements - 1 on error ( invalid v | def get_vendor_ies(self, mac_block=None, oui_type=None):
"""vendor information element querying
:mac_block: str
first 3 bytes of mac addresses in format of
00-11-22 or 00:11:22 or 001122
:oui_type: int
vendors ie type
:return: int
is valid ... |
: fields: str [] | def get_shark_field(self, fields):
"""
:fields: str[]
"""
out = super(BACK, self).get_shark_field(fields)
out.update({'acked_seqs': self.acked_seqs,
'bitmap_str': self.bitmap_str})
return out |
strip ( 2 byte ) wlan. ba. control: payload: ctypes. structure: return: int multitid ( tid: traffic indicator ): return: int ackpolicy | def strip_cntrl(payload):
"""strip(2 byte) wlan.ba.control
:payload: ctypes.structure
:return: int
multitid (tid: traffic indicator)
:return: int
ackpolicy
"""
cntrl = struct.unpack('H', payload)[0]
cntrl_bits = format(cntrl, '016b')[::-1]
... |
strip ( 2 byte ) wlan_mgt. fixed. ssc: payload: ctypes. structure: return: int ssc_seq ( starting sequence control sequence ): return: int ssc_frag ( starting sequence control fragment number ) | def strip_ssc(payload):
"""strip(2 byte) wlan_mgt.fixed.ssc
:payload: ctypes.structure
:return: int
ssc_seq (starting sequence control sequence)
:return: int
ssc_frag (starting sequence control fragment number)
"""
ssc = struct.unpack('H', payload)... |
strip ( 8 byte ) wlan. ba. bm: payload: ctypes. structure: return: str bitmap | def strip_bitmap_str(payload):
"""strip(8 byte) wlan.ba.bm
:payload: ctypes.structure
:return: str
bitmap
"""
bitmap = struct.unpack('BBBBBBBB', payload)
bitmap_str = ''
for elem in bitmap:
bitmap_str += format(elem, '08b')[::-1]
re... |
extracts acknowledged sequences from bitmap and starting sequence number.: bitmap: str: ssc_seq: int: return: int [] acknowledged sequence numbers | def extract_acked_seqs(bitmap, ssc_seq):
"""extracts acknowledged sequences from bitmap and
starting sequence number.
:bitmap: str
:ssc_seq: int
:return: int[]
acknowledged sequence numbers
"""
acked_seqs = []
for idx, val in enumerate(bitmap):... |
Call Heartbeat URL | def heartbeat():
"""Call Heartbeat URL"""
print "We got a call heartbeat notification\n"
if request.method == 'POST':
print request.form
else:
print request.args
return "OK" |
sends a request and gets a response from the Plivo REST API | def request(self, path, method=None, data={}):
"""sends a request and gets a response from the Plivo REST API
path: the URL (relative to the endpoint URL, after the /v1
method: the HTTP method to use, defaults to POST
data: for POST or PUT, a dict of data to send
returns Plivo ... |
REST Reload Plivo Config helper | def reload_config(self, call_params):
"""REST Reload Plivo Config helper
"""
path = '/' + self.api_version + '/ReloadConfig/'
method = 'POST'
return self.request(path, method, call_params) |
REST Reload Plivo Cache Config helper | def reload_cache_config(self, call_params):
"""REST Reload Plivo Cache Config helper
"""
path = '/' + self.api_version + '/ReloadCacheConfig/'
method = 'POST'
return self.request(path, method, call_params) |
REST Call Helper | def call(self, call_params):
"""REST Call Helper
"""
path = '/' + self.api_version + '/Call/'
method = 'POST'
return self.request(path, method, call_params) |
REST BulkCalls Helper | def bulk_call(self, call_params):
"""REST BulkCalls Helper
"""
path = '/' + self.api_version + '/BulkCall/'
method = 'POST'
return self.request(path, method, call_params) |
REST GroupCalls Helper | def group_call(self, call_params):
"""REST GroupCalls Helper
"""
path = '/' + self.api_version + '/GroupCall/'
method = 'POST'
return self.request(path, method, call_params) |
REST Transfer Live Call Helper | def transfer_call(self, call_params):
"""REST Transfer Live Call Helper
"""
path = '/' + self.api_version + '/TransferCall/'
method = 'POST'
return self.request(path, method, call_params) |
REST Hangup All Live Calls Helper | def hangup_all_calls(self):
"""REST Hangup All Live Calls Helper
"""
path = '/' + self.api_version + '/HangupAllCalls/'
method = 'POST'
return self.request(path, method) |
REST Hangup Live Call Helper | def hangup_call(self, call_params):
"""REST Hangup Live Call Helper
"""
path = '/' + self.api_version + '/HangupCall/'
method = 'POST'
return self.request(path, method, call_params) |
REST Schedule Hangup Helper | def schedule_hangup(self, call_params):
"""REST Schedule Hangup Helper
"""
path = '/' + self.api_version + '/ScheduleHangup/'
method = 'POST'
return self.request(path, method, call_params) |
REST Cancel a Scheduled Hangup Helper | def cancel_scheduled_hangup(self, call_params):
"""REST Cancel a Scheduled Hangup Helper
"""
path = '/' + self.api_version + '/CancelScheduledHangup/'
method = 'POST'
return self.request(path, method, call_params) |
REST RecordStart helper | def record_start(self, call_params):
"""REST RecordStart helper
"""
path = '/' + self.api_version + '/RecordStart/'
method = 'POST'
return self.request(path, method, call_params) |
REST RecordStop | def record_stop(self, call_params):
"""REST RecordStop
"""
path = '/' + self.api_version + '/RecordStop/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference Mute helper | def conference_mute(self, call_params):
"""REST Conference Mute helper
"""
path = '/' + self.api_version + '/ConferenceMute/'
method = 'POST'
return self.request(path, method, call_params) |
REST Play something on a Call Helper | def play(self, call_params):
"""REST Play something on a Call Helper
"""
path = '/' + self.api_version + '/Play/'
method = 'POST'
return self.request(path, method, call_params) |
REST PlayStop on a Call Helper | def play_stop(self, call_params):
"""REST PlayStop on a Call Helper
"""
path = '/' + self.api_version + '/PlayStop/'
method = 'POST'
return self.request(path, method, call_params) |
REST Schedule playing something on a call Helper | def schedule_play(self, call_params):
"""REST Schedule playing something on a call Helper
"""
path = '/' + self.api_version + '/SchedulePlay/'
method = 'POST'
return self.request(path, method, call_params) |
REST Cancel a Scheduled Play Helper | def cancel_scheduled_play(self, call_params):
"""REST Cancel a Scheduled Play Helper
"""
path = '/' + self.api_version + '/CancelScheduledPlay/'
method = 'POST'
return self.request(path, method, call_params) |
REST Add soundtouch audio effects to a Call | def sound_touch(self, call_params):
"""REST Add soundtouch audio effects to a Call
"""
path = '/' + self.api_version + '/SoundTouch/'
method = 'POST'
return self.request(path, method, call_params) |
REST Remove soundtouch audio effects on a Call | def sound_touch_stop(self, call_params):
"""REST Remove soundtouch audio effects on a Call
"""
path = '/' + self.api_version + '/SoundTouchStop/'
method = 'POST'
return self.request(path, method, call_params) |
REST Send digits to a Call | def send_digits(self, call_params):
"""REST Send digits to a Call
"""
path = '/' + self.api_version + '/SendDigits/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference Unmute helper | def conference_unmute(self, call_params):
"""REST Conference Unmute helper
"""
path = '/' + self.api_version + '/ConferenceUnmute/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference Kick helper | def conference_kick(self, call_params):
"""REST Conference Kick helper
"""
path = '/' + self.api_version + '/ConferenceKick/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference Hangup helper | def conference_hangup(self, call_params):
"""REST Conference Hangup helper
"""
path = '/' + self.api_version + '/ConferenceHangup/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference Deaf helper | def conference_deaf(self, call_params):
"""REST Conference Deaf helper
"""
path = '/' + self.api_version + '/ConferenceDeaf/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference Undeaf helper | def conference_undeaf(self, call_params):
"""REST Conference Undeaf helper
"""
path = '/' + self.api_version + '/ConferenceUndeaf/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference RecordStart helper | def conference_record_start(self, call_params):
"""REST Conference RecordStart helper
"""
path = '/' + self.api_version + '/ConferenceRecordStart/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference RecordStop | def conference_record_stop(self, call_params):
"""REST Conference RecordStop
"""
path = '/' + self.api_version + '/ConferenceRecordStop/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference Play helper | def conference_play(self, call_params):
"""REST Conference Play helper
"""
path = '/' + self.api_version + '/ConferencePlay/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference Speak helper | def conference_speak(self, call_params):
"""REST Conference Speak helper
"""
path = '/' + self.api_version + '/ConferenceSpeak/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference List Helper | def conference_list(self, call_params):
"""REST Conference List Helper
"""
path = '/' + self.api_version + '/ConferenceList/'
method = 'POST'
return self.request(path, method, call_params) |
REST Conference List Members Helper | def conference_list_members(self, call_params):
"""REST Conference List Members Helper
"""
path = '/' + self.api_version + '/ConferenceListMembers/'
method = 'POST'
return self.request(path, method, call_params) |
Return an XML element representing this element | def _xml(self, root):
"""
Return an XML element representing this element
"""
element = root.createElement(self.name)
# Add attributes
keys = self.attrs.keys()
keys.sort()
for a in keys:
element.setAttribute(a, self.attrs[a])
if self.... |
validate a request from plivo | def validateRequest(self, uri, postVars, expectedSignature):
"""validate a request from plivo
uri: the full URI that Plivo requested on your server
postVars: post vars that Plivo sent with the request
expectedSignature: signature in HTTP X-Plivo-Signature header
returns true if... |
Depth - first search. | def DFS_prefix(self, root=None):
"""
Depth-first search.
.. seealso::
`Wikipedia DFS descritpion <http://en.wikipedia.org/wiki/Depth-first_search>`_
:param root: first to start the search
:return: list of nodes
"""
if not root:
root = sel... |
Breadth - first search. | def BFS(self, root=None):
"""
Breadth-first search.
.. seealso::
`Wikipedia BFS descritpion <http://en.wikipedia.org/wiki/Breadth-first_search>`_
:param root: first to start the search
:return: list of nodes
"""
if not root:
root = self... |
Return a node with label. Create node if label is new | def add_node(self,label):
'''Return a node with label. Create node if label is new'''
try:
n = self._nodes[label]
except KeyError:
n = Node()
n['label'] = label
self._nodes[label]=n
return n |
Get or create edges using get_or_create_node | def add_edge(self, n1_label, n2_label,directed=False):
"""
Get or create edges using get_or_create_node
"""
n1 = self.add_node(n1_label)
n2 = self.add_node(n2_label)
e = Edge(n1, n2, directed)
self._edges.append(e)
return e |
Parse dom into a Graph. | def parse_dom(dom):
"""Parse dom into a Graph.
:param dom: dom as returned by minidom.parse or minidom.parseString
:return: A Graph representation
"""
root = dom.getElementsByTagName("graphml")[0]
graph = root.getElementsByTagName("graph")[0]
name = graph.getAttr... |
Parse a string into a Graph. | def parse_string(self, string):
"""Parse a string into a Graph.
:param string: String that is to be passed into Grapg
:return: Graph
"""
dom = minidom.parseString(string)
return self.parse_dom(dom) |
Return the other node | def node(self, node):
"""
Return the other node
"""
if node == self.node1:
return self.node2
elif node == self.node2:
return self.node1
else:
return None |
Return a generator that yields whenever a message is waiting in the queue. Will block otherwise. Example: >>> for msg in queue. consume ( timeout = 1 ):... print msg my message another message: param kwargs: any arguments that: meth: ~hotqueue. HotQueue. get can accept (: attr: block will default to True if not given ) | def consume(self, **kwargs):
"""Return a generator that yields whenever a message is waiting in the
queue. Will block otherwise. Example:
>>> for msg in queue.consume(timeout=1):
... print msg
my message
another message
:param kwargs: any arg... |
Return a message from the queue. Example: >>> queue. get () my message >>> queue. get () another message: param block: whether or not to wait until a msg is available in the queue before returning ; False by default: param timeout: when using: attr: block if no msg is available for: attr: timeout in seconds give up and... | def get(self, block=False, timeout=None):
"""Return a message from the queue. Example:
>>> queue.get()
'my message'
>>> queue.get()
'another message'
:param block: whether or not to wait until a msg is available in
the queue before returning; ``F... |
Put one or more messages onto the queue. Example: >>> queue. put ( my message ) >>> queue. put ( another message ) To put messages onto the queue in bulk which can be significantly faster if you have a large number of messages: >>> queue. put ( my message another message third message ) | def put(self, *msgs):
"""Put one or more messages onto the queue. Example:
>>> queue.put("my message")
>>> queue.put("another message")
To put messages onto the queue in bulk, which can be significantly
faster if you have a large number of messages:
... |
Decorator for using a function as a queue worker. Example: >>> | def worker(self, *args, **kwargs):
"""Decorator for using a function as a queue worker. Example:
>>> @queue.worker(timeout=1)
... def printer(msg):
... print msg
>>> printer()
my message
another message
You can also use it without pas... |
Factory for creating the argument parser | def _arg_parser():
"""Factory for creating the argument parser"""
description = "Converts a completezip to a litezip"
parser = argparse.ArgumentParser(description=description)
verbose_group = parser.add_mutually_exclusive_group()
verbose_group.add_argument(
'-v', '--verbose', action='store_t... |
Complex code ahead. Comments have been added in as needed. | def to_bytes(self, previous: bytes):
"""
Complex code ahead. Comments have been added in as needed.
"""
# First, validate the lengths.
if len(self.conditions) != len(self.body):
raise exc.CompileError("Conditions and body length mismatch!")
bc = b""
... |
A to - bytes specific to Python 3. 5 and below. | def to_bytes_35(self, previous: bytes):
"""
A to-bytes specific to Python 3.5 and below.
"""
# Calculations ahead.
bc = b""
# Calculate the length of the iterator.
it_bc = util.generate_bytecode_from_obb(self.iterator, previous)
bc += it_bc
# Pu... |
A to - bytes specific to Python 3. 6 and above. | def to_bytes_36(self, previous: bytes):
"""
A to-bytes specific to Python 3.6 and above.
"""
# Calculations ahead.
bc = b""
# Calculate the length of the iterator.
it_bc = util.generate_bytecode_from_obb(self.iterator, previous)
bc += it_bc
bc +=... |
Runs the correct validator for given obj ects. Assumes all same type | def validate_content(*objs):
"""Runs the correct validator for given `obj`ects. Assumes all same type"""
from .main import Collection, Module
validator = {
Collection: cnxml.validate_collxml,
Module: cnxml.validate_cnxml,
}[type(objs[0])]
return validator(*[obj.file for obj in objs]) |
Validate the given litezip as struct. Returns a list of validation messages. | def validate_litezip(struct):
"""Validate the given litezip as `struct`.
Returns a list of validation messages.
"""
msgs = []
def _fmt_err(err):
return (Path(err.filename), "{}:{} -- {}: {}".format(*(err[1:])))
obj_by_type = {}
for obj in struct:
if not is_valid_identifier... |
Wraps an instruction to be Python 3. 6 + compatible. This does nothing on Python 3. 5 and below. | def ensure_instruction(instruction: int) -> bytes:
"""
Wraps an instruction to be Python 3.6+ compatible. This does nothing on Python 3.5 and below.
This is most useful for operating on bare, single-width instructions such as
``RETURN_FUNCTION`` in a version portable way.
:param instruction: The i... |
Small helper value to pack an index value into bytecode. | def pack_value(index: int) -> bytes:
"""
Small helper value to pack an index value into bytecode.
This is used for version compat between 3.5- and 3.6+
:param index: The item to pack.
:return: The packed item.
"""
if PY36:
return index.to_bytes(1, byteorder="little")
else:
... |
Generates a simple call with an index for something. | def generate_simple_call(opcode: int, index: int):
"""
Generates a simple call, with an index for something.
:param opcode: The opcode to generate.
:param index: The index to use as an argument.
:return:
"""
bs = b""
# add the opcode
bs += opcode.to_bytes(1, byteorder="little")
... |
Generates a bytecode from an object. | def generate_bytecode_from_obb(obb: object, previous: bytes) -> bytes:
"""
Generates a bytecode from an object.
:param obb: The object to generate.
:param previous: The previous bytecode to use when generating subobjects.
:return: The generated bytecode.
"""
# Generates bytecode from a spec... |
Helper to get optional details about const references | def _get_const_info(const_index, const_list):
"""
Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is... |
Helper to get optional details about named references | def _get_name_info(name_index, name_list):
"""Helper to get optional details about named references
Returns the dereferenced name as both value and repr if the name
list is defined.
Otherwise returns the name index and its repr().
"""
argval = name_index
if name_list is not None:
... |
Add arguments described in the usage string to the parser. View more details at the <create_parser > docs | def add_to_parser(parser, usage, ignore_existing=False):
"""
Add arguments described in the usage string to the
parser. View more details at the <create_parser> docs
Args:
parser (ArgumentParser): parser to add arguments to
usage (str): Usage string in the format described above
... |
Compiles Pyte objects into a bytecode list. | def compile_bytecode(code: list) -> bytes:
"""
Compiles Pyte objects into a bytecode list.
:param code: A list of objects to compile.
:return: The computed bytecode.
"""
bc = b""
for i, op in enumerate(code):
try:
# Get the bytecode.
if isinstance(op, _PyteOp... |
Simulates the actions of the stack to check safety. | def _simulate_stack(code: list) -> int:
"""
Simulates the actions of the stack, to check safety.
This returns the maximum needed stack.
"""
max_stack = 0
curr_stack = 0
def _check_stack(ins):
if curr_stack < 0:
raise CompileError("Stack turned negative on instruction: ... |
Compiles a set of bytecode instructions into a working function using Python s bytecode compiler. | def compile(code: list, consts: list, names: list, varnames: list,
func_name: str = "<unknown, compiled>",
arg_count: int = 0, kwarg_defaults: Tuple[Any] = (), use_safety_wrapper: bool = True):
"""
Compiles a set of bytecode instructions into a working function, using Python's bytecode
... |
Given the parsed xml to an ElementTree parse the id from the content. | def _parse_document_id(elm_tree):
"""Given the parsed xml to an `ElementTree`,
parse the id from the content.
"""
xpath = '//md:content-id/text()'
return [x for x in elm_tree.xpath(xpath, namespaces=COLLECTION_NSMAP)][0] |
Return a list of resource paths from the directory. Ignore records via the list of excludes which are callables that take a file parameter ( as a Path instance ). | def _find_resources(directory, excludes=[]):
"""Return a list of resource paths from the directory.
Ignore records via the list of `excludes`,
which are callables that take a file parameter (as a `Path` instance).
"""
return sorted([r for r in directory.glob('*')
if True not in [... |
Parse the file structure to a data structure given the path to a module directory. | def parse_module(path, excludes=None):
"""Parse the file structure to a data structure given the path to
a module directory.
"""
file = path / MODULE_FILENAME
if not file.exists():
raise MissingFile(file)
id = _parse_document_id(etree.parse(file.open()))
excludes = excludes or []
... |
Parse a file structure to a data structure given the path to a collection directory. | def parse_collection(path, excludes=None):
"""Parse a file structure to a data structure given the path to
a collection directory.
"""
file = path / COLLECTION_FILENAME
if not file.exists():
raise MissingFile(file)
id = _parse_document_id(etree.parse(file.open()))
excludes = exclud... |
Parse a litezip file structure to a data structure given the path to the litezip directory. | def parse_litezip(path):
"""Parse a litezip file structure to a data structure given the path
to the litezip directory.
"""
struct = [parse_collection(path)]
struct.extend([parse_module(x) for x in path.iterdir()
if x.is_dir() and x.name.startswith('m')])
return tuple(sorted(... |
Converts a completezip file structure to a litezip file structure. Returns a litezip data structure. | def convert_completezip(path):
"""Converts a completezip file structure to a litezip file structure.
Returns a litezip data structure.
"""
for filepath in path.glob('**/index_auto_generated.cnxml'):
filepath.rename(filepath.parent / 'index.cnxml')
logger.debug('removed {}'.format(filepa... |
Iterate over the instructions in a bytecode string. | def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
cells=None, linestarts=None, line_offset=0):
"""Iterate over the instructions in a bytecode string.
Generates a sequence of Instruction namedtuples giving the details of each
opcode. Additional informa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.