本文整理汇总了Python中util.Timer.start方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.start方法的具体用法?Python Timer.start怎么用?Python Timer.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类util.Timer
的用法示例。
在下文中一共展示了Timer.start方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _send_message
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
def _send_message(self, message, success=None, error=None, *args, **kwargs):
if message.startswith('msg'):
try:
how_long = int(message.split()[1])
t = Timer(how_long, self.protocol.incomming_message, self.self_buddy, u"Here's your message %ds later" % how_long)
t.start()
except Exception:
pass
示例2: generate_sudoku
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
def generate_sudoku(self, target = 25):
search = AStarSearch()
base_sudoku = self.generate_full_sudoku()
timer = Timer()
if self.__kind == 'reverse':
problem = ReverseSudokuGenerationProblem(Sudoku(), target, self.solver)
else:
problem = SudokuGenerationProblem(base_sudoku, target, self.solver)
timer.start()
node, cnt_explored = search.search(problem, h = lambda n: problem.value(n.state))
time = timer.stop()
return node.state, len(node.state), cnt_explored, time
示例3: do_POST
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
def do_POST(self):
t = Timer()
t.start()
response = 200
result = {}
try:
content_length = int(self.headers.getheader('content-length'))
req = json.loads(self.rfile.read(content_length))
print req
req_type = req['type']
result = None
if req_type == 'catalog':
result = json.dumps(self.server.catalog)
elif req_type == 'execute':
task = req['args']['task']
json.dumps(BasicExecutor(self.server.cache, task).execute())
elif req_type == 'lookup':
uuid = req['args']['uuid']
result = self.server.cache[uuid]
if type(result) is pd.DataFrame:
page_size = int(req['args']['page_size'])
page_num = int(req['args']['page_num'])
i = page_size * page_num
j = i + page_size
result = result[i:j]
result = result.to_json()
except:
print traceback.format_exc()
response = 500
result = '{}'
t.stop()
self.send_response(response)
self.send_header('Content-type','application/json')
self.end_headers()
self.wfile.write(result)
print 'Run Time:', t.time()
示例4: DigsbyConnect
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
class DigsbyConnect(TimeoutSocketOne):
_SERVERTIMEOUT = 8
def stale_connection(self):
if getattr(self, '_triumphant', False):
log.info('stale_connection was called but i already won! yayayay')
else:
log.info('%r had a stale connection. Calling do_fail (%r) with a connlost error', self, self.do_fail)
self.do_fail(DigsbyLoginError('connlost'))
def succ(self):
generator = self.do_login()
self._timeouttimer = Timer(self._SERVERTIMEOUT, self.stale_connection)
self._timeouttimer.start()
self.run_sequence( generator )
@lock
def handle_error(self, e=None):
if hasattr(self, '_timeouttimer'):
self._timeouttimer.stop()
TimeoutSocketOne.handle_error(self)
@lock
def handle_expt(self):
if hasattr(self, '_timeouttimer'):
self._timeouttimer.stop()
TimeoutSocketOne.handle_expt(self)
@lock
def handle_close(self):
if hasattr(self, '_timeouttimer'):
self._timeouttimer.stop()
TimeoutSocketOne.handle_close(self)
def do_login(self):
login_str = make_pstring(self.cid) + make_pstring(self.un) + make_pstring(self.password)
codelen = yield (4, login_str)
codelen = unpack('!I', codelen)[0]
if codelen <= 0:
raise DigsbyLoginError('client')
code = yield (codelen, '')
try:
if code == 'success':
cookielen = unpack('!I', (yield (4, '')))[0]
cookie = yield (cookielen, '')
log.debug('Got cookie: %r', cookie)
serverslen = unpack('!I', (yield (4, '')))[0]
servers = yield (serverslen, '')
log.debug('Got servers: %r', servers)
servers = servers.split(' ')
self.cookie = cookie
self.servers = servers
self._triumphant = True
return
elif code == 'error':
log.debug('Got error!')
reasonlen = unpack('!I', (yield (4, '')))[0]
reason = yield (reasonlen, '')
log.debug('Got error reason: %r', reason)
raise DigsbyLoginError(reason)
else:
log.debug('Unknown error occurred! blaming the client!')
raise DigsbyLoginError('client')
except DigsbyLoginError, e:
if e.reason == 'server':
log.debug('Got "upgrading digsby" error code. Sleeping.')
import time; time.sleep(POLL_SLEEP_TIME)
raise e
except Exception, e:
print_exc()
raise DigsbyLoginError('client')
示例5: OscarTimeoutSocket
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
class OscarTimeoutSocket(common.socket):
def tryconnect(self, ips, on_connect, on_fail, timeout = 2.0):
self._connectedonce = False
info('tryconnect Y=%r, N=%r', on_connect, on_fail)
self.ips = self.iptuples(ips)
if not callable(on_connect) or not callable(on_fail):
raise TypeError( 'on_connect and on_fail must be callables' )
self.on_connect = on_connect
self.on_fail = on_fail
self.timetowait = timeout
self._tryagain(timeout)
def tryaccept(self, addr, on_connect, on_fail, timeout = 1.5):
self._connectedonce = False
info('tryaccept Y=%r, N=%r', on_connect, on_fail)
self.ips = ()
self.on_connect = on_connect
self.on_fail = on_fail
info('listening for a connection at %s:%d', *addr)
self.bind( addr )
self.listen(1)
if timeout:
info('timeout in %r secs', timeout)
def dotimeout():
info('TIMEOUT. calling %r', self.on_fail)
self.on_fail()
self.timeout = Timer(timeout, dotimeout)
self.timeout.start()
def _tryagain(self, timetowait):
# Try the next IP.
addr = self.ips.pop(0)
if len(self.ips) > 0:
timeoutfunc = partial(self._tryagain, timetowait)
else:
# This is the last one.
timeoutfunc = self.on_fail
self.timeout = Timer(timetowait, timeoutfunc)
info('%r attempting conn: %s:%d', self, *addr)
self.make_socket()
self.connect(addr, error=timeoutfunc)
info('timeout is %r seconds...', timetowait)
if self.timeout is not None:
self.timeout.start()
def handle_expt(self):
info('handle_expt in %r', self)
self.handle_disconnect()
def handle_error(self, e=None):
info('handle_error in %r', self)
import traceback
traceback.print_exc()
if not self._connectedonce:
self.handle_disconnect()
else:
self.close()
def handle_disconnect(self):
self.cancel_timeout()
self.close()
if len(self.ips) > 0:
info('got an error, trying next ip immediately: ' + \
repr(self.ips[0]))
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self._tryagain(self.timetowait)
elif not self._connectedonce:
info('no more ips to attempt, calling on_fail (%r)', self.on_fail)
self.on_fail()
def handle_connect(self):
info('connected!')
self.cancel_timeout()
#self.handle_disconnect = lambda: None
self._connectedonce = True
self.on_connect()
self.on_fail = Sentinel
def handle_accept(self):
self.cancel_timeout()
conn, address = self.accept()
info('%r connection accepted (%r), canceling timeout and calling %r', self, address, self.on_connect)
self._connectedonce = True
self.on_connect(conn)
def cancel_timeout(self):
# Cancel any timeout.
#.........这里部分代码省略.........
示例6: main
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
def main():
n_epoch = params.n_epoch
save_weight_filename = params.save_weight_file
do_validation_only = params.test_only
gen_n_text_samples = params.gen_n_samples
learning_rate = params.learning_rate
training_t = Timer()
validation_t = Timer()
best_pp = None
prev_loss = None
prev_acc = None
patience = MAX_PATIENCE
if params.mode == 'C2W2C':
def c2w2c_weighted_objective(fn):
def weighted(y_true, y_pred, weights, mask=None):
assert mask is None
assert weights is not None
score_array = fn(y_true, y_pred)
# reduce score_array to same ndim as weight array
ndim = K.ndim(score_array)
weight_ndim = K.ndim(weights)
score_array = K.mean(score_array, axis=list(range(weight_ndim, ndim)))
# apply sample weighting
score_array *= weights
word_scores = K.sum(score_array, axis=-1)
return K.mean(word_scores)
return weighted
# by default Keras calculates only mean which is not correct because
# word loss = sum(char losses), thus we need to monkey batch the
# weighted_objective function to return correct loss for C2W2C model
# ATTENTION: this might not work in later Keras versions, only tested with 1.0.5
ket.weighted_objective = c2w2c_weighted_objective
# ======== PREPARE MODELS AND DATA ========
t_model, v_model, training_data, validation_data, gen_text = prepare_env(params)
def validate_model(best):
if gen_n_text_samples:
print '\nGenerating %d text samples...' % gen_n_text_samples
n_seed = 100
start = max(0, np.random.randint(0, training_dataset.n_words - n_seed))
seed = training_dataset.get_words()[start: start + n_seed]
gen_text(seed=seed, how_many=gen_n_text_samples)
print '\nValidating model...'
validation_t.start()
v_model.set_weights(t_model.get_weights())
v_model.reset_states()
n_v_samples, gen_v = validation_data[0]()
loss, _ = v_model.evaluate_generator(gen_v, n_v_samples)
pp = np.exp(loss)
val_elapsed, val_tot = validation_t.lap()
validation_info = '''Validation result:
- Model loss: %f
- Perplexity: %f %s
- OOV rate: %f
- Validation took: %s
- Total validation: %s
''' % (loss, pp, delta_str(pp, best), validation_data[1], val_elapsed, val_tot)
info(validation_info)
return pp
if do_validation_only:
validate_model(None)
sys.exit(0)
print '\nTraining model...'
for epoch in range(1, n_epoch + 1):
print '=== Epoch %d ===' % epoch
training_t.start()
n_t_samples, gen_t = training_data[0]()
t_model.reset_states()
callbacks = []
if save_weight_filename:
callbacks += [ModelCheckpoint(save_weight_filename, monitor='loss', mode='min', save_best_only=True)]
h = t_model.fit_generator(generator=gen_t,
samples_per_epoch=n_t_samples,
callbacks=callbacks,
nb_epoch=1,
verbose=1)
fit_elapsed, fit_tot = training_t.lap()
loss = h.history['loss'][0]
acc = h.history['acc'][0]
epoch_info = '''Epoch %d summary at %s:
- Model loss: %f %s
- Model accuracy: %f %s
- Perplexity: %f
#.........这里部分代码省略.........
示例7: generate_sudoku
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
def generate_sudoku(self, target = 25):
'''
Genera un sudoku rimuovendo casualemente dei valori fino a che non si ottiene un livello di difficoltà pari a quello specificato dal parametro target
Ogni 1000 Backtrack ripristina metà valori scelti casualemente tra quelli rimossi
returns (current_sudoku, len(current_sudoku), cnt_backtrack, time)
'''
base_sudoku = self.generate_full_sudoku()
current_sudoku = Sudoku(base_sudoku.get_dict())
cache = [] # Cache dei valori per il backtrack
cnt_backtrack = 0
cnt_step = 0
single_solution = True;
timer = Timer()
timer.start()
while True:
cnt_step += 1
#print '----------------------------'
#print 'Cache size', len(cache)
# Test di uscita
if len(current_sudoku) == target and single_solution:
break;
#print 'Current values count: ', len(current_sudoku)
#print 'Single solution: ', single_solution
#print 'Backtrack', cnt_backtrack
# Quanti valori togliere
n = len(current_sudoku) / 20
#print 'Prova a rimuovere %d valori' %n
assert n != 0
# Togli i numeri
for i in range(n):
key = random.choice(current_sudoku.filled_cell())
cache.append(key)
current_sudoku.clear_cell(key)
#print 'Cache size', len(cache)
# Verifica l'unicità della soluzione
(sols, b, t) = self.solver.solve(current_sudoku, max_sol = 2)
# Se unica, continua
if len(sols) == 1:
single_solution = True
#print "Rimossi con successo %d elementi" % n
continue
# Se più di una, torna indietro
else:
#print "Backtrack, sols: %d" % len(sols)
single_solution = False
cnt_backtrack += 1
# Ripristina gli ultimi n valori tolti
#print 'Restored cache size', len(cache)
for i in range(n):
# Ripristina gli utlimi elementi tolti
k = cache[-1]
current_sudoku.set_cell(k, base_sudoku.cell(k))
cache.pop(-1)
if cnt_backtrack % 1000 == 0:
#print 'Riprista casualmente metà cache'
for i in range(len(cache)/2):
# Ripristina gli utlimi elementi tolti
idx = random.randint(0, len(cache)-1)
k = cache[idx]
current_sudoku.set_cell(k, base_sudoku.cell(k))
cache.pop(idx)
#print '----------------------------'
#print 'Backtrack necessari: ', cnt_backtrack
time = timer.stop()
return current_sudoku, len(current_sudoku), cnt_step, time
示例8: __init__
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
class ElectrumGui:
def __init__(self, config, network):
set_language(config.get('language'))
self.network = network
self.config = config
self.windows = []
self.efilter = OpenFileEventFilter(self.windows)
self.app = QApplication(sys.argv)
self.app.installEventFilter(self.efilter)
self.timer = Timer()
self.app.connect(self.app, QtCore.SIGNAL('new_window'), self.start_new_window)
def new_window(self, config):
self.app.emit(SIGNAL('new_window'), config)
def load_wallet_file(self, path):
self.app.emit(SIGNAL('new_window'), self.config, path)
def start_new_window(self, config, path=None):
if path is None:
path = config.get_wallet_path()
for w in self.windows:
if w.config.get_wallet_path() == path:
w.bring_to_top()
break
else:
w = ElectrumWindow(config, self.network, self)
w.connect_slots(self.timer)
w.load_wallet_file(path)
w.show()
self.windows.append(w)
url = config.get('url')
if url:
w.pay_to_URI(url)
return w
def main(self):
self.timer.start()
last_wallet = self.config.get('gui_last_wallet')
if last_wallet is not None and self.config.get('wallet_path') is None:
if os.path.exists(last_wallet):
self.config.cmdline_options['default_wallet_path'] = last_wallet
# main window
self.current_window = self.main_window = self.start_new_window(self.config)
# plugins interact with main window
run_hook('init_qt', self)
signal.signal(signal.SIGINT, lambda *args: self.app.quit())
# main loop
self.app.exec_()
# clipboard persistence. see http://www.mail-archive.com/[email protected]/msg17328.html
event = QtCore.QEvent(QtCore.QEvent.Clipboard)
self.app.sendEvent(self.app.clipboard(), event)
示例9: Executor
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
class Executor(Process):
def __init__(self, catalog, results, task):
Process.__init__(self)
self.catalog = catalog
self.results = results
self.task = task
self.timer = Timer()
def get_result(self, uuid):
result = self.results[uuid]
while result.complete == 0.0:
time.sleep(0.0005)
result = self.results[uuid]
return result
def wait(self, uuid):
while self.results[uuid].complete == 0.0:
time.sleep(0.0005)
def run(self):
self.timer.start()
try:
if isinstance(self.task, ClassifyTask):
self.classify()
elif isinstance(self.task, CorrelateTask):
self.correlate()
elif isinstance(self.task, DifferenceTask):
self.difference()
elif isinstance(self.task, FeatureSelectTask):
self.feature_select()
elif isinstance(self.task, FrequentItemsetsTask):
self.frequent_itemsets()
elif isinstance(self.task, IntersectTask):
self.intersect()
elif isinstance(self.task, LoadTask):
self.load()
elif isinstance(self.task, MergeTask):
self.merge()
elif isinstance(self.task, ProjectTask):
self.project()
elif isinstance(self.task, SelectTask):
self.select()
elif isinstance(self.task, UnionTask):
self.union()
else:
raise NotImplementedError()
except Exception as e:
print str(e)
result = ErrorResult(self.task, str(e))
self.results[self.task.uuid] = result
self.timer.stop()
print 'task' + str(self.task.uuid) + ': ' + str(self.timer.time()) + 's'
def classify(self):
raise NotImplementedError()
def correlate(self):
raise NotImplementedError()
def difference(self):
raise NotImplementedError()
def feature_select(self):
raise NotImplementedError()
def frequent_itemsets(self):
raise NotImplementedError()
def intersect(self):
raise NotImplementedError()
def load(self):
raise NotImplementedError()
def merge(self):
raise NotImplementedError()
def project(self):
raise NotImplementedError()
def select(self):
raise NotImplementedError()
def union(self):
raise NotImplementedError()
示例10: TimeoutSocketOne
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
class TimeoutSocketOne(common.socket):
'''
single socket timeout socket
'''
@lock
def try_connect(self, address, succ, fail, time_to_wait, provide_init):
provide_init(self)
self.real_success = succ
self.fail = fail
self.dead = False
self.data = None
#make new socket
self.make_socket()
self.timeoutvalid = True
self.timeout = Timer(time_to_wait, self.handle_timeout)
self.timeout.start()
print '*'*40
from util import funcinfo
print funcinfo(self.connect)
print '*'*40
self.connect(address, error=self.do_fail)
#do connect with callback
#success indicates that the socket started, but guarantees nothing
#error indicates that there was a problem, should try to close + do fail
def succ(self):
info('succ')
self.real_success()
@lock
def do_fail(self, *a, **k):
info('do_fail')
if self.timeout is not None:
self.timeout.cancel()
self.timeout = None
self.timeoutvalid = False
self.close()
print a, k
self.fail(*a,**k)
@lock
def handle_connect(self):
info('CONNECT')
if self.timeout is not None:
self.timeout.cancel()
self.timeout = None
self.timeoutvalid = False
self.succ()
#cancel timeout
#success
@lock
def handle_timeout(self):
info('TIMEOUT')
#mark as dead
if self.timeoutvalid:
if self.timeout is not None:
self.timeout.cancel()
self.timeout = None
self.timeoutvalid = False
self.close()
self.dead = True
self.fail()
@lock
def collect_incoming_data(self, data):
self.data += data
@lock
def __error(self):
olddead = self.dead
self.dead = True
if self.timeout is not None:
self.timeout.cancel()
self.timeout = None
self.timeoutvalid = False
#cancel timeout
self.close()
if not olddead:
self.fail()
def handle_error(self, e=None):
info('ERROR: %r', e)
import traceback;traceback.print_exc()
self.__error()
def handle_expt(self):
info('EXPT')
self.__error()
def handle_close(self):
info('CLOSE')
self.__error()
示例11: TimeoutSocket
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import start [as 别名]
class TimeoutSocket(common.socket):
def tryconnect(self, ips, on_connect, on_fail, timeout=2.0):
'''
Setup for a new set of ips and start the connect routine
@param ips:
@param on_connect:
@param on_fail:
@param timeout:
'''
self.cancel_timeout()
self.timetowait = timeout
self.on_connect = on_connect
self.on_fail = on_fail
self._ips = iptuples(ips)
self.attempts = 0
self._accepting = False
self.try_connect()
def try_connect(self):
'Do the connection routine.'
addr = self._ips[self.attempts]
log.warning('tryconnect: %r', (addr,))
self.attempts += 1
self.timeout = Timer(self.timetowait, lambda s=self.socket: self.handle_timeout(s))
self.make_socket()
if self.timeout is not None:
self.timeout.start()
def succ(*a, **k):
log.info("WIN")
def fail(*a, **k):
log.info("FAIL")
self.connect(addr, success=succ, error=fail)
def tryaccept(self, addr, on_connect, on_fail, timeout = 1.5):
self._accepting = True
info('tryaccept Y=%r, N=%r', on_connect, on_fail)
self.on_connect = on_connect
self.on_fail = on_fail
info('listening for a connection at %r', (addr,))
self.make_socket()
common.socket.bind( self, addr )
self.listen(1)
if timeout:
info('timeout in %r secs', timeout)
self.timeout = Timer(timeout, lambda s=self.socket: self.handle_timeout(s))
self.timeout.start()
def handle_timeout(self, socket):
info('TIMEOUT %r', socket)
if socket is self.socket:
self.do_disconnect()
elif socket is not None:
socket.close()
def handle_expt(self):
info('handle_expt in %r', self)
self.do_disconnect()
def handle_error(self, e=None):
info('handle_error in %r', self)
import traceback
traceback.print_exc()
self.do_disconnect()
def do_disconnect(self):
'''
toss away the current connection
will try the next address immediately
'''
log.warning('do_disconnect')
self.cancel_timeout()
self.close()
if not self._accepting and self.attempts < len(self._ips):
self.try_connect()
else:
self.on_fail()
def handle_connect(self):
info('connected!')
self.cancel_timeout()
self.on_connect(self)
def handle_accept(self):
self.cancel_timeout()
conn, address = self.accept()
info('%r connection accepted (%r), canceling timeout and calling %r', self, address, self.on_connect)
self.on_connect(conn)
def cancel_timeout(self):
# Cancel any timeout.
if hasattr(self, 'timeout') and self.timeout is not None:
info('cancelling timeout')
self.timeout.cancel()
#.........这里部分代码省略.........