本文整理汇总了Python中utils.Timer.elapsed方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.elapsed方法的具体用法?Python Timer.elapsed怎么用?Python Timer.elapsed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类utils.Timer
的用法示例。
在下文中一共展示了Timer.elapsed方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RemoteSubscriber
# 需要导入模块: from utils import Timer [as 别名]
# 或者: from utils.Timer import elapsed [as 别名]
class RemoteSubscriber(object):
def __init__(self, uuid, commandID, ipaddress="", port=32400, protocol="http", name=""):
self.poller = False
self.uuid = uuid
self.commandID = commandID
self.url = ""
self.name = name
self.lastUpdated = Timer()
if ipaddress and protocol:
self.url = "%s://%s:%s" % (protocol, ipaddress, port)
def refresh(self, sub):
log.debug("RemoteSubscriber::refresh %s (cid=%s)" % (self.uuid, sub.commandID))
if sub.url != self.url:
log.debug("RemoteSubscriber::refresh new url %s", sub.url)
self.url = sub.url
if sub.commandID != self.commandID:
log.debug("RemoteSubscriber::refresh new commandID %s", sub.commandID)
self.commandID = sub.commandID
self.lastUpdated.restart()
def shouldRemove(self):
if self.lastUpdated.elapsed() > SUBSCRIBER_REMOVE_INTERVAL:
log.debug("RemoteSubscriber::shouldRemove removing %s because elapsed: %lld" % (self.uuid, self.lastUpdated.elapsed()))
return True
log.debug("RemoteSubscriber::shouldRemove will not remove %s because elapsed: %lld" % (self.uuid, self.lastUpdated.elapsed()))
return False
示例2: TimelineManager
# 需要导入模块: from utils import Timer [as 别名]
# 或者: from utils.Timer import elapsed [as 别名]
class TimelineManager(threading.Thread):
def __init__(self):
self.currentItems = {}
self.currentStates = {}
self.idleTimer = Timer()
self.subTimer = Timer()
self.serverTimer = Timer()
self.stopped = False
self.halt = False
threading.Thread.__init__(self)
def stop(self):
self.halt = True
self.join()
def run(self):
while not self.halt:
if playerManager._player and playerManager._video:
if not playerManager.is_paused():
self.SendTimelineToSubscribers()
playerManager.update()
self.idleTimer.restart()
else:
if settings.display_sleep > 0 and self.idleTimer.elapsed() >= settings.display_sleep:
if display.is_on:
log.debug("TimelineManager::run putting display to sleep")
display.power_off()
time.sleep(1)
def SendTimelineToSubscribers(self):
log.debug("TimelineManager::SendTimelineToSubscribers updating all subscribers")
for sub in remoteSubscriberManager.subscribers.values():
self.SendTimelineToSubscriber(sub)
def SendTimelineToSubscriber(self, subscriber):
timelineXML = self.GetCurrentTimeLinesXML(subscriber)
url = "%s/:/timeline" % subscriber.url
log.debug("TimelineManager::SendTimelineToSubscriber sending timeline to %s" % url)
tree = et.ElementTree(timelineXML)
tmp = StringIO()
tree.write(tmp, encoding="utf-8", xml_declaration=True)
tmp.seek(0)
xmlData = tmp.read()
# TODO: Abstract this into a utility function and add other X-Plex-XXX fields
requests.post(url, data=xmlData, headers={
"Content-Type": "application/x-www-form-urlencoded",
"Connection": "keep-alive",
"Content-Range": "bytes 0-/-1",
"X-Plex-Client-Identifier": settings.client_uuid
})
def WaitForTimeline(self, subscriber):
log.info("TimelineManager::WaitForTimeline not implemented...")
def GetCurrentTimeLinesXML(self, subscriber):
tlines = self.GetCurrentTimeline()
#
# Only "video" is supported right now
#
mediaContainer = et.Element("MediaContainer")
if subscriber.commandID is not None:
mediaContainer.set("commandID", str(subscriber.commandID))
mediaContainer.set("location", tlines["location"])
lineEl = et.Element("Timeline")
for key, value in tlines.items():
lineEl.set(key, str(value))
mediaContainer.append(lineEl)
return mediaContainer
def GetCurrentTimeline(self):
# https://github.com/plexinc/plex-home-theater-public/blob/pht-frodo/plex/Client/PlexTimelineManager.cpp#L142
options = {
"location": "navigation",
"state": playerManager.get_state(),
"type": "video"
}
controllable = []
video = playerManager._video
player = playerManager._player
if video and player:
media = playerManager._video.parent
options["location"] = "fullScreenVideo"
options["time"] = player.position * 1e3
options["ratingKey"] = video.get_video_attr("ratingKey")
options["key"] = video.get_video_attr("key")
options["containerKey"] = video.get_video_attr("key")
#.........这里部分代码省略.........
示例3: main
# 需要导入模块: from utils import Timer [as 别名]
# 或者: from utils.Timer import elapsed [as 别名]
def main(argv):
# rma, drug, stress = load_data()
rma, label = data.load_mdd_data()
alpha_range = np.logspace(-2, 7, 10)
l1_ratio_range = np.arange(0.0, 1.0, 0.1)
en_param_grid = dict(alpha=alpha_range, l1_ratio=l1_ratio_range)
c_range = np.logspace(-2, 7, 10)
gamma_range = np.logspace(-6, 3, 10)
svm_param_grid = dict(gamma=gamma_range, C=c_range)
logit_param_grid = dict(C=c_range)
test_size = float(argv[1])
n_iter = int(argv[2])
n_folds = int(argv[3])
target = argv[4]
classifier = argv[5]
pca_components = int(argv[7])
log = {
"target": target,
"pca": {"n_components": pca_components},
"split": {"type": "StratifiedShuffleSplit", "n_iter": n_iter, "test_size": test_size},
"cross_val": {"n_folds": n_folds},
"classifier": classifier,
}
# if target == 'drug':
# target = drug
# else:
# target = stress
pca = PCA(n_components=pca_components)
if classifier == "svm":
clf = SVC()
param_grid = svm_param_grid
grid_search = True
elif classifier == "en":
clf = SGDClassifier(loss="log", penalty="elasticnet", n_jobs=1)
param_grid = en_param_grid
grid_search = True
elif classifier == "logit":
clf = LogisticRegression()
param_grid = logit_param_grid
grid_search = True
timer = Timer()
print("\nStarting..." + " ".join(argv))
pprint(log)
split = StratifiedShuffleSplit(label[target], n_iter=n_iter, test_size=test_size)
if grid_search:
clf = GridSearchCV(clf, param_grid=param_grid, cv=n_folds, n_jobs=1)
pipeline = Pipeline([("pca", pca), ("clf", clf)])
accuracy = cross_val_score(pipeline, rma, y=label[target], scoring="accuracy", cv=split, n_jobs=n_iter, verbose=1)
print("\n{}: Accuracy: {:.2%} +/- {:.2%}".format(timer.elapsed(), np.nanmean(accuracy), np.nanstd(accuracy)))
log["results"] = {"accuracy": {"scores": accuracy.tolist(), "mean": accuracy.mean(), "std": accuracy.std()}}
log["time"] = timer.elapsed()
# results = [dict(log, accuracy=acc) for acc in accuracy]
# log_results(results)
# save_results(results, folder=argv[6], filename='results_new.json')
save_experiment(log, folder=argv[6])
示例4: dict
# 需要导入模块: from utils import Timer [as 别名]
# 或者: from utils.Timer import elapsed [as 别名]
if args.clf == 'logit':
pass
elif args.clf == 'en':
alpha_range = np.logspace(-2, 7, 10)
l1_ratio_range = np.arange(0., 1., 10)
param_grid = dict(alpha=alpha_range, l1_ratio=l1_ratio_range)
clf = SGDClassifier(loss='log', penalty='elasticnet')
grid = GridSearchCV(clf, param_grid=param_grid, cv=args.n_folds, n_jobs=-1)
pipeline.append(('en', grid))
else:
result['error'] = '{} is not a valid classifier.'.format(args.clf)
save_experiment(result, folder=args.results_path, error=True,
verbose=args.verbose)
pipeline = Pipeline(pipeline)
timer = Timer()
accuracy = cross_val_score(pipeline, betas, y=target, scoring='accuracy', cv=split, n_jobs=1)
result['time'] = timer.elapsed()
result['results'] = {
'accuracy': {
'scores': accuracy.tolist(),
'mean': accuracy.mean(),
'std': accuracy.std()
}
}
save_experiment(result, folder=args.results_path, verbose=args.verbose)
示例5: PlayerManager
# 需要导入模块: from utils import Timer [as 别名]
# 或者: from utils.Timer import elapsed [as 别名]
class PlayerManager(object):
"""
Manages the relationship between a ``Player`` instance and a ``Media``
item. This is designed to be used as a singleton via the ``playerManager``
instance in this module. All communication between a caller and either the
current ``player`` or ``media`` instance should be done through this class
for thread safety reasons as all methods that access the ``player`` or
``media`` are thread safe.
"""
def __init__(self):
self._player = None
self._video = None
self._lock = RLock()
self.last_update = Timer()
self.__part = 1
@synchronous('_lock')
def update(self):
if self._video and self._player:
# Check to see if we need to turn the display on
if not display.is_on:
log.debug("PlayerManager::update display is off, turning on")
self._player.pause()
display.power_on()
if self.last_update.elapsed() > SCROBBLE_INTERVAL and not self.is_paused():
if not self._video.played:
position = self._player.position * 1e3 # In ms
duration = self._video.get_duration()
if float(position)/float(duration) >= COMPLETE_PERCENT:
log.info("PlayerManager::update setting media as watched")
self._video.set_played()
else:
log.info("PlayerManager::update updating media position")
self._video.update_position(position)
self.last_update.restart()
@synchronous('_lock')
def play(self, video, offset=0):
self.stop()
args = []
if offset > 0:
args.extend(("-l", str(offset)))
audio_idx = video.get_audio_idx()
if audio_idx is not None:
log.debug("PlayerManager::play selecting audio stream index=%s" % audio_idx)
args.extend(["-n", audio_idx])
sub_idx = video.get_subtitle_idx()
if sub_idx is not None:
log.debug("PlayerManager::play selecting subtitle index=%s" % sub_idx)
args.extend(["-t", sub_idx])
else:
# No subtitles -- this is pretty hacky
log.debug("PlayerManager::play disabling subtitles")
args.extend(["--subtitles", "/dev/null"])
# TODO: Check settings for transcode settings...
url = video.get_playback_url()
if not url:
log.error("PlayerManager::play no URL found")
return
self._player = Player(mediafile=url, args=args, start_playback=True, finished_callback=self.finished_callback)
self._video = video
@synchronous('_lock')
def stop(self):
if not self._video or not self._player:
return
log.debug("PlayerManager::stop stopping playback of %s" % self._video)
osd.hide()
self._player.stop()
self._player = None
self._video = None
@synchronous('_lock')
def get_volume(self, percent=False):
if self._player:
if not percent:
return self._player._volume
return self._player._VOLUME_STEPS.index(self._player._volume)/float(len(self._player._VOLUME_STEPS))
@synchronous('_lock')
def toggle_pause(self):
if self._player:
self._player.toggle_pause()
if self.is_paused() and self._video:
log.debug("PlayerManager::toggle_pause showing OSD")
try:
duration = int(int(self._video.get_duration())*1e-3)
except:
duration = 0
#.........这里部分代码省略.........