code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
deserialize 1 or more actions; return a list of
Action* objects
'''
actions = []
while len(raw) > 0:
atype, alen = struct.unpack('!HH', raw[:4])
atype = OpenflowActionType(atype)
action = _ActionClassMap.get(atype)()
action.from_bytes(raw[:alen])
raw ... | def _unpack_actions(raw) | deserialize 1 or more actions; return a list of
Action* objects | 5.127235 | 3.350036 | 1.530502 |
'''
Two match objects overlap if the same packet can be matched
by both *and* they have the same priority.
'''
one = self.matches_entry(othermatch, strict)
if strict:
return one
return one and othermatch.matches_entry(self, strict) | def overlaps_with(self, othermatch, strict=False) | Two match objects overlap if the same packet can be matched
by both *and* they have the same priority. | 8.74446 | 3.163367 | 2.764289 |
'''
Return True if this match object matches another
match object (e.g., a flow table entry).
NB: from OF 1.0 spec:
A match occurs "when a flow entry exactly matches
or is more specific than one" [in a flow_mod command]
(likely to be self in this case).
'... | def matches_entry(self, othermatch, strict=False) | Return True if this match object matches another
match object (e.g., a flow table entry).
NB: from OF 1.0 spec:
A match occurs "when a flow entry exactly matches
or is more specific than one" [in a flow_mod command]
(likely to be self in this case). | 5.781901 | 2.915611 | 1.983084 |
'''
Return True if the given packet matches this match object.
'''
match = []
wildbits = _make_bitmap(self._wildcards)
for mf,pkttuple in OpenflowMatch._match_field_to_packet.items():
mf = "_{}".format(mf)
# if the attribute is a network address, ... | def matches_packet(self, pkt) | Return True if the given packet matches this match object. | 6.500441 | 6.099946 | 1.065656 |
'''
Build and return a new OpenflowMatch object based on the
packet object passed as a parameter.
'''
m = OpenflowMatch()
for mf,pkttuple in OpenflowMatch._match_field_to_packet.items():
for pktcls,field in pkttuple:
if pkt.has_header(pktcls):
... | def build_from_packet(pkt) | Build and return a new OpenflowMatch object based on the
packet object passed as a parameter. | 6.593526 | 4.499193 | 1.465491 |
'''
Set length of the header based on
'''
self.length = len(raw) + OpenflowHeader._MINLEN | def pre_serialize(self, raw, pkt, i) | Set length of the header based on | 22.039124 | 10.037808 | 2.195611 |
'''
Find all the pcap-eligible devices on the local system.
'''
if len(self._interfaces):
raise PcapException("Device discovery should only be done once.")
ppintf = self._ffi.new("pcap_if_t * *")
errbuf = self._ffi.new("char []", 128)
rv =... | def discoverdevs(self) | Find all the pcap-eligible devices on the local system. | 4.211894 | 3.886114 | 1.083832 |
'''
Long method name, but self-explanatory. Set the bpf
filter on all devices that have been opened.
'''
with PcapLiveDevice._lock:
for dev in PcapLiveDevice._OpenDevices.values():
_PcapFfi.instance()._set_filter(dev, filterstr) | def set_bpf_filter_on_all_devices(filterstr) | Long method name, but self-explanatory. Set the bpf
filter on all devices that have been opened. | 13.77574 | 6.219001 | 2.215105 |
'''
Create an ARP reply (just change what needs to be changed
from a request)
'''
pkt = create_ip_arp_request(srchw, srcip, targetip)
pkt[0].dst = dsthw
pkt[1].operation = ArpOperation.Reply
pkt[1].targethwaddr = dsthw
return pkt | def create_ip_arp_reply(srchw, dsthw, srcip, targetip) | Create an ARP reply (just change what needs to be changed
from a request) | 7.26429 | 4.168006 | 1.742869 |
'''
Create and return a packet containing an Ethernet header
and ARP header.
'''
ether = Ethernet()
ether.src = srchw
ether.dst = SpecialEthAddr.ETHER_BROADCAST.value
ether.ethertype = EtherType.ARP
arp = Arp()
arp.operation = ArpOperation.Request
arp.senderhwaddr = srchw
... | def create_ip_arp_request(srchw, srcip, targetip) | Create and return a packet containing an Ethernet header
and ARP header. | 3.581733 | 2.81006 | 1.274611 |
'''
Setup logging format and log level.
'''
if debug:
level = logging.DEBUG
else:
level = logging.INFO
if logfile is not None:
logging.basicConfig(format="%(asctime)s %(levelname)8s %(message)s", datefmt="%H:%M:%S %Y/%m/%d", level=level, filename=logfile)
else:
... | def setup_logging(debug, logfile=None) | Setup logging format and log level. | 1.868355 | 1.700797 | 1.098517 |
'''
Entrypoint function for non-test ("real") mode. At this point
we assume that we are running as root and have pcap module.
'''
usercode_entry_point = import_or_die(usercode, ('main', 'switchy_main'))
if options.dryrun:
log_info("Imported your code successfully. Exiting dry run.")
... | def main_real(usercode, netobj, options) | Entrypoint function for non-test ("real") mode. At this point
we assume that we are running as root and have pcap module. | 9.465915 | 7.356645 | 1.286716 |
'''
Should be called by Switchyard user code when a network object is
being shut down. (This method cleans up internal threads and network
interaction objects.)
'''
if not LLNetReal.running:
return
LLNetReal.running = False
log_debug("Joining... | def shutdown(self) | Should be called by Switchyard user code when a network object is
being shut down. (This method cleans up internal threads and network
interaction objects.) | 9.1595 | 4.251686 | 2.154322 |
'''
Internal method. Creates threads to handle low-level
network receive.
'''
for devname,pdev in self._pcaps.items():
t = threading.Thread(target=LLNetReal._low_level_dispatch, args=(pdev, devname, self._pktqueue))
t.start()
self._threads.app... | def _spawn_threads(self) | Internal method. Creates threads to handle low-level
network receive. | 10.882378 | 5.888199 | 1.848167 |
'''
Internal method. Assemble information on each interface/
device that we know about, i.e., its MAC address and configured
IP address and prefix.
'''
devtype = {}
for p in pcap_devices():
if p.isloop:
devtype[p.name] = InterfaceType.... | def _assemble_devinfo(self) | Internal method. Assemble information on each interface/
device that we know about, i.e., its MAC address and configured
IP address and prefix. | 3.177285 | 2.645339 | 1.201088 |
'''
Internal method. Create libpcap devices
for every network interface we care about and
set them in non-blocking mode.
'''
self._pcaps = {}
for devname,intf in self._devinfo.items():
if intf.iftype == InterfaceType.Loopback:
senddev ... | def _make_pcaps(self) | Internal method. Create libpcap devices
for every network interface we care about and
set them in non-blocking mode. | 9.411544 | 5.150459 | 1.827321 |
'''
Handle process INT signal.
'''
log_debug("Got SIGINT.")
if signum == signal.SIGINT:
LLNetReal.running = False
if self._pktqueue.qsize() == 0:
# put dummy pkt in queue to unblock a
# possibly stuck user thread
... | def _sig_handler(self, signum, stack) | Handle process INT signal. | 12.998661 | 10.440089 | 1.245072 |
'''
Thread entrypoint for doing low-level receive and dispatch
for a single pcap device.
'''
while LLNetReal.running:
# a non-zero timeout value is ok here; this is an
# independent thread that handles input for this
# one pcap device. it thro... | def _low_level_dispatch(pcapdev, devname, pktqueue) | Thread entrypoint for doing low-level receive and dispatch
for a single pcap device. | 8.787444 | 7.225061 | 1.216245 |
'''
Receive packets from any device on which one is available.
Blocks until it receives a packet, unless a timeout value >=0
is given. Raises Shutdown exception when device(s) are shut
down (i.e., on a SIGINT to the process). Raises NoPackets when
there are no packets... | def recv_packet(self, timeout=None) | Receive packets from any device on which one is available.
Blocks until it receives a packet, unless a timeout value >=0
is given. Raises Shutdown exception when device(s) are shut
down (i.e., on a SIGINT to the process). Raises NoPackets when
there are no packets that can be read.
... | 7.928147 | 3.18606 | 2.488386 |
'''
Send a Switchyard Packet object on the given device
(string name of device).
Raises ValueError if packet object isn't valid, or device
name isn't recognized.
'''
if packet is None:
raise ValueError("No packet object given to send_packet")
... | def send_packet(self, dev, packet) | Send a Switchyard Packet object on the given device
(string name of device).
Raises ValueError if packet object isn't valid, or device
name isn't recognized. | 4.457918 | 3.200861 | 1.392725 |
if not isinstance(node, javalang.tree.Declaration):
return False
if 'private' in node.modifiers:
return False
if isinstance(node, javalang.tree.Documented) and node.documentation:
doc = javalang.javadoc.parse(node.documentation)
if 'hid... | def __default_filter(self, node) | Excludes private members and those tagged "@hide" / "@exclude" in their
docblocks. | 3.411086 | 2.598693 | 1.312616 |
if see.startswith('<a href'):
# HTML link -- <a href="...">...</a>
return self.__html_to_rst(see)
elif '"' in see:
# Plain text
return see
else:
# Type reference (default)
return ':java:ref:`%s`' % (see.replace('#'... | def __output_see(self, see) | Convert the argument to a @see tag to rest | 7.523846 | 7.046201 | 1.067788 |
outer_type = name.rpartition('.')[0]
document = util.Document()
document.add(imports_block)
document.add_heading(name, '=')
method_summary = util.StringBuilder()
document.add_object(method_summary)
package_dir = util.Directive('java:package', package)... | def compile_type_document(self, imports_block, package, name, declaration) | Compile a complete document, documenting a type and its members | 2.074779 | 2.053801 | 1.010215 |
documents = {}
imports = util.StringBuilder()
for imp in ast.imports:
if imp.static or imp.wildcard:
continue
package_parts = []
cls_parts = []
for part in imp.path.split('.'):
if cls_parts or part[0].is... | def compile(self, ast) | Compile autodocs for the given Java syntax tree. Documents will be
returned documenting each separate type. | 3.799466 | 3.558701 | 1.067655 |
'''
Return packed byte representation of the UDP header.
'''
hdr = struct.pack(RIPv2._PACKFMT, self.command.value, 2)
routes = b''.join([r.to_bytes() for r in self._routes])
return hdr + routes | def to_bytes(self) | Return packed byte representation of the UDP header. | 10.270965 | 6.392762 | 1.606655 |
if len(data) % 2 != 0:
arr = array.array('H', data[:-1])
else:
arr = array.array('H', data)
if skip_word is not None:
for i in range(0, len(arr)):
if i == skip_word:
continue
start += arr[i]
else:
for i in range(0, len(arr)):
start += arr[i]
if len(data) % 2 !=... | def checksum (data, start = 0, skip_word = None) | Calculate standard internet checksum over data starting at start'th byte
skip_word: If specified, it's the word offset of a word in data to "skip"
(as if it were zero). The purpose is when data is received
data which contains a computed checksum that you are trying to
verify -... | 2.758224 | 2.690703 | 1.025094 |
has_explicit_title, title, target = split_explicit_title(text)
title = utils.unescape(title)
target = utils.unescape(target)
if not has_explicit_title:
target = target.lstrip('~')
if title[0] == '~':
title = title[1:].rpartition('.')[2]
app = inliner.document.set... | def javadoc_role(name, rawtext, text, lineno, inliner, options={}, content=[]) | Role for linking to external Javadoc | 4.043306 | 4.068038 | 0.993921 |
'''
Add new input port + packet to buffer.
'''
id = len(self._buffer) + 1
if id > self._buffsize:
raise FullBuffer()
self._buffer[id] = (port, deepcopy(pkt))
return id | def add(self, port, pkt) | Add new input port + packet to buffer. | 6.991942 | 4.652576 | 1.502811 |
'''
Process actions in order, in two stages. Each action implements a __call__, which
applies any packet-level changes or other non-output changes. The functors
can optionally return another function to be applied at the second stage.
'''
second_stage = []
for a... | def _process_actions(self, actions, inport, packet) | Process actions in order, in two stages. Each action implements a __call__, which
applies any packet-level changes or other non-output changes. The functors
can optionally return another function to be applied at the second stage. | 10.806177 | 2.846012 | 3.796954 |
'''
Handle single packet on the data plane.
'''
inport = self._switchyard_net.port_by_name(inport)
portnum = inport.ifnum
log_info("Processing packet: {}->{}".format(portnum, packet))
actions = None
for tnum,t in enumerate(self._tables):
actio... | def _handle_datapath(self, inport, packet) | Handle single packet on the data plane. | 9.363522 | 8.523768 | 1.098519 |
'''
Return packed byte representation of the UDP header.
'''
return struct.pack(UDP._PACKFMT, self._src, self._dst,
self._len, self._checksum) | def to_bytes(self) | Return packed byte representation of the UDP header. | 9.215855 | 4.261832 | 2.162416 |
'''Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < UDP._MINLEN:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an UDP object".format(len(raw)))
fields = struct.unpack(UDP._PACKFMT, r... | def from_bytes(self, raw) | Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. | 4.352777 | 2.618768 | 1.662147 |
'''
Return packed byte representation of the TCP header.
'''
header = self._make_header(self._checksum)
return header + self._options.to_bytes() | def to_bytes(self) | Return packed byte representation of the TCP header. | 11.475135 | 5.030525 | 2.281101 |
'''Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < TCP._MINLEN:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an TCP object".format(len(raw)))
fields = struct.unpack(TCP._PACKFMT, r... | def from_bytes(self, raw) | Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. | 3.871027 | 2.89156 | 1.338733 |
'''
Return packed byte representation of the UDP header.
'''
csum = 0
if dochecksum:
csum = self.checksum()
return b''.join((struct.pack(ICMP._PACKFMT, self._type.value, self._code.value, csum), self._icmpdata.to_bytes())) | def to_bytes(self, dochecksum=True) | Return packed byte representation of the UDP header. | 6.077451 | 4.345373 | 1.398603 |
'''
Parse and clean up argument to user code; separate *args from
**kwargs.
'''
args = []
kwargs = {}
if isinstance(argstr, str):
for a in argstr.split():
if '=' in a:
k,attr = a.split('=')
kwargs[k] = attr
else:
... | def _parse_codeargs(argstr) | Parse and clean up argument to user code; separate *args from
**kwargs. | 4.574526 | 2.633274 | 1.737201 |
if isinstance(dq, str):
dq = IPv4Address(dq)
v = int(dq)
c = 0
while v & 0x80000000:
c += 1
v <<= 1
v = v & 0xffFFffFF
if v != 0:
raise RuntimeError("Netmask %s is not CIDR-compatible" % (dq,))
return c | def netmask_to_cidr (dq) | Takes a netmask as either an IPAddr or a string, and returns the number
of network bits. e.g., 255.255.255.0 -> 24
Raise exception if subnet mask is not CIDR-compatible. | 3.342999 | 2.854457 | 1.171151 |
def check (r0, r1):
a = int(r0)
b = r1
if (not allow_host) and (a & ((1<<b)-1)):
raise RuntimeError("Host part of CIDR address is not zero (%s)"
% (addr,))
return (r0,32-r1)
addr = addr.split('/', 2)
if len(addr) == 1:
if infer is False:
return check(IP... | def parse_cidr (addr, infer=True, allow_host=False) | Takes a CIDR address or plain dotted-quad, and returns a tuple of address
and count-of-network-bits.
Can infer the network bits based on network classes if infer=True.
Can also take a string in the form 'address/netmask', as long as the
netmask is representable in CIDR.
FIXME: This function is badly named. | 3.452433 | 3.456316 | 0.998876 |
addr = int(addr)
if addr == 0:
# Special case -- default network
return 32-32 # all bits wildcarded
if (addr & (1 << 31)) == 0:
# Class A
return 32-24
if (addr & (3 << 30)) == 2 << 30:
# Class B
return 32-16
if (addr & (7 << 29)) == 6 << 29:
# Class C
return 32-8
if (addr ... | def infer_netmask (addr) | Uses network classes to guess the number of network bits | 2.713157 | 2.685869 | 1.01016 |
return ((self.__value[0] == 0x01)
and (self.__value[1] == 0x80)
and (self.__value[2] == 0xC2)
and (self.__value[3] == 0x00)
and (self.__value[4] == 0x00)
and (self.__value[5] <= 0x0F)) | def isBridgeFiltered (self) | Checks if address is an IEEE 802.1D MAC Bridge Filtered MAC Group Address
This range is 01-80-C2-00-00-00 to 01-80-C2-00-00-0F. MAC frames that
have a destination MAC address within this range are not relayed by
bridges conforming to IEEE 802.1D | 2.661068 | 2.054822 | 1.295036 |
return separator.join(('{:02x}'.format(x) for x in self.__value)) | def toStr (self, separator = ':') | Returns the address as string consisting of 12 hex chars separated
by separator. | 5.764154 | 5.535158 | 1.041371 |
'''
Return packed byte representation of the Ethernet header.
'''
return struct.pack(Ethernet._PACKFMT, self._dst.packed,
self._src.packed, self._ethertype.value) | def to_bytes(self) | Return packed byte representation of the Ethernet header. | 11.085058 | 5.422785 | 2.044163 |
'''Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < Ethernet._MINLEN:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an "
"Ethernet object".format(len(raw)))
dst,src,ethe... | def from_bytes(self, raw) | Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. | 4.934791 | 3.224194 | 1.53055 |
'''
Get the simulation substrate started. The key things are to set up
a series of queues that connect nodes together and get the link emulation
objects started (all inside the NodeExecutor class). The NodePlumbing
named tuples hold together threads for each node, the emulation
substrate (Node... | def run_simulation(topo, **kwargs) | Get the simulation substrate started. The key things are to set up
a series of queues that connect nodes together and get the link emulation
objects started (all inside the NodeExecutor class). The NodePlumbing
named tuples hold together threads for each node, the emulation
substrate (NodeExecutors), ... | 19.36418 | 3.965552 | 4.883099 |
'''
Implement short-cut commands: any unique command prefix should
work.'''
cmdargs = line.split()
remain = ' '.join(cmdargs[1:])
if 'show'.startswith(cmdargs[0]):
self.do_show(remain)
elif 'set'.startswith(cmdargs[0]):
self.do_set(remain)
... | def default(self, line) | Implement short-cut commands: any unique command prefix should
work. | 2.230414 | 1.851002 | 1.204977 |
'''
Internal switchyard static initialization method.
'''
if ApplicationLayer._isinit:
return
ApplicationLayer._isinit = True
ApplicationLayer._to_app = {}
ApplicationLayer._from_app = Queue() | def _init() | Internal switchyard static initialization method. | 16.948013 | 8.608667 | 1.968715 |
'''
Called by a network stack implementer to receive application-layer
data for sending on to a remote location.
Can optionally take a timeout value. If no data are available,
raises NoPackets exception.
Returns a 2-tuple: flowaddr and data.
The flowaddr cons... | def recv_from_app(timeout=_default_timeout) | Called by a network stack implementer to receive application-layer
data for sending on to a remote location.
Can optionally take a timeout value. If no data are available,
raises NoPackets exception.
Returns a 2-tuple: flowaddr and data.
The flowaddr consists of 5 items: pro... | 12.831472 | 1.950923 | 6.57713 |
'''
Called by a network stack implementer to push application-layer
data "up" from the stack.
Arguments are protocol number, local_addr (a 2-tuple of IP address
and port), remote_addr (a 2-tuple of IP address and port), and the
message.
Returns True if a socke... | def send_to_app(proto, local_addr, remote_addr, data) | Called by a network stack implementer to push application-layer
data "up" from the stack.
Arguments are protocol number, local_addr (a 2-tuple of IP address
and port), remote_addr (a 2-tuple of IP address and port), and the
message.
Returns True if a socket was found to which... | 4.112774 | 2.380227 | 1.727892 |
'''
Internal method used by socket emulation layer to create a new "upward"
queue for an app-layer socket and to register the socket object.
Returns two queues: "downward" (fromapp) and "upward" (toapp).
'''
queue_to_app = Queue()
with _lock:
Applicati... | def _register_socket(s) | Internal method used by socket emulation layer to create a new "upward"
queue for an app-layer socket and to register the socket object.
Returns two queues: "downward" (fromapp) and "upward" (toapp). | 10.806032 | 3.016913 | 3.581818 |
'''
Internal method used to update an existing socket registry when the socket
is re-bound to a different local port number. Requires the socket object
and old sockid. Returns None.
'''
with _lock:
sock_queue = ApplicationLayer._to_app.pop(oldid)
... | def _registry_update(s, oldid) | Internal method used to update an existing socket registry when the socket
is re-bound to a different local port number. Requires the socket object
and old sockid. Returns None. | 12.87395 | 4.190734 | 3.072004 |
'''
Internal method used to remove the socket from AppLayer registry.
Warns if the "upward" socket queue has any left-over data.
'''
with _lock:
sock_queue = ApplicationLayer._to_app.pop(s._sockid())
if not sock_queue.empty():
log_warn("Socket be... | def _unregister_socket(s) | Internal method used to remove the socket from AppLayer registry.
Warns if the "upward" socket queue has any left-over data. | 24.612196 | 6.504662 | 3.783778 |
'''
Alter the local address with which this socket is associated.
The address parameter is a 2-tuple consisting of an IP address
and port number.
NB: this method fails and returns -1 if the requested port
to bind to is already in use but does *not* check that the
... | def bind(self, address) | Alter the local address with which this socket is associated.
The address parameter is a 2-tuple consisting of an IP address
and port number.
NB: this method fails and returns -1 if the requested port
to bind to is already in use but does *not* check that the
address is valid. | 14.536229 | 6.810516 | 2.13438 |
'''
Receive data on the socket. The buffersize and flags
arguments are currently ignored. Only returns the data.
'''
_,_,data = self._recv(buffersize)
return data | def recv(self, buffersize, flags=0) | Receive data on the socket. The buffersize and flags
arguments are currently ignored. Only returns the data. | 10.189755 | 3.638995 | 2.800157 |
'''
Receive data on the socket. The buffersize and flags
arguments are currently ignored. Returns the data and
an address tuple (IP address and port) of the remote host.
'''
_,remoteaddr,data = self._recv(buffersize)
return data,remoteaddr | def recvfrom(self, buffersize, flags=0) | Receive data on the socket. The buffersize and flags
arguments are currently ignored. Returns the data and
an address tuple (IP address and port) of the remote host. | 7.903312 | 2.892644 | 2.73221 |
'''
Send data on the socket. A call to connect() must have
been previously made for this call to succeed.
Flags is currently ignored.
'''
if self._remote_addr == (None,None):
raise sockerr("ENOTCONN: socket not connected")
return self._send(data, self... | def send(self, data, flags=0) | Send data on the socket. A call to connect() must have
been previously made for this call to succeed.
Flags is currently ignored. | 10.041655 | 5.083186 | 1.975465 |
'''
Send data on the socket. Accepts the same parameters as the
built-in socket sendto: data[, flags], address
where address is a 2-tuple of IP address and port.
Any flags are currently ignored.
'''
remoteaddr = args[-1]
remoteaddr = _normalize_addrs(remo... | def sendto(self, data, *args) | Send data on the socket. Accepts the same parameters as the
built-in socket sendto: data[, flags], address
where address is a 2-tuple of IP address and port.
Any flags are currently ignored. | 5.966499 | 2.662787 | 2.240697 |
'''
Set the timeout value for this socket.
'''
if timeout is None:
self._block = True
elif float(timeout) == 0.0:
self._block = False
else:
self._timeout = float(timeout)
self._block = True | def settimeout(self, timeout) | Set the timeout value for this socket. | 3.317524 | 2.994425 | 1.1079 |
'''
Return packed byte representation of the ARP header.
'''
return struct.pack(Arp._PACKFMT, self._hwtype.value, self._prototype.value, self._hwaddrlen, self._protoaddrlen, self._operation.value, self._senderhwaddr.packed, self._senderprotoaddr.packed, self._targethwaddr.packed, self._t... | def to_bytes(self) | Return packed byte representation of the ARP header. | 4.407492 | 3.046575 | 1.446704 |
'''Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < Arp._MINLEN:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an Arp object".format(len(raw)))
fields = struct.unpack(Arp._PACKFMT, r... | def from_bytes(self, raw) | Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. | 3.134351 | 2.391675 | 1.310525 |
rows = []
for i, tr in enumerate(table.find_all('tr')):
row = []
for c in tr.contents:
cell_type = getattr(c, 'name', None)
if cell_type not in ('td', 'th'):
continue
rowspan = int(c.attrs.get('rows... | def _process_table_cells(self, table) | Compile all the table cells.
Returns a list of rows. The rows may have different lengths because of
column spans. | 2.605672 | 2.45579 | 1.061032 |
'''
Import user code; return reference to usercode function.
(str) -> function reference
'''
log_debug("Importing {}".format(module_name))
module_name = os.path.abspath(module_name)
if module_name.endswith('.py'):
module_name,ext = os.path.splitext(module_name)
modname = os.path... | def import_or_die(module_name, entrypoint_names) | Import user code; return reference to usercode function.
(str) -> function reference | 3.814202 | 3.414802 | 1.116961 |
'''
Run the command progargs with optional input to be fed in to stdin.
'''
stdin = None
if stdinput is not None:
assert(isinstance(stdinput, list))
stdin=PIPE
err = 0
output = b''
log_debug("Calling {} with input {}".format(' '.join(progargs), stdinput))
try:
... | def _runcmd(progargs, stdinput=None) | Run the command progargs with optional input to be fed in to stdin. | 3.073062 | 2.765342 | 1.111277 |
'''
pfctl -a switchyard -f- < rules.txt
pfctl -a switchyard -F rules
pfctl -t switchyard -F r
'''
st,output = _runcmd("/sbin/pfctl -aswitchyard -f -", self._rules)
log_debug("Installing rules: {}".format(output)) | def block(self) | pfctl -a switchyard -f- < rules.txt
pfctl -a switchyard -F rules
pfctl -t switchyard -F r | 20.083822 | 5.422791 | 3.703595 |
'''
Display the topology
'''
__do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs)
pyp.show() | def show_graph(cn_topo, showintfs=False, showaddrs=False) | Display the topology | 8.171948 | 7.034001 | 1.161778 |
'''
Save the topology to an image file
'''
__do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs)
pyp.savefig(filename) | def save_graph(cn_topo, filename, showintfs=False, showaddrs=False) | Save the topology to an image file | 6.460555 | 5.534104 | 1.167407 |
'''
Load a topology from filename and return it.
'''
t = None
with open(filename, 'rU') as infile:
tdata = infile.read()
t = Topology.unserialize(tdata)
return t | def load_from_file(filename) | Load a topology from filename and return it. | 5.336437 | 4.105007 | 1.299983 |
'''
Save a topology to a file.
'''
jstr = cn_topo.serialize()
with open(filename, 'w') as outfile:
outfile.write(jstr) | def save_to_file(cn_topo, filename) | Save a topology to a file. | 3.68105 | 3.649613 | 1.008614 |
'''
Add a node to the topology
'''
if name in self.nodes:
raise Exception("A node by the name {} already exists. Can't add a duplicate.".format(name))
self.__nxgraph.add_node(name)
self.__nxgraph.node[name]['label'] = name
self.__nxgraph.node[name]['n... | def __addNode(self, name, cls) | Add a node to the topology | 3.440186 | 3.090888 | 1.113009 |
'''
Add a new host node to the topology.
'''
if name is None:
while True:
name = 'h' + str(self.__hnum)
self.__hnum += 1
if name not in self.__nxgraph:
break
self.__addNode(name, Host)
return ... | def addHost(self, name=None) | Add a new host node to the topology. | 3.719063 | 3.149066 | 1.181005 |
'''
Add a new switch to the topology.
'''
if name is None:
while True:
name = 's' + str(self.__snum)
self.__snum += 1
if name not in self.__nxgraph:
break
self.__addNode(name, Switch)
return n... | def addSwitch(self, name=None) | Add a new switch to the topology. | 3.728714 | 3.421387 | 1.089825 |
'''
Add a new switch to the topology.
'''
if name is None:
while True:
name = 'r' + str(self.__rnum)
self.__rnum += 1
if name not in self.__nxgraph:
break
self.__addNode(name, Router)
return n... | def addRouter(self, name=None) | Add a new switch to the topology. | 4.177574 | 3.553553 | 1.175605 |
'''
Add a bidirectional link between node1 and node2 with the given
capacity and delay to the topology.
'''
for n in (node1, node2):
if not self.__nxgraph.has_node(n):
raise Exception("No node {} exists for building a link".format(n))
macs = [N... | def addLink(self, node1, node2, capacity, delay) | Add a bidirectional link between node1 and node2 with the given
capacity and delay to the topology. | 3.003302 | 2.779432 | 1.080545 |
'''
Return a JSON string of the serialized topology
'''
return json.dumps(json_graph.node_link_data(self.__nxgraph), cls=Encoder) | def serialize(self) | Return a JSON string of the serialized topology | 10.279255 | 5.00114 | 2.055383 |
'''
Unserialize a JSON string representation of a topology
'''
topod = json.loads(jsonstr)
G = json_graph.node_link_graph(topod)
for n,ndict in G.nodes(data=True):
if 'nodeobj' not in ndict or 'type' not in ndict:
raise Exception("Required type... | def unserialize(jsonstr) | Unserialize a JSON string representation of a topology | 4.404052 | 4.001738 | 1.100535 |
'''
Assign IP addresses to all interfaces on hosts and routers in the
network.
NB: this method assumes that all interfaces are assigned
addresses on the same subnet. If you don't want that behavior,
the setInterfaceAddresses method must be used.
'''
... | def assignIPAddresses(self, prefix=None) | Assign IP addresses to all interfaces on hosts and routers in the
network.
NB: this method assumes that all interfaces are assigned
addresses on the same subnet. If you don't want that behavior,
the setInterfaceAddresses method must be used. | 5.337552 | 3.566036 | 1.496775 |
'''
Given two node names that identify a link, return the pair of
interface names assigned at each endpoint (as a tuple in the
same order as the nodes given).
'''
linkdata = self.getLink(node1,node2)
return linkdata[node1],linkdata[node1] | def getLinkInterfaces(self, node1, node2) | Given two node names that identify a link, return the pair of
interface names assigned at each endpoint (as a tuple in the
same order as the nodes given). | 8.663121 | 2.621056 | 3.305203 |
'''
Set any one of Ethernet (MAC) address, IP address or IP netmask for
a given interface on a node.
'''
if not self.hasNode(node):
raise Exception("No such node {}".format(node))
nobj = self.getNode(node)['nodeobj']
if interface not in nobj:
... | def setInterfaceAddresses(self, node, interface, mac=None, ip=None, netmask=None) | Set any one of Ethernet (MAC) address, IP address or IP netmask for
a given interface on a node. | 3.317581 | 2.55262 | 1.299677 |
'''
Return the Ethernet and IP+mask addresses assigned to a
given interface on a node.
'''
intf = self.getNode(node)['nodeobj'].getInterface(interface)
return intf.ethaddr,intf.ipaddr,intf.netmask | def getInterfaceAddresses(self, node, interface) | Return the Ethernet and IP+mask addresses assigned to a
given interface on a node. | 8.852928 | 3.78331 | 2.339995 |
'''
Rename all nodes in the network from x to prefix_x. If no prefix
is given, use the name of the graph as the prefix.
The purpose of this method is to make node names unique so that
composing two graphs is well-defined.
'''
nxgraph = Topology.__relabel... | def addNodeLabelPrefix(self, prefix=None, copy=False) | Rename all nodes in the network from x to prefix_x. If no prefix
is given, use the name of the graph as the prefix.
The purpose of this method is to make node names unique so that
composing two graphs is well-defined. | 6.642932 | 2.822376 | 2.353667 |
'''
Union/add two topologies together to form a larger topology.
If rename is False, the method assumes that node names
don't clash (i.e., you've called addNodeLabelPrefix or
you've explicitly chosen names to avoid clashes).
If rename is True, nodes/links are relabel... | def union(self, other, rename=False) | Union/add two topologies together to form a larger topology.
If rename is False, the method assumes that node names
don't clash (i.e., you've called addNodeLabelPrefix or
you've explicitly chosen names to avoid clashes).
If rename is True, nodes/links are relabeled such that the
... | 5.590219 | 1.636937 | 3.41505 |
'''Return a Null header object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < 4:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct a Null object".format(len(raw)))
fields = struct.unpack('=I', raw[:4])
sel... | def from_bytes(self, raw) | Return a Null header object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. | 7.58924 | 3.422991 | 2.217137 |
'''
Returns serialized bytes object representing all headers/
payloads in this packet'''
rawlist = []
i = len(self._headers)-1
while i >= 0:
self._headers[i].pre_serialize(b''.join(rawlist), self, i)
rawlist.insert(0, self._headers[i].to_bytes())
... | def to_bytes(self) | Returns serialized bytes object representing all headers/
payloads in this packet | 4.93906 | 2.959832 | 1.668696 |
'''
Parse a raw bytes object and construct the list of packet header
objects (and possible remaining bytes) that are part of this packet.
'''
if next_cls is None:
from switchyard.lib.packet import Ethernet
next_cls = Ethernet
self._headers = []
... | def _parse(self, raw, next_cls) | Parse a raw bytes object and construct the list of packet header
objects (and possible remaining bytes) that are part of this packet. | 4.630805 | 2.960109 | 1.564403 |
'''
Add a PacketHeaderBase derived class object, or a raw bytes object
as the next "header" item in this packet. Note that 'header'
may be a slight misnomer since the last portion of a packet is
considered application payload and not a header per se.
'''
if isins... | def add_header(self, ph) | Add a PacketHeaderBase derived class object, or a raw bytes object
as the next "header" item in this packet. Note that 'header'
may be a slight misnomer since the last portion of a packet is
considered application payload and not a header per se. | 9.00925 | 2.395904 | 3.760271 |
'''
Return True if the packet has a header of the given hdrclass,
False otherwise.
'''
if isinstance(hdrclass, str):
return self.get_header_by_name(hdrclass) is not None
return self.get_header(hdrclass) is not None | def has_header(self, hdrclass) | Return True if the packet has a header of the given hdrclass,
False otherwise. | 3.483964 | 2.218193 | 1.570631 |
'''
Return the header object that has the given (string) header
class name. Returns None if no such header exists.
'''
for hdr in self._headers:
if hdr.__class__.__name__ == hdrname:
return hdr
return None | def get_header_by_name(self, hdrname) | Return the header object that has the given (string) header
class name. Returns None if no such header exists. | 4.353965 | 2.168999 | 2.007361 |
'''
Return the first header object that is of
class hdrclass, or None if the header class isn't
found.
'''
if isinstance(hdrclass, str):
return self.get_header_by_name(hdrclass)
for hdr in self._headers:
if isinstance(hdr, hdrclass):
... | def get_header(self, hdrclass, returnval=None) | Return the first header object that is of
class hdrclass, or None if the header class isn't
found. | 3.776677 | 2.167176 | 1.742672 |
'''
Return the first index of the header class hdrclass
starting at startidx (default=0), or -1 if the
header class isn't found in the list of headers.
'''
for hdridx in range(startidx, len(self._headers)):
if isinstance(self._headers[hdridx], hdrclass):
... | def get_header_index(self, hdrclass, startidx=0) | Return the first index of the header class hdrclass
starting at startidx (default=0), or -1 if the
header class isn't found in the list of headers. | 3.359138 | 1.814986 | 1.850779 |
'''Return class of next header, if known.'''
if self._next_header_class_key == '':
return None
key = getattr(self, self._next_header_class_key)
rv = self._next_header_map.get(key, None)
if rv is None:
log_warn("No class exists to handle next header value {... | def next_header_class(self) | Return class of next header, if known. | 4.822228 | 4.151624 | 1.161528 |
env = Environment(extensions=['jinja2_time.TimeExtension'])
value_template = env.from_string(self.value_template)
return value_template.render(**context) | def process(self, **context) | Render value_template of the parameter using context.
:param context: Processing context | 3.868189 | 3.0393 | 1.272724 |
serializer = UpdateSerializer(data=request.data)
if serializer.is_valid():
try:
bot = caching.get_or_set(TelegramBot, hook_id)
except TelegramBot.DoesNotExist:
logger.warning("Hook id %s not associated to an bot" % hook_id)
... | def post(self, request, hook_id) | Process Telegram webhook.
1. Serialize Telegram message
2. Get an enabled Telegram bot
3. Create :class:`Update <permabots.models.telegram_api.Update>`
5. Delay processing to a task
6. Response provider | 2.587803 | 2.360462 | 1.096312 |
bots = Bot.objects.filter(owner=request.user)
serializer = BotSerializer(bots, many=True)
return Response(serializer.data) | def get(self, request, format=None) | Get list of bots
---
serializer: BotSerializer
responseMessages:
- code: 401
message: Not authenticated | 2.643583 | 3.215898 | 0.822036 |
serializer = BotSerializer(data=request.data)
if serializer.is_valid():
bot = Bot.objects.create(owner=request.user,
name=serializer.data['name'])
return Response(BotSerializer(bot).data, status=status.HTTP_201_CREATED)
return... | def post(self, request, format=None) | Add a new bot
---
serializer: BotSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request | 1.792111 | 1.763453 | 1.016251 |
bot = self.get_bot(id, request.user)
serializer = BotSerializer(bot)
return Response(serializer.data) | def get(self, request, id, format=None) | Get bot by id
---
serializer: BotSerializer
responseMessages:
- code: 401
message: Not authenticated | 3.492866 | 4.687008 | 0.745223 |
bot = self.get_bot(id, request.user)
serializer = BotUpdateSerializer(bot, data=request.data)
if serializer.is_valid():
try:
bot = serializer.save()
except:
return Response(status=status.HTTP_400_BAD_REQUEST)
else:
... | def put(self, request, id, format=None) | Update an existing bot
---
serializer: BotUpdateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request | 1.934937 | 1.964636 | 0.984883 |
bot = self.get_bot(id, request.user)
bot.delete()
return Response(status=status.HTTP_204_NO_CONTENT) | def delete(self, request, id, format=None) | Delete an existing bot
---
responseMessages:
- code: 401
message: Not authenticated | 2.774193 | 3.357668 | 0.826226 |
return super(TelegramBotList, self).get(request, bot_id, format) | def get(self, request, bot_id, format=None) | Get list of Telegram bots
---
serializer: TelegramBotSerializer
responseMessages:
- code: 401
message: Not authenticated | 4.42071 | 5.979133 | 0.739356 |
try:
return super(TelegramBotList, self).post(request, bot_id, format)
except:
return Response({"error": 'Telegram Error. Check Telegram token or try later.'}, status=status.HTTP_400_BAD_REQUEST) | def post(self, request, bot_id, format=None) | Add TelegramBot
---
serializer: TelegramBotSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request | 4.309582 | 4.207794 | 1.02419 |
return super(TelegramBotDetail, self).get(request, bot_id, id, format) | def get(self, request, bot_id, id, format=None) | Get TelegramBot by id
---
serializer: TelegramBotSerializer
responseMessages:
- code: 401
message: Not authenticated | 3.977058 | 6.279234 | 0.633367 |
return super(TelegramBotDetail, self).put(request, bot_id, id, format) | def put(self, request, bot_id, id, format=None) | Update existing TelegramBot
---
serializer: TelegramBotUpdateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request | 4.153057 | 6.296934 | 0.659536 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.