本文整理汇总了Python中divmod函数的典型用法代码示例。如果您正苦于以下问题:Python divmod函数的具体用法?Python divmod怎么用?Python divmod使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了divmod函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __divmod__
def __divmod__(self, other):
if self.__is_negative() and other.__is_negative():
q, r = divmod(-self, -other)
return q, -r
elif self.__is_negative():
q, r = divmod(-self, other)
q, r = -q, -r
if r != zero:
r += other
q -= one
return q, r
elif other.__is_negative():
q, r = divmod(self, -other)
q = -q
if r != zero:
r += other
q -= one
return q, r
else: # neither self nor other is negative
s1 = self
b = one
q, r = zero, zero
while s1 >= b:
b <<= one
while b > one:
b >>= one
q, r = q << one, r << one
if s1 >= b:
s1 -= b
r += one
if r >= other:
r -= other
q += one
return (q, r)
示例2: add_automatic_comment
def add_automatic_comment(self):
if self.fixed is True:
text = (
"This %s has been scheduled for fixed downtime from %s to %s. "
"Notifications for the %s will not be sent out during that time period." % (
self.ref.my_type,
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.start_time)),
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.end_time)),
self.ref.my_type)
)
else:
hours, remainder = divmod(self.duration, 3600)
minutes, seconds = divmod(remainder, 60)
text = ("This %s has been scheduled for flexible downtime starting between %s and %s "
"and lasting for a period of %d hours and %d minutes. "
"Notifications for the %s will not be sent out during that time period." % (
self.ref.my_type,
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.start_time)),
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.end_time)),
hours, minutes, self.ref.my_type)
)
if self.ref.my_type == 'host':
comment_type = 1
else:
comment_type = 2
c = Comment(self.ref, False, "(Nagios Process)", text, comment_type, 2, 0, False, 0)
self.comment_id = c.id
self.extra_comment = c
self.ref.add_comment(c)
示例3: timeago
def timeago(secs, precision=0):
"""
:param int secs: number of seconds "ago".
:param int precision: optional decimal precision of returned seconds.
Pass a duration of time and return human readable shorthand, fe::
>>> asctime(126.32)
' 2m 6s',
>>> asctime(70.9999, 2)
' 1m 10.99s'
"""
# split by days, mins, hours, secs
years = weeks = days = mins = hours = 0
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
years, weeks = divmod(weeks, 52)
((num1, num2), (label1, label2)) = (
((years, weeks), (u'y', u'w')) if years >= 1.0 else
((weeks, days), (u'w', u'd')) if weeks >= 1.0 else
((days, hours), (u'd', u'h')) if days >= 1.0 else
((hours, mins), (u'h', u'm')) if hours >= 1.0 else
((mins, secs), (u'm', u's')))
return (u'%2d%s%2.*f%s' % (num1, label1, precision, num2, label2,))
示例4: timedelta
def timedelta(pub_date):
delta = datetime.now(tz=timezone.utc) - pub_date
secs = delta.total_seconds()
days, remainder = divmod(secs, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
days_str = ''
if days != 0:
days_str = '{:0.0f} day'.format(days)
if days > 1: days_str += 's'
days_str += ', '
hours_str = ''
if hours != 0:
hours_str = '{:0.0f} hour'.format(hours)
if hours > 1: hours_str += 's'
hours_str += ', '
minutes_str = ''
if minutes != 0:
minutes_str = '{:0.0f} minute'.format(minutes)
if minutes > 1: minutes_str += 's'
minutes_str += ', '
else:
minutes_str = 'seconds'
delta_str = '{}{}{}'.format(days_str, hours_str, minutes_str)
return delta_str.strip(', ') + ' ago'
示例5: timeago
def timeago(secs, precision=0):
"""
Pass float or int in seconds, and return string of 0d 0h 0s format,
but only the two most relative, fe:
asctime(126.32) returns 2m6s,
asctime(10.9999, 2) returns 10.99s
"""
# split by days, mins, hours, secs
years, weeks, days, mins, hours = 0, 0, 0, 0, 0
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
years, weeks = divmod(weeks, 52)
years, weeks, days, hours, mins = (
int(years), int(weeks), int(days), int(hours), int(mins))
# return printable string
if years > 0:
return '%3s%-3s' % (str(years)+'y', str(weeks)+'w',)
if weeks > 0:
return '%3s%-3s' % (str(weeks)+'w', str(days)+'d',)
if days > 0:
return '%3s%-3s' % (str(days)+'d', str(hours)+'h',)
elif hours > 0:
return '%3s%-3s' % (str(hours)+'h', str(mins)+'m',)
elif mins > 0:
return '%3s%-3s' % (str(mins)+'m', str(int(secs))+'s',)
else:
fmt = '%.'+str(precision)+'f s'
return fmt % secs
示例6: _mods
def _mods(i, mod):
(q, r) = divmod(i, mod)
while True:
yield r
if not q:
break
(q, r) = divmod(q, mod)
示例7: clusters
def clusters(args):
"""Load and index subject clusters."""
global session, db
lgr = session.logger
lgr.log_info(session, 'Accumulating subject clusters...')
start = time.time()
recordStore = db.get_object(session, 'recordStore')
clusDocFac = db.get_object(session, 'clusterDocumentFactory')
for rec in recordStore:
clusDocFac.load(session, rec)
session.database = '{0}_cluster'.format(session.database)
clusDb = server.get_object(session, session.database)
# Remove existing live index
clusDb.clear_indexes(session)
clusFlow = clusDb.get_object(session, 'buildClusterWorkflow')
clusFlow.process(session, clusDocFac)
(mins, secs) = divmod(time.time() - start, 60)
(hours, mins) = divmod(mins, 60)
lgr.log_info(
session,
'Subject Clustering complete ({0:.0f}h {1:.0f}m {2:.0f}s)'
''.format(hours, mins, secs)
)
# return session.database to the default (finding aid) DB
session.database = db.id
return 0
示例8: durationHuman
def durationHuman(seconds):
seconds = long(round(seconds))
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
years, days = divmod(days, 365.242199)
sdays = str(days)
syears = str(years)
sseconds = str(seconds).rjust(2, '0')
sminutes = str(minutes).rjust(2, '0')
shours = str(hours).rjust(2, '0')
duration = []
if years > 0:
duration.append('%s year' % syears + 's'*(years != 1) + ' ')
else:
if days > 0:
duration.append('%s day' % sdays + 's'*(days != 1) + ' ')
if hours > 0:
duration.append('%s:' % shours)
if minutes >= 0:
duration.append('%s:' % sminutes)
if seconds >= 0:
duration.append('%s' % sseconds)
return ''.join(duration)
示例9: test_time
def test_time(self):
t = datetime(1, 1, 1, 3, 30, 0)
deltas = np.random.randint(1, 20, 3).cumsum()
ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas])
df = DataFrame({'a': np.random.randn(len(ts)),
'b': np.random.randn(len(ts))},
index=ts)
ax = df.plot()
# verify tick labels
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for t, l in zip(ticks, labels):
m, s = divmod(int(t), 60)
h, m = divmod(m, 60)
xp = l.get_text()
if len(xp) > 0:
rs = time(h, m, s).strftime('%H:%M:%S')
self.assertEqual(xp, rs)
# change xlim
ax.set_xlim('1:30', '5:00')
# check tick labels again
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for t, l in zip(ticks, labels):
m, s = divmod(int(t), 60)
h, m = divmod(m, 60)
xp = l.get_text()
if len(xp) > 0:
rs = time(h, m, s).strftime('%H:%M:%S')
self.assertEqual(xp, rs)
示例10: as_hms
def as_hms(value):
"""Given a floating-point number of seconds, translates it to an
HH:MM:SS string."""
long_seconds = int(value)
(long_minutes, seconds) = divmod(long_seconds, 60)
(hours, minutes) = divmod(long_minutes, 60)
return "%d:%02d:%02d" % (hours, minutes, seconds)
示例11: _get_time_diff_formatted
def _get_time_diff_formatted(old, recent):
""" Formats the difference between two datetime objects """
diff = recent - old
days = diff.days
m, s = divmod(diff.seconds, 60)
h, m = divmod(m, 60)
return '{} days, {} hours, {} minutes, and {} seconds'.format(days, h, m, s)
示例12: _get_col_row
def _get_col_row(self, n):
if self._direction == "column":
col, row = divmod(n, self._nrows)
else:
row, col = divmod(n, self._ncols)
return col, row
示例13: _fix
def _fix(self):
if abs(self.microseconds) > 999999:
s = self.microseconds//abs(self.microseconds)
div, mod = divmod(self.microseconds*s, 1000000)
self.microseconds = mod*s
self.seconds += div*s
if abs(self.seconds) > 59:
s = self.seconds//abs(self.seconds)
div, mod = divmod(self.seconds*s, 60)
self.seconds = mod*s
self.minutes += div*s
if abs(self.minutes) > 59:
s = self.minutes//abs(self.minutes)
div, mod = divmod(self.minutes*s, 60)
self.minutes = mod*s
self.hours += div*s
if abs(self.hours) > 23:
s = self.hours//abs(self.hours)
div, mod = divmod(self.hours*s, 24)
self.hours = mod*s
self.days += div*s
if abs(self.months) > 11:
s = self.months//abs(self.months)
div, mod = divmod(self.months*s, 12)
self.months = mod*s
self.years += div*s
if (self.hours or self.minutes or self.seconds or self.microseconds or
self.hour is not None or self.minute is not None or
self.second is not None or self.microsecond is not None):
self._has_time = 1
else:
self._has_time = 0
示例14: draw_peers
def draw_peers(state):
window_height = state['y'] - 4
win_peers = curses.newwin(window_height, 75, 3, 0)
offset = state['peerinfo_offset']
for index in xrange(offset, offset+window_height):
if index < len(state['peerinfo']):
peer = state['peerinfo'][index]
condition = (index == offset+window_height-1) and (index+1 < len(state['peerinfo']))
condition = condition or ( (index == offset) and (index > 0) )
if condition:
# scrolling up or down is possible
win_peers.addstr(index-offset, 3, "...")
else:
if peer['inbound']:
win_peers.addstr(index-offset, 1, 'I')
elif 'syncnode' in peer:
if peer['syncnode']:
# syncnodes are outgoing only
win_peers.addstr(index-offset, 1, 'S')
addr_str = peer['addr'].replace(".onion","").replace(":" + g.node_port,"").replace(":" + g.node_port_test,"").strip("[").strip("]")
# truncate long ip addresses (ipv6)
addr_str = (addr_str[:17] + '...') if len(addr_str) > 20 else addr_str
win_peers.addstr(index-offset, 3, addr_str)
win_peers.addstr(index-offset, 24, peer['subver'].strip("/").replace("Satoshi:","Sat")[:11])
mbrecv = "% 7.1f" % ( float(peer['bytesrecv']) / 1048576 )
mbsent = "% 7.1f" % ( float(peer['bytessent']) / 1048576 )
win_peers.addstr(index-offset, 35, mbrecv + 'MB')
win_peers.addstr(index-offset, 45, mbsent + 'MB')
timedelta = int(time.time() - peer['conntime'])
m, s = divmod(timedelta, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
time_string = ""
if d:
time_string += ("%d" % d + "d").rjust(3) + " "
time_string += "%02d" % h + ":"
elif h:
time_string += "%02d" % h + ":"
time_string += "%02d" % m + ":"
time_string += "%02d" % s
win_peers.addstr(index-offset, 55, time_string.rjust(12))
if 'syncheight' in peer:
win_peers.addstr(index-offset, 69, str(peer['syncheight']).rjust(6))
win_peers.refresh()
示例15: format_number
def format_number(number, unit=None, units=None):
plural = (abs(number) > 1)
if number >= 10000:
pow10 = 0
x = number
while x >= 10:
x, r = divmod(x, 10)
pow10 += 1
if r:
break
if not r:
number = '10^%s' % pow10
if isinstance(number, int) and number > 8192:
pow2 = 0
x = number
while x >= 2:
x, r = divmod(x, 2)
pow2 += 1
if r:
break
if not r:
number = '2^%s' % pow2
if not unit:
return str(number)
if plural:
if not units:
units = unit + 's'
return '%s %s' % (number, units)
else:
return '%s %s' % (number, unit)