desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
':class:`bool`: Whether the current binary is packed with UPX.'
| @property
def packed(self):
| return ('UPX!' in self.get_data())
|
':class:`bool`: Whether the current binary is position-independent.'
| @property
def pie(self):
| return (self.elftype == 'DYN')
|
':class:`bool`: Whether the current binary has an ``RPATH``.'
| @property
def rpath(self):
| dt_rpath = self.dynamic_by_tag('DT_RPATH')
if (not dt_rpath):
return None
return self.dynamic_string(dt_rpath.entry.d_ptr)
|
':class:`bool`: Whether the current binary has a ``RUNPATH``.'
| @property
def runpath(self):
| dt_runpath = self.dynamic_by_tag('DT_RUNPATH')
if (not dt_runpath):
return None
return self.dynamic_string(dt_rpath.entry.d_ptr)
|
'checksec(banner=True)
Prints out information in the binary, similar to ``checksec.sh``.
Arguments:
banner(bool): Whether to print the path to the ELF binary.'
| def checksec(self, banner=True):
| red = text.red
green = text.green
yellow = text.yellow
res = []
if (self.version and (self.version != (0,))):
res.append(('Version:'.ljust(10) + '.'.join(map(str, self.version))))
if self.build:
res.append(('Build:'.ljust(10) + self.build))
res.extend([('RELRO:'.ljust(10) + {... |
':class:`str`: GNU Build ID embedded into the binary'
| @property
def buildid(self):
| section = self.get_section_by_name('.note.gnu.build-id')
if section:
return section.data()[16:]
return None
|
':class:`bool`: Whether the current binary was built with
Fortify Source (``-DFORTIFY``).'
| @property
def fortify(self):
| if any((s.endswith('_chk') for s in self.plt)):
return True
return False
|
':class:`bool`: Whether the current binary was built with
Address Sanitizer (``ASAN``).'
| @property
def asan(self):
| return any((s.startswith('__asan_') for s in self.symbols))
|
':class:`bool`: Whether the current binary was built with
Memory Sanitizer (``MSAN``).'
| @property
def msan(self):
| return any((s.startswith('__msan_') for s in self.symbols))
|
':class:`bool`: Whether the current binary was built with
Undefined Behavior Sanitizer (``UBSAN``).'
| @property
def ubsan(self):
| return any((s.startswith('__ubsan_') for s in self.symbols))
|
'Writes a 64-bit integer ``data`` to the specified ``address``'
| def p64(self, address, data, *a, **kw):
| self._update_args(kw)
return self.write(address, packing.p64(data, *a, **kw))
|
'Writes a 32-bit integer ``data`` to the specified ``address``'
| def p32(self, address, data, *a, **kw):
| self._update_args(kw)
return self.write(address, packing.p32(data, *a, **kw))
|
'Writes a 16-bit integer ``data`` to the specified ``address``'
| def p16(self, address, data, *a, **kw):
| self._update_args(kw)
return self.write(address, packing.p16(data, *a, **kw))
|
'Writes a 8-bit integer ``data`` to the specified ``address``'
| def p8(self, address, data, *a, **kw):
| self._update_args(kw)
return self.write(address, packing.p8(data, *a, **kw))
|
'Writes a packed integer ``data`` to the specified ``address``'
| def pack(self, address, data, *a, **kw):
| self._update_args(kw)
return self.write(address, packing.pack(data, *a, **kw))
|
'Unpacks an integer from the specified ``address``.'
| def u64(self, address, *a, **kw):
| self._update_args(kw)
return packing.u64(self.read(address, 8), *a, **kw)
|
'Unpacks an integer from the specified ``address``.'
| def u32(self, address, *a, **kw):
| self._update_args(kw)
return packing.u32(self.read(address, 4), *a, **kw)
|
'Unpacks an integer from the specified ``address``.'
| def u16(self, address, *a, **kw):
| self._update_args(kw)
return packing.u16(self.read(address, 2), *a, **kw)
|
'Unpacks an integer from the specified ``address``.'
| def u8(self, address, *a, **kw):
| self._update_args(kw)
return packing.u8(self.read(address, 1), *a, **kw)
|
'Unpacks an integer from the specified ``address``.'
| def unpack(self, address, *a, **kw):
| self._update_args(kw)
return packing.unpack(self.read(address, context.bytes), *a, **kw)
|
'Reads a null-terminated string from the specified ``address``'
| def string(self, address):
| data = ''
while True:
c = self.read(address, 1)
if (not c):
return ''
if (c == '\x00'):
return data
data += c
address += 1
|
'Writes a full array of values to the specified address.
See: :func:`.packing.flat`'
| def flat(self, address, *a, **kw):
| return self.write(address, packing.flat(*a, **kw))
|
'Writes fitted data into the specified address.
See: :func:`.packing.fit`'
| def fit(self, address, *a, **kw):
| return self.write(address, packing.fit(*a, **kw))
|
'Disables NX for the ELF.
Zeroes out the ``PT_GNU_STACK`` program header ``p_type`` field.'
| def disable_nx(self):
| PT_GNU_STACK = packing.p32(ENUM_P_TYPE['PT_GNU_STACK'])
if (not self.executable):
log.error('Can only make stack executable with executables')
for (i, segment) in enumerate(self.iter_segments()):
if (not segment.header.p_type):
continue
if ('GNU_STACK' n... |
'AdbClient\'s connection to the ADB server'
| @property
def c(self):
| if (not self._c):
try:
level = self.level
with context.quiet:
if (not self.isEnabledFor(logging.INFO)):
level = logging.FATAL
self._c = Connection(self.host, self.port, level=level)
except Exception:
if ((self.ho... |
'Decorator which automatically closes the connection to the ADB server
after calling the decorated function.'
| def _autoclose(fn):
| @functools.wraps(fn)
def wrapper(self, *a, **kw):
rv = fn(self, *a, **kw)
if self._c:
self._c.close()
self._c = None
return rv
return wrapper
|
'Decorator which automatically selects a device transport before calling
the decorated function, and closes the connection afterward.'
| def _with_transport(fn):
| @functools.wraps(fn)
def wrapper(self, *a, **kw):
self.transport()
rv = fn(self, *a, **kw)
if self._c:
self._c.close()
self._c = None
return rv
return wrapper
|
'Sends data to the ADB server'
| def send(self, *a, **kw):
| return self.c.adb_send(*a, **kw)
|
'Receives a hex-ascii packed integer from the ADB server'
| def unpack(self, *a, **kw):
| return self.c.adb_unpack(*a, **kw)
|
'Receives a length-prefixed data buffer from the ADB server'
| def recvl(self):
| length = self.c.adb_unpack()
return self.c.recvn(length)
|
'Kills the remote ADB server"
>>> c=pwnlib.protocols.adb.AdbClient()
>>> c.kill()
The server is automatically re-started on the next request,
if the default host/port are used.
>>> c.version() > (4,0)
True'
| @_autoclose
def kill(self):
| try:
self.send('host:kill')
except EOFError:
pass
|
'Returns:
Tuple containing the ``(major, minor)`` version from the ADB server
Example:
>>> pwnlib.protocols.adb.AdbClient().version() # doctest: +SKIP
(4, 36)'
| @_autoclose
def version(self):
| response = self.send('host:version')
if (response == OKAY):
return (self.c.adb_unpack(), self.c.adb_unpack())
self.error('Could not fetch version')
|
'Arguments:
long(bool): If :const:`True`, fetch the long-format listing.
Returns:
String representation of all available devices.'
| @_autoclose
def devices(self, long=False):
| msg = 'host:devices'
if long:
msg += '-l'
response = self.send(msg)
if (response == 'OKAY'):
return self.recvl()
self.error('Could not enumerate devices')
|
'Returns:
Generator which returns a short-format listing of available
devices each time a device state changes.'
| @_autoclose
def track_devices(self):
| self.send('host:track-devices')
while True:
(yield self.recvl())
|
'Sets the Transport on the rmeote device.
Examples:
>>> pwnlib.protocols.adb.AdbClient().transport()'
| def transport(self, serial=None):
| if ((not serial) and context.device):
serial = context.device
if serial:
serial = str(serial)
msg = ('host:transport:%s' % serial)
else:
msg = 'host:transport-any'
if (self.send(msg) == FAIL):
if serial:
self.error(('Could not set transport ... |
'Executes a program on the device.
Returns:
A :class:`pwnlib.tubes.tube.tube` which is connected to the process.
Examples:
>>> pwnlib.protocols.adb.AdbClient().execute([\'echo\',\'hello\']).recvall()
\'hello\n\''
| @_autoclose
@_with_transport
def execute(self, argv):
| self.transport(context.device)
if isinstance(argv, str):
argv = [argv]
argv = list(map(sh_string, argv))
cmd = ('exec:%s' % ' '.join(argv))
if (OKAY == self.send(cmd)):
rv = self._c
self._c = None
return rv
|
'Decorator which enters \'sync:\' mode to the selected transport,
then invokes the decorated funciton.'
| def _sync(fn):
| @functools.wraps(fn)
def wrapper(self, *a, **kw):
rv = None
if (FAIL != self.send('sync:')):
rv = fn(self, *a, **kw)
return rv
return wrapper
|
'Execute the ``LIST`` command of the ``SYNC`` API.
Arguments:
path(str): Path of the directory to list.
Return:
A dictionary, where the keys are relative filenames,
and the values are a dictionary containing the same
values as ``stat()`` supplies.
Note:
In recent releases of Android (e.g. 7.0), the domain that
adbd exe... | def list(self, path):
| st = self.stat(path)
if (not st):
log.error(('Cannot list directory %r: Does not exist' % path))
if (not stat.S_ISDIR(st['mode'])):
log.error(('Cannot list directory %r: Path is not a directory' % path))
return self._list(path)
|
'Execute the ``STAT`` command of the ``SYNC`` API.
Arguments:
path(str): Path to the file to stat.
Return:
On success, a dictionary mapping the values returned.
If the file cannot be ``stat()``ed, None is returned.
Example:
>>> expected = {\'mode\': 16749, \'size\': 0, \'time\': 0}
>>> pwnlib.protocols.adb.AdbClient().... | @_with_transport
@_sync
def stat(self, path):
| self.c.flat32('STAT', len(path), path)
if (self.c.recvn(4) != 'STAT'):
self.error('An error occured while attempting to STAT a file.')
mode = self.c.u32()
size = self.c.u32()
time = self.c.u32()
if ((mode, size, time) == (0, 0, 0)):
return None
return ... |
'Execute the ``WRITE`` command of the ``SYNC`` API.
Arguments:
path(str): Path to the file to write
data(str): Data to write to the file
mode(int): File mode to set (e.g. ``0o755``)
timestamp(int): Unix timestamp to set the file date to
callback(callable): Callback function invoked as data
is written. Arguments provid... | def write(self, path, data, mode=493, timestamp=None, callback=None):
| st = self.stat(path)
if (st and stat.S_ISDIR(st['mode'])):
log.error(('Cannot write to %r: Path is a directory' % path))
return self._write(path, data, mode=493, timestamp=None, callback=None)
|
'Execute the ``READ`` command of the ``SYNC`` API.
Arguments:
path(str): Path to the file to read
filesize(int): Size of the file, in bytes. Optional.
callback(callable): Callback function invoked as data
becomes available. Arguments provided are:
- File path
- All data
- Expected size of all data
- Current chunk
- E... | @_with_transport
@_sync
def read(self, path, filesize=0, callback=(lambda *a: True)):
| self.c.send((('RECV' + p32(len(path))) + path))
all_data = ''
while True:
magic = self.c.recvn(4)
if (magic == 'DONE'):
break
if (magic == 'FAIL'):
self.error(('Could not read file %r: Got FAIL.' % path))
if (magic != 'DATA'):
... |
'This layer does not propagate gradients.'
| def backward(self, top, propagate_down, bottom):
| pass
|
'Reshaping happens during the call to forward.'
| def reshape(self, bottom, top):
| pass
|
'Initialize CocoEval using coco APIs for gt and dt
:param cocoGt: coco object with ground truth annotations
:param cocoDt: coco object with detection results
:return: None'
| def __init__(self, cocoGt=None, cocoDt=None):
| self.cocoGt = cocoGt
self.cocoDt = cocoDt
self.params = {}
self.evalImgs = defaultdict(list)
self.eval = {}
self._gts = defaultdict(list)
self._dts = defaultdict(list)
self.params = Params()
self._paramsEval = {}
self.stats = []
self.ious = {}
if (not (cocoGt is None)):
... |
'Prepare ._gts and ._dts for evaluation based on params
:return: None'
| def _prepare(self):
| def _toMask(objs, coco):
for obj in objs:
t = coco.imgs[obj['image_id']]
if (type(obj['segmentation']) == list):
if (type(obj['segmentation'][0]) == dict):
print 'debug'
obj['segmentation'] = mask.frPyObjects(obj['segmentation'], t[... |
'Run per image evaluation on given images and store results (a list of dict) in self.evalImgs
:return: None'
| def evaluate(self):
| tic = time.time()
print 'Running per image evaluation... '
p = self.params
p.imgIds = list(np.unique(p.imgIds))
if p.useCats:
p.catIds = list(np.unique(p.catIds))
p.maxDets = sorted(p.maxDets)
self.params = p
self._prepare()
catIds = (p.catIds ... |
'perform evaluation for single category and image
:return: dict (single image results)'
| def evaluateImg(self, imgId, catId, aRng, maxDet):
| p = self.params
if p.useCats:
gt = self._gts[(imgId, catId)]
dt = self._dts[(imgId, catId)]
else:
gt = [_ for cId in p.catIds for _ in self._gts[(imgId, cId)]]
dt = [_ for cId in p.catIds for _ in self._dts[(imgId, cId)]]
if ((len(gt) == 0) and (len(dt) == 0)):
re... |
'Accumulate per image evaluation results and store the result in self.eval
:param p: input params for evaluation
:return: None'
| def accumulate(self, p=None):
| print 'Accumulating evaluation results... '
tic = time.time()
if (not self.evalImgs):
print 'Please run evaluate() first'
if (p is None):
p = self.params
p.catIds = (p.catIds if (p.useCats == 1) else [(-1)])
T = len(p.iouThrs)
R = len(p.recThrs)
... |
'Compute and display summary metrics for evaluation results.
Note this functin can *only* be applied on the default parameter setting'
| def summarize(self):
| def _summarize(ap=1, iouThr=None, areaRng='all', maxDets=100):
p = self.params
iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6} | maxDets={:>3} ] = {}'
titleStr = ('Average Precision' if (ap == 1) else 'Average Recall')
typeStr = ('(AP)' if (ap == 1... |
'Constructor of Microsoft COCO helper class for reading and visualizing annotations.
:param annotation_file (str): location of annotation file
:param image_folder (str): location to the folder that hosts images.
:return:'
| def __init__(self, annotation_file=None):
| self.dataset = {}
self.anns = []
self.imgToAnns = {}
self.catToImgs = {}
self.imgs = {}
self.cats = {}
if (not (annotation_file == None)):
print 'loading annotations into memory...'
tic = time.time()
dataset = json.load(open(annotation_file, 'r'))
pri... |
'Print information about the annotation file.
:return:'
| def info(self):
| for (key, value) in self.dataset['info'].items():
print ('%s: %s' % (key, value))
|
'Get ann ids that satisfy given filter conditions. default skips that filter
:param imgIds (int array) : get anns for given imgs
catIds (int array) : get anns for given cats
areaRng (float array) : get anns for given area range (e.g. [0 inf])
iscrowd (boolean) : get anns for given crowd label (False o... | def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
| imgIds = (imgIds if (type(imgIds) == list) else [imgIds])
catIds = (catIds if (type(catIds) == list) else [catIds])
if (len(imgIds) == len(catIds) == len(areaRng) == 0):
anns = self.dataset['annotations']
else:
if (not (len(imgIds) == 0)):
lists = [self.imgToAnns[imgId] for i... |
'filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids'
| def getCatIds(self, catNms=[], supNms=[], catIds=[]):
| catNms = (catNms if (type(catNms) == list) else [catNms])
supNms = (supNms if (type(supNms) == list) else [supNms])
catIds = (catIds if (type(catIds) == list) else [catIds])
if (len(catNms) == len(supNms) == len(catIds) == 0):
cats = self.dataset['categories']
else:
cats = self.datas... |
'Get img ids that satisfy given filter conditions.
:param imgIds (int array) : get imgs for given ids
:param catIds (int array) : get imgs with all given cats
:return: ids (int array) : integer array of img ids'
| def getImgIds(self, imgIds=[], catIds=[]):
| imgIds = (imgIds if (type(imgIds) == list) else [imgIds])
catIds = (catIds if (type(catIds) == list) else [catIds])
if (len(imgIds) == len(catIds) == 0):
ids = self.imgs.keys()
else:
ids = set(imgIds)
for (i, catId) in enumerate(catIds):
if ((i == 0) and (len(ids) == ... |
'Load anns with the specified ids.
:param ids (int array) : integer ids specifying anns
:return: anns (object array) : loaded ann objects'
| def loadAnns(self, ids=[]):
| if (type(ids) == list):
return [self.anns[id] for id in ids]
elif (type(ids) == int):
return [self.anns[ids]]
|
'Load cats with the specified ids.
:param ids (int array) : integer ids specifying cats
:return: cats (object array) : loaded cat objects'
| def loadCats(self, ids=[]):
| if (type(ids) == list):
return [self.cats[id] for id in ids]
elif (type(ids) == int):
return [self.cats[ids]]
|
'Load anns with the specified ids.
:param ids (int array) : integer ids specifying img
:return: imgs (object array) : loaded img objects'
| def loadImgs(self, ids=[]):
| if (type(ids) == list):
return [self.imgs[id] for id in ids]
elif (type(ids) == int):
return [self.imgs[ids]]
|
'Display the specified annotations.
:param anns (array of object): annotations to display
:return: None'
| def showAnns(self, anns):
| if (len(anns) == 0):
return 0
if ('segmentation' in anns[0]):
datasetType = 'instances'
elif ('caption' in anns[0]):
datasetType = 'captions'
if (datasetType == 'instances'):
ax = plt.gca()
polygons = []
color = []
for ann in anns:
c = ... |
'Load result file and return a result api object.
:param resFile (str) : file name of result file
:return: res (obj) : result api object'
| def loadRes(self, resFile):
| res = COCO()
res.dataset['images'] = [img for img in self.dataset['images']]
print 'Loading and preparing results... '
tic = time.time()
anns = json.load(open(resFile))
assert (type(anns) == list), 'results in not an array of objects'
annsImgIds ... |
'Download COCO images from mscoco.org server.
:param tarDir (str): COCO results directory name
imgIds (list): images to be downloaded
:return:'
| def download(self, tarDir=None, imgIds=[]):
| if (tarDir is None):
print 'Please specify target directory'
return (-1)
if (len(imgIds) == 0):
imgs = self.imgs.values()
else:
imgs = self.loadImgs(imgIds)
N = len(imgs)
if (not os.path.exists(tarDir)):
os.makedirs(tarDir)
for (i, img) in enumera... |
'all_boxes is a list of length number-of-classes.
Each list element is a list of length number-of-images.
Each of those list elements is either an empty list []
or a numpy array of detection.
all_boxes[class][image] = [] or np.array of shape #dets x 5'
| def evaluate_detections(self, all_boxes, output_dir=None):
| raise NotImplementedError
|
'Evaluate detection proposal recall metrics.
Returns:
results: dictionary of results with keys
\'ar\': average recall
\'recalls\': vector recalls at each IoU overlap threshold
\'thresholds\': vector of IoU overlap thresholds
\'gt_overlaps\': vector of all ground-truth overlaps'
| def evaluate_recall(self, candidate_boxes=None, thresholds=None, area='all', limit=None):
| areas = {'all': 0, 'small': 1, 'medium': 2, 'large': 3, '96-128': 4, '128-256': 5, '256-512': 6, '512-inf': 7}
area_ranges = [[(0 ** 2), (100000.0 ** 2)], [(0 ** 2), (32 ** 2)], [(32 ** 2), (96 ** 2)], [(96 ** 2), (100000.0 ** 2)], [(96 ** 2), (128 ** 2)], [(128 ** 2), (256 ** 2)], [(256 ** 2), (512 ** 2)], [(5... |
'Turn competition mode on or off.'
| def competition_mode(self, on):
| pass
|
'Return the absolute path to image i in the image sequence.'
| def image_path_at(self, i):
| return self.image_path_from_index(self._image_index[i])
|
'Construct an image path from the image\'s "index" identifier.'
| def image_path_from_index(self, index):
| image_path = os.path.join(self._data_path, 'JPEGImages', (index + self._image_ext))
assert os.path.exists(image_path), 'Path does not exist: {}'.format(image_path)
return image_path
|
'Load the indexes listed in this dataset\'s image set file.'
| def _load_image_set_index(self):
| image_set_file = os.path.join(self._data_path, 'ImageSets', 'Main', (self._image_set + '.txt'))
assert os.path.exists(image_set_file), 'Path does not exist: {}'.format(image_set_file)
with open(image_set_file) as f:
image_index = [x.strip() for x in f.readlines()]
return image_index
|
'Return the default path where PASCAL VOC is expected to be installed.'
| def _get_default_path(self):
| return os.path.join(cfg.DATA_DIR, ('VOCdevkit' + self._year))
|
'Return the database of ground-truth regions of interest.
This function loads/saves from/to a cache file to speed up future calls.'
| def gt_roidb(self):
| cache_file = os.path.join(self.cache_path, (self.name + '_gt_roidb.pkl'))
if os.path.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = cPickle.load(fid)
print '{} gt roidb loaded from {}'.format(self.name, cache_file)
return roidb
gt_roidb = [... |
'Return the database of selective search regions of interest.
Ground-truth ROIs are also included.
This function loads/saves from/to a cache file to speed up future calls.'
| def selective_search_roidb(self):
| cache_file = os.path.join(self.cache_path, (self.name + '_selective_search_roidb.pkl'))
if os.path.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = cPickle.load(fid)
print '{} ss roidb loaded from {}'.format(self.name, cache_file)
return roidb
... |
'Load image and bounding boxes info from XML file in the PASCAL VOC
format.'
| def _load_pascal_annotation(self, index):
| filename = os.path.join(self._data_path, 'Annotations', (index + '.xml'))
tree = ET.parse(filename)
objs = tree.findall('object')
if (not self.config['use_diff']):
non_diff_objs = [obj for obj in objs if (int(obj.find('difficult').text) == 0)]
objs = non_diff_objs
num_objs = len(objs... |
'Load image ids.'
| def _load_image_set_index(self):
| image_ids = self._COCO.getImgIds()
return image_ids
|
'Return the absolute path to image i in the image sequence.'
| def image_path_at(self, i):
| return self.image_path_from_index(self._image_index[i])
|
'Construct an image path from the image\'s "index" identifier.'
| def image_path_from_index(self, index):
| file_name = (((('COCO_' + self._data_name) + '_') + str(index).zfill(12)) + '.jpg')
image_path = osp.join(self._data_path, 'images', self._data_name, file_name)
assert osp.exists(image_path), 'Path does not exist: {}'.format(image_path)
return image_path
|
'Creates a roidb from pre-computed proposals of a particular methods.'
| def _roidb_from_proposals(self, method):
| top_k = self.config['top_k']
cache_file = osp.join(self.cache_path, ((self.name + '_{:s}_top{:d}'.format(method, top_k)) + '_roidb.pkl'))
if osp.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = cPickle.load(fid)
print '{:s} {:s} roidb loaded from {:s... |
'Load pre-computed proposals in the format provided by Jan Hosang:
http://www.mpi-inf.mpg.de/departments/computer-vision-and-multimodal-
computing/research/object-recognition-and-scene-understanding/how-
good-are-detection-proposals-really/
For MCG, use boxes from http://www.eecs.berkeley.edu/Research/Projects/
CS/visi... | def _load_proposals(self, method, gt_roidb):
| box_list = []
top_k = self.config['top_k']
valid_methods = ['MCG', 'selective_search', 'edge_boxes_AR', 'edge_boxes_70']
assert (method in valid_methods)
print 'Loading {} boxes'.format(method)
for (i, index) in enumerate(self._image_index):
if ((i % 1000) == 0):
print ... |
'Return the database of ground-truth regions of interest.
This function loads/saves from/to a cache file to speed up future calls.'
| def gt_roidb(self):
| cache_file = osp.join(self.cache_path, (self.name + '_gt_roidb.pkl'))
if osp.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = cPickle.load(fid)
print '{} gt roidb loaded from {}'.format(self.name, cache_file)
return roidb
gt_roidb = [self._lo... |
'Loads COCO bounding-box instance annotations. Crowd instances are
handled by marking their overlaps (with all categories) to -1. This
overlap value means that crowd "instances" are excluded from training.'
| def _load_coco_annotation(self, index):
| im_ann = self._COCO.loadImgs(index)[0]
width = im_ann['width']
height = im_ann['height']
annIds = self._COCO.getAnnIds(imgIds=index, iscrowd=None)
objs = self._COCO.loadAnns(annIds)
valid_objs = []
for obj in objs:
x1 = np.max((0, obj['bbox'][0]))
y1 = np.max((0, obj['bbox'][... |
'This layer does not propagate gradients.'
| def backward(self, top, propagate_down, bottom):
| pass
|
'Reshaping happens during the call to forward.'
| def reshape(self, bottom, top):
| pass
|
'This layer does not propagate gradients.'
| def backward(self, top, propagate_down, bottom):
| pass
|
'Reshaping happens during the call to forward.'
| def reshape(self, bottom, top):
| pass
|
'This layer does not propagate gradients.'
| def backward(self, top, propagate_down, bottom):
| pass
|
'Reshaping happens during the call to forward.'
| def reshape(self, bottom, top):
| pass
|
'Randomly permute the training roidb.'
| def _shuffle_roidb_inds(self):
| if cfg.TRAIN.ASPECT_GROUPING:
widths = np.array([r['width'] for r in self._roidb])
heights = np.array([r['height'] for r in self._roidb])
horz = (widths >= heights)
vert = np.logical_not(horz)
horz_inds = np.where(horz)[0]
vert_inds = np.where(vert)[0]
inds = ... |
'Return the roidb indices for the next minibatch.'
| def _get_next_minibatch_inds(self):
| if ((self._cur + cfg.TRAIN.IMS_PER_BATCH) >= len(self._roidb)):
self._shuffle_roidb_inds()
db_inds = self._perm[self._cur:(self._cur + cfg.TRAIN.IMS_PER_BATCH)]
self._cur += cfg.TRAIN.IMS_PER_BATCH
return db_inds
|
'Return the blobs to be used for the next minibatch.
If cfg.TRAIN.USE_PREFETCH is True, then blobs will be computed in a
separate process and made available through self._blob_queue.'
| def _get_next_minibatch(self):
| if cfg.TRAIN.USE_PREFETCH:
return self._blob_queue.get()
else:
db_inds = self._get_next_minibatch_inds()
minibatch_db = [self._roidb[i] for i in db_inds]
return get_minibatch(minibatch_db, self._num_classes)
|
'Set the roidb to be used by this layer during training.'
| def set_roidb(self, roidb):
| self._roidb = roidb
self._shuffle_roidb_inds()
if cfg.TRAIN.USE_PREFETCH:
self._blob_queue = Queue(10)
self._prefetch_process = BlobFetcher(self._blob_queue, self._roidb, self._num_classes)
self._prefetch_process.start()
def cleanup():
print 'Terminating BlobFe... |
'Setup the RoIDataLayer.'
| def setup(self, bottom, top):
| layer_params = yaml.load(self.param_str)
self._num_classes = layer_params['num_classes']
self._name_to_top_map = {}
idx = 0
top[idx].reshape(cfg.TRAIN.IMS_PER_BATCH, 3, max(cfg.TRAIN.SCALES), cfg.TRAIN.MAX_SIZE)
self._name_to_top_map['data'] = idx
idx += 1
if cfg.TRAIN.HAS_RPN:
t... |
'Get blobs and copy them into this layer\'s top blob vector.'
| def forward(self, bottom, top):
| blobs = self._get_next_minibatch()
for (blob_name, blob) in blobs.iteritems():
top_ind = self._name_to_top_map[blob_name]
shape = blob.shape
if (len(shape) == 1):
blob = blob.reshape(blob.shape[0], 1, 1, 1)
if ((len(shape) == 2) and (blob_name != 'im_info')):
... |
'This layer does not propagate gradients.'
| def backward(self, top, propagate_down, bottom):
| pass
|
'Reshaping happens during the call to forward.'
| def reshape(self, bottom, top):
| pass
|
'Randomly permute the training roidb.'
| def _shuffle_roidb_inds(self):
| self._perm = np.random.permutation(np.arange(len(self._roidb)))
self._cur = 0
|
'Return the roidb indices for the next minibatch.'
| def _get_next_minibatch_inds(self):
| if ((self._cur + cfg.TRAIN.IMS_PER_BATCH) >= len(self._roidb)):
self._shuffle_roidb_inds()
db_inds = self._perm[self._cur:(self._cur + cfg.TRAIN.IMS_PER_BATCH)]
self._cur += cfg.TRAIN.IMS_PER_BATCH
return db_inds
|
'Initialize the SolverWrapper.'
| def __init__(self, solver_prototxt, roidb, output_dir, pretrained_model=None):
| self.output_dir = output_dir
if (cfg.TRAIN.HAS_RPN and cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS):
assert cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED
if cfg.TRAIN.BBOX_REG:
print 'Computing bounding-box regression targets...'
(self.bbox_means, self.bbox_stds) ... |
'Take a snapshot of the network after unnormalizing the learned
bounding-box regression weights. This enables easy use at test-time.'
| def snapshot(self):
| net = self.solver.net
scale_bbox_params_faster_rcnn = (cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS and net.params.has_key('bbox_pred'))
scale_bbox_params_rfcn = (cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS and net.params.has_key('rfcn_bbox'))
scale_bbox_params_rpn = (cfg.TRAIN.RP... |
'Network training loop.'
| def train_model(self, max_iters):
| last_snapshot_iter = (-1)
timer = Timer()
model_paths = []
while (self.solver.iter < max_iters):
timer.tic()
self.solver.step(1)
timer.toc()
if ((self.solver.iter % (10 * self.solver_param.display)) == 0):
print 'speed: {:.3f}s / iter'.format(timer.av... |
'docstring for setUp'
| def setUp(self):
| pass
|
'docstring for tearDown'
| def tearDown(self):
| pass
|
'Set use_sandbox to True to use the sandbox (test) APNs servers.
Default is False.'
| def __init__(self, use_sandbox=False, cert_file=None, key_file=None, enhanced=False):
| super(APNs, self).__init__()
self.use_sandbox = use_sandbox
self.cert_file = cert_file
self.key_file = key_file
self._feedback_connection = None
self._gateway_connection = None
self.enhanced = enhanced
|
'Returns an unsigned char in packed form'
| @staticmethod
def packed_uchar(num):
| return pack('>B', num)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.