本文整理汇总了Python中utils.utils.Utils类的典型用法代码示例。如果您正苦于以下问题:Python Utils类的具体用法?Python Utils怎么用?Python Utils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Utils类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: execute
def execute(self, userdata):
if self.comms.isKilled or self.comms.isAborted:
self.comms.abortMission()
return 'aborted'
if not self.comms.retVal or \
len(self.comms.retVal['foundLines']) == 0:
return 'lost'
lines = self.comms.retVal['foundLines']
if len(lines) == 1 or self.comms.expectedLanes == 1:
self.angleSampler.newSample(lines[0]['angle'])
elif len(lines) >= 2:
if self.comms.chosenLane == self.comms.LEFT:
self.angleSampler.newSample(lines[0]['angle'])
elif self.comms.chosenLane == self.comms.RIGHT:
self.angleSampler.newSample(lines[1]['angle'])
else:
rospy.loginfo("Something goes wrong with chosenLane")
variance = self.angleSampler.getVariance()
rospy.loginfo("Variance: {}".format(variance))
if (variance < 5.0):
dAngle = Utils.toHeadingSpace(self.angleSampler.getMedian())
adjustHeading = Utils.normAngle(self.comms.curHeading + dAngle)
self.comms.sendMovement(h=adjustHeading, blocking=True)
self.comms.adjustHeading = adjustHeading
return 'aligned'
else:
rospy.sleep(rospy.Duration(0.05))
return 'aligning'
开发者ID:silverbullet1,项目名称:bbauv,代码行数:32,代码来源:states.py
示例2: findSamples
def findSamples(self, category, binImg, samples, outImg):
contours = self.findContourAndBound(binImg.copy(), bounded=True,
upperbounded=True,
bound=self.minContourArea,
upperbound=self.maxContourArea)
contours = sorted(contours, key=cv2.contourArea, reverse=True)
for contour in contours:
# Find the center of each contour
rect = cv2.minAreaRect(contour)
centroid = rect[0]
# Find the orientation of each contour
points = np.int32(cv2.cv.BoxPoints(rect))
edge1 = points[1] - points[0]
edge2 = points[2] - points[1]
if cv2.norm(edge1) > cv2.norm(edge2):
angle = math.degrees(math.atan2(edge1[1], edge1[0]))
else:
angle = math.degrees(math.atan2(edge2[1], edge2[0]))
if 90 < abs(Utils.normAngle(self.comms.curHeading) -
Utils.normAngle(angle)) < 270:
angle = Utils.invertAngle(angle)
samples.append({'centroid': centroid, 'angle': angle,
'area': cv2.contourArea(contour),
'category': category})
if self.debugMode:
Vision.drawRect(outImg, points)
开发者ID:silverbullet1,项目名称:bbauv,代码行数:31,代码来源:vision.py
示例3: _evaluate_bandwidth_availability
def _evaluate_bandwidth_availability(self, check_1, check_2):
state = ''
changed = False
wma_1 = Utils.compute_wma(check_1)
logging.debug('BANDWIDTH wma_1: %s' % (wma_1))
if check_2 is not None:
wma_2 = Utils.compute_wma(check_2)
logging.debug('BANDWIDTH wma_2: %s' % (wma_2))
wma_diff = wma_2 - wma_1
wma_diff_abs = abs(wma_diff)
variation = round(float(wma_diff_abs/wma_1*100), 1)
logging.debug('BANDWIDTH variation: %s' % (variation))
if variation >= float(self._cfg['bandwidth_avail_factor']):
variation_dim = 'accretion'
if wma_diff > 0.0:
variation_dim = 'degradation'
state = 'BANDWIDTH availability --> %s%% %s <b style="color: red;">(!!! NEW !!!)</b>' % (variation, variation_dim)
changed = True
else:
state = 'BANDWIDTH availability --> %s' % (wma_2)
else:
state = 'BANDWIDTH availability --> %s' % (wma_1)
logging.debug('BANDWIDTH check_final: %s' % (state))
return changed, state
开发者ID:bl4ckh0l3z,项目名称:downjustforme,代码行数:30,代码来源:evaluator.py
示例4: print_table
def print_table(ligs):
for lig_num, lig in enumerate(ligs):
for element_num, element in enumerate(lig):
ligs[lig_num][element_num] = ActionSearch._format_.get(element,
element)
Utils.print_table(ligs)
开发者ID:commial,项目名称:docky,代码行数:7,代码来源:search.py
示例5: create_share
def create_share(self, obj):
share = Utils.create_object()
share.title = obj.logo_title
share.description = obj.short_description
share.url = Utils.get_current_url(self.request)
encoded_url = urlquote_plus(share.url)
title = obj.logo_title
encoded_title = urlquote_plus(title)
encoded_detail = urlquote_plus(obj.short_description)
url_detail = obj.short_description + '\n\n' + share.url
encoded_url_detail = urlquote_plus(url_detail)
share.image_url = Utils.get_url(
self.request,
PosterService.poster_image_url(obj)
)
encoded_image_url = urlquote_plus(share.image_url)
# email shouldn't encode space
share.email = 'subject=%s&body=%s' % (
urlquote(title, ''), urlquote(url_detail, '')
)
#
share.fb = 'u=%s' % encoded_url
#
share.twitter = 'text=%s' % encoded_url_detail
#
share.google_plus = 'url=%s' % encoded_url
#
share.linkedin = 'url=%s&title=%s&summary=%s' % (
encoded_url, encoded_title, encoded_detail
)
#
share.pinterest = 'url=%s&media=%s&description=%s' % (
encoded_url, encoded_image_url, encoded_detail
)
return share
开发者ID:renjimin,项目名称:alatting,代码行数:35,代码来源:views.py
示例6: camCallback
def camCallback(self, rosImg):
outImg = self.visionFilter.gotFrame(Utils.rosimg2cv(rosImg))
if self.canPublish and outImg is not None:
try:
self.outPub.publish(Utils.cv2rosimg(outImg))
except Exception, e:
pass
开发者ID:quarbby,项目名称:OpenCV,代码行数:7,代码来源:vision_robosub_day1.py
示例7: run
def run(self):
images = self.client.images()
# Parse images information
images_enhanced = []
for img in images:
for repotag in img["RepoTags"]:
registry, repository = self.parse_repository(
":".join(repotag.split(":")[:-1]))
images_enhanced.append({"IMAGE ID": img["Id"][:10],
"CREATED": img["Created"],
"VIRTUAL SIZE": img["VirtualSize"],
"TAG": repotag.split(":")[-1],
"REPOSITORY": repository,
"REGISTRY": registry,
})
# Sort images (with facilities for sort key)
sort_by = self.args.sort_by
for column in self._FIELDS_:
if column.startswith(sort_by.upper()):
sort_by = column
break
images = sorted(images_enhanced, key=lambda x: x.get(sort_by))
# Print images information
for img in images:
img["VIRTUAL SIZE"] = ActionImages.printable_size(
img["VIRTUAL SIZE"])
img["CREATED"] = ActionImages.printable_date(img["CREATED"])
Utils.print_table([self._FIELDS_] + [[img[k]
for k in self._FIELDS_] for img in images])
开发者ID:commial,项目名称:docky,代码行数:33,代码来源:images.py
示例8: __init__
def __init__(self, config, phishtank, openphish, cleanmx):
logging.debug("Instantiating the '%s' class" % (self.__class__.__name__))
self._cfg = config
self._phishtank = phishtank
self._openphish = openphish
self._cleanmx = cleanmx
Utils.remove_dir_content(self._cfg['dir_out'])
开发者ID:boh717,项目名称:phishunter,代码行数:7,代码来源:extractor.py
示例9: _clean_status_container
def _clean_status_container(self, status):
targets = []
for container in self.client.containers(all=True):
if container["Status"].startswith(status):
# Sanitize
if container["Names"] is None:
container["Names"] = ["NO_NAME"]
targets.append(container)
if len(targets) == 0:
print "No containers %s found." % (status.lower())
return
# Display available elements
print "%d containers %s founds." % (len(targets), status.lower())
ligs = [["NAME", "IMAGE", "COMMAND"]]
ligs += [[",".join(c["Names"]).replace("/", ""), c["Image"], c["Command"]]
for c in targets]
Utils.print_table(ligs)
if Utils.ask("Remove some of them", default="N"):
for container in targets:
if Utils.ask(
"\tRemove %s" % container["Names"][0].replace("/", ""),
default="N"):
# Force is false to avoid bad moves
print "\t-> Removing %s..." % container["Id"][:10]
self.client.remove_container(container["Id"], v=False,
link=False,
force=False)
开发者ID:commial,项目名称:docky,代码行数:30,代码来源:clean.py
示例10: run
def run(self):
print("Running...")
os.system('ls -i -t ' + self._cfg['dir_archive'] +'/* | cut -d\' \' -f2 | tail -n+1 | xargs rm -f')
data_old = JSONAdapter.load(self._cfg['dir_in'], self._cfg['serial_file'])
if data_old is not None:
data_file_name_new = data_old[0] + '_' + self._cfg['serial_file']
Utils.rename_file(self._cfg['dir_in'], self._cfg['dir_archive'], \
self._cfg['serial_file'], data_file_name_new)
else:
data_old = []
if Utils.is_internet_up() is True:
urls = self._cfg['urls_to_check']
data_new = []
data_new.insert(0, Utils.timestamp_to_string(time.time()))
thread_id = 0
threads = []
display = Display(visible=0, size=(1024, 768))
display.start()
for url in urls:
thread_id += 1
alivechecker_thread = AliveChecker(thread_id, self._cfg, url)
threads.append(alivechecker_thread)
alivechecker_thread.start()
# Waiting for all threads to complete
for thread in threads:
thread.join()
display.stop()
for thread in threads:
data_new.append(thread.data)
logging.debug('%s\n' % (thread.log))
thread.browser.quit()
if len(data_new) > 0:
JSONAdapter.save(data_new, self._cfg['dir_in'], self._cfg['serial_file'])
data_all = []
if len(data_old) > 0:
data_all.append(data_old)
data_all.append(data_new)
JSONAdapter.save(data_all, self._cfg['dir_out'], self._cfg['serial_file'])
state = self._evaluator.run(data_all)
logging.debug('Final state: %s' % (state))
if self._emailnotifiers and state != '':
EmailNotifiers.notify(state)
else:
logging.debug('Empty data')
else:
logging.error('Internet is definitely down!')
sys.exit(2)
print("Done...")
开发者ID:bl4ckh0l3z,项目名称:downjustforme,代码行数:59,代码来源:run.py
示例11: sonarImageCallback
def sonarImageCallback(self, rosImg):
# outImg = self.visionFilter.gotSonarFrame(Utils.rosimg2cv(rosImg))
outImg = self.sonarFilter.gotSonarFrame(Utils.rosimg2cv(rosImg))
if self.canPublish and outImg is not None:
try:
self.sonarPub.publish(Utils.cv2rosimg(outImg))
except Exception, e:
pass
开发者ID:quarbby,项目名称:OpenCV,代码行数:8,代码来源:comms.py
示例12: camCallback
def camCallback(self, rosImg):
try:
if self.processingCount == self.processingRate:
self.retVal, outImg = self.visionFilter.gotFrame(Utils.rosimg2cv(rosImg))
if self.canPublish and outImg is not None:
self.outPub.publish(Utils.cv2rosimg(outImg))
self.processingCount = 0
self.processingCount += 1
except Exception as e:
print e
开发者ID:silverbullet1,项目名称:bbauv,代码行数:10,代码来源:bot_comms.py
示例13: _dump_file_trails
def _dump_file_trails(self, apk_file):
logging.debug("Dumping file_trails")
path = apk_file.get_path()
file = apk_file.get_filename()
file_trails = dict()
file_trails['file_name'] = file
file_trails['file_md5_sum'] = Utils.compute_md5_file(path, file)
file_trails['file_sha256_sum'] = Utils.compute_sha256_file(path, file)
file_trails['file_dimension'] = Utils.get_size(path, file)
return file_trails
开发者ID:bl4ckh0l3z,项目名称:droidtrail,代码行数:10,代码来源:trailsdumper.py
示例14: camCallback
def camCallback(self, img):
rospy.loginfo("Solo")
img = Utils.rosimg2cv(img)
red_img = Img(img, conn)
if(1000 < red_img.area < 1500):
red_img.drawBounding(red_img.mask_bgr)
red_img.drawCentroid(red_img.mask_bgr)
drawCenter(red_img.mask_bgr)
self.img_pub.publish(Utils.cv2rosimg(red_img.mask_bgr))
self.img_pub2.publish(Utils.cv2rosimg(red_img.enhanced_bgr))
开发者ID:silverbullet1,项目名称:bbauv,代码行数:10,代码来源:vision.py
示例15: sonarCallback
def sonarCallback(self, rosimg):
rospy.loginfo("Inside sonar")
cvImg = Utils.rosimg2cv(rosimg)
gray = cv2.cvtColor(cvImg, cv2.COLOR_BGR2GRAY)
mask = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)[1]
mask_bgr = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
sobel_bgr = self.sobelLine(mask)
#self.sonarCont(mask, mask_bgr)
sonarPub = rospy.Publisher("/Vision/image_filter_sonar", Image)
sonarPub.publish(Utils.cv2rosimg(sobel_bgr))
开发者ID:quarbby,项目名称:OpenCV,代码行数:10,代码来源:testVision.py
示例16: execute
def execute(self, userdata):
if self.comms.isKilled or self.comms.isAborted:
self.comms.abortMission()
return 'aborted'
curCorner = self.comms.visionFilter.curCorner
start = time.time()
while not self.comms.retVal or \
self.comms.retVal.get('foundLines', None) is None or \
len(self.comms.retVal['foundLines']) == 0:
if self.comms.isKilled or self.comms.isAborted:
self.comms.abortMission()
return 'aborted'
if time.time() - start > self.timeout:
if curCorner == 4:
self.comms.failTask()
return 'lost'
else:
self.comms.visionFilter.curCorner += 1
self.comms.detectingBox = True
return 'next_corner'
rospy.sleep(rospy.Duration(0.1))
# Calculate angle between box and lane
if self.comms.visionFilter.curCorner == 0:
boxCentroid = (self.centerX, self.centerY)
else:
boxCentroid = self.comms.visionFilter.corners[curCorner]
laneCentroid = self.comms.retVal['foundLines'][0]['pos']
boxLaneAngle = math.atan2(laneCentroid[1] - boxCentroid[1],
laneCentroid[0] - boxCentroid[0])
self.angleSampler.newSample(math.degrees(boxLaneAngle))
variance = self.angleSampler.getVariance()
rospy.loginfo("Variance: {}".format(variance))
if (variance < 5.0):
dAngle = Utils.toHeadingSpace(self.angleSampler.getMedian())
adjustHeading = Utils.normAngle(self.comms.curHeading + dAngle)
self.comms.inputHeading = adjustHeading
rospy.loginfo("box-lane angle: {}".format(self.comms.inputHeading))
self.comms.sendMovement(h=adjustHeading,
d=self.comms.laneSearchDepth,
blocking=True)
self.comms.sendMovement(f=self.forward_dist, h=adjustHeading,
d=self.comms.laneSearchDepth,
blocking=True)
self.comms.visionFilter.curCorner = 0
return 'aligned'
else:
rospy.sleep(rospy.Duration(0.05))
return 'aligning'
开发者ID:silverbullet1,项目名称:bbauv,代码行数:52,代码来源:acousticStates.py
示例17: _extract
def _extract(self, path_in, file, password):
try:
if Utils.is_zip(path_in, file):
Utils.extract_zip(path_in, file, path_in, password)
elif Utils.is_rar(path_in, file):
Utils.extract_rar(path_in, file, path_in, password)
elif Utils.is_tar(path_in, file):
Utils.extract_tar(path_in, file, path_in)
except OSError, e:
logging.error(e)
return False
开发者ID:bl4ckh0l3z,项目名称:droidtrail,代码行数:11,代码来源:extractor.py
示例18: save_ph_ws
def save_ph_ws(ph_ws):
logging.debug("XMLAdapter is storing phishing websites...")
Utils.remove_dir_content(XMLAdapter.config['dir_out'])
for cm_name, cm in ph_ws.items():
if len(cm) > 0:
try:
file_ph_ws_name = os.path.join(XMLAdapter.config['dir_out'], cm_name + '.xml')
file_ph_ws = open(file_ph_ws_name, 'w')
file_ph_ws.write(dicttoxml.dicttoxml(ph_ws))
file_ph_ws.close()
except OSError, e:
logging.error("Error saving phishing websites in xml format: %s" % (e))
raise OSError
开发者ID:boh717,项目名称:phishunter,代码行数:15,代码来源:xmladapter.py
示例19: run
def run(self):
# Format inputs
reg_from = self.get_registryaddr("from")
reg_to = self.get_registryaddr("to")
imgsrc = self.args.IMGSRC
if ":" not in imgsrc:
imgsrc += ":latest"
imgdst = self.args.IMGDST if (self.args.IMGDST != '-') else imgsrc
if ":" not in imgdst:
imgdst += ":latest"
isrc = reg_from + imgsrc
idst = reg_to + imgdst
# Confirm transfer
if not Utils.ask("Transfer %s -> %s" % (isrc, idst)):
return
# Search for source image avaibility
isrc_id = None
for img in self.client.images():
if isrc in img["RepoTags"]:
isrc_id = img["Id"]
print "'%s' is locally available (%s), use it" % (isrc, img["Id"][:10])
# Source image is not available, pull it
if isrc_id is None:
if not Utils.ask("'%s' is not locally available, try to pull it" % isrc):
return
# Try to pull Image without creds
res = self.client.pull(isrc, insecure_registry=True)
if "error" in res:
print "An error as occurred (DEBUG: %s)" % res
return
print "'%s' successfully pulled !" % isrc
raise NotImplementedError("Get image id")
# Tag the element
idst, idst_tag = ":".join(idst.split(":")[:-1]), idst.split(":")[-1]
self.client.tag(isrc_id, idst, tag=idst_tag, force=False)
# Push the element, insecure mode
print "Pushing..."
for status in self.client.push(idst, tag=idst_tag, stream=True,
insecure_registry=True):
sys.stdout.write("\r" + json.loads(status)["status"])
sys.stdout.flush()
print "\nTransfer complete !"
开发者ID:commial,项目名称:docky,代码行数:48,代码来源:transfer.py
示例20: __init__
def __init__(self, peer_id, log=None):
super(PeerState, self).__init__()
self.id = peer_id # site ID
self.peers = [] # known peers
self.strokes = [] # currently drawn strokes
self.prqs = [] # past requests
self.processed_ops = []
self.session = -1
# attached ui
self.window = None
self.lock = Lock()
# site log file
self.log = log
if self.id >= 0:
self.engine = OperationEngine(self.id,log)
else:
# This is so that I can draw locally if I never join a session
self.engine = OperationEngine(0,log)
self.queue = Queue(log)
# Join/leave handling
self.ip = ''
self.port = 0
self.cs = None
self.uid = Utils.generateID()
self.ips = []
self.ports = []
开发者ID:sixam,项目名称:dw6824,代码行数:33,代码来源:common.py
注:本文中的utils.utils.Utils类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论