我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用math.modf()。
def OSCTimeTag(time): """Convert a time in floating seconds to its OSC binary representation """ if time > 0: fract, secs = math.modf(time) secs = secs - NTP_epoch binary = struct.pack('>LL', int(secs), int(fract * NTP_units_per_second)) else: binary = struct.pack('>LL', 0, 1) return binary ###### # # OSCMessage decoding functions # ######
def OSCTimeTag(time): """Convert a time in floating seconds to its OSC binary representation """ if time > 0: fract, secs = math.modf(time) secs = secs - NTP_epoch binary = struct.pack('>LL', long(secs), long(fract * NTP_units_per_second)) else: binary = struct.pack('>LL', 0L, 1L) return binary ###### # # OSCMessage decoding functions # ######
def jd_to_date(jd): jd = jd + 0.5 F, I = math.modf(jd) I = int(I) A = math.trunc((I - 1867216.25)/36524.25) if I > 2299160: B = I + 1 + A - math.trunc(A / 4.) else: B = I C = B + 1524 D = math.trunc((C - 122.1) / 365.25) E = math.trunc(365.25 * D) G = math.trunc((C - E) / 30.6001) day = C - E + F - math.trunc(30.6001 * G) if G < 13.5: month = G - 1 else: month = G - 13 if month > 2.5: year = D - 4716 else: year = D - 4715 return year, month, day # Find string between 2 strings
def _dict_to_tuple(d): '''Convert a dictionary to a time tuple. Depends on key values in the regexp pattern! ''' # TODO: Adding a ms field to struct_time tuples is problematic # since they don't have this field. Should use datetime # which has a microseconds field, else no ms.. When mapping struct_time # to gDateTime the last 3 fields are irrelevant, here using dummy values to make # everything happy. # retval = _niltime[:] for k,i in ( ('Y', 0), ('M', 1), ('D', 2), ('h', 3), ('m', 4), ): v = d.get(k) if v: retval[i] = int(v) v = d.get('s') if v: msec,sec = _modf(float(v)) retval[6],retval[5] = int(round(msec*1000)), int(sec) if d.get('neg', 0): retval[0:5] = [(x is not None or x) and operator.__neg__(x) for x in retval[0:5]] return tuple(retval)
def secondsInDayToTime(sssod): # 3600 seconds per hour (h, s) = divmod(sssod, 3600) (m, s) = divmod(s, 60) (fs, s) = math.modf( s ) return datetime.time(int(h), int(m), int(s), int(fs*1.0e6)) ## Generalized version of 'quote_split' as found in command.py ## This one defaults to "'" for opening and "'" for closing quotes ## but these characters can be overridden ## ## quote_split do not extract _words_ but split the ## string at the indicated character, ## provided the character is not inside ## quotes ## ## "aap 'noot 1; mies 2'; foo bar" ## results in: ## ["aap 'noot 1;mies 2'", "foo bar"]
def rotateHue ( self, hue_inc ): """ Rotates the hue value of Colz object """ if isinstance( hue_inc, int ): hue_inc /= 360.0 newhue = self.h + hue_inc if newhue > 1.0: newhue, whole = math.modf(newhue) # Keep decimal part if newhue < 0.0: newhue, whole = math.modf(newhue) # Keep decimal part newhue = 1.0 + newhue self.h = newhue self.hsl[0] = self.h self.hsla[0] = self.h self.updateFromHsl() # Return array of integer values
def testModf(self): self.assertRaises(TypeError, math.modf) def testmodf(name, result, expected): (v1, v2), (e1, e2) = result, expected if abs(v1-e1) > eps or abs(v2-e2): self.fail('%s returned %r, expected %r'%\ (name, result, expected)) testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0)) testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0)) self.assertEqual(math.modf(INF), (0.0, INF)) self.assertEqual(math.modf(NINF), (-0.0, NINF)) modf_nan = math.modf(NAN) self.assertTrue(math.isnan(modf_nan[0])) self.assertTrue(math.isnan(modf_nan[1]))
def testModf(self): self.assertRaises(TypeError, math.modf) def testmodf(name, result, expected): (v1, v2), (e1, e2) = result, expected if abs(v1-e1) > eps or abs(v2-e2): self.fail('%s returned %r, expected %r'%\ (name, (v1,v2), (e1,e2))) testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0)) testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0)) self.assertEqual(math.modf(INF), (0.0, INF)) self.assertEqual(math.modf(NINF), (-0.0, NINF)) modf_nan = math.modf(NAN) self.assertTrue(math.isnan(modf_nan[0])) self.assertTrue(math.isnan(modf_nan[1]))
def get_utc_offset() -> str: ''' function gets the difference between our timezones in hours and returns a string that will be put into the iso8601 format if we're 3 hours ahead, we will return +03:00 if we're 3 hours behind, we will return -03:00 :return: ''' now = datetime.datetime.now() local_hour = now.hour utc_hour = now.utcnow().hour utc_offset = local_hour - utc_hour str_preamble = '+' if utc_offset >= 0 else '-' # convert the fraction and the whole to a string. Works for ints and floats fraction, whole = math.modf(utc_offset) fraction = str(fraction)[2:].zfill(2) # from 0.5 get 05 only whole = str(int(whole)).zfill(2) return '{preamble}{whole}:{fraction}'.format(preamble=str_preamble, whole=whole, fraction=fraction)
def gradientLine( ctx, points_list, hsl_palette_list, loop_palette = True ): pal = hsl_palette_list[:] if loop_palette: pal.append( hsl_palette_list[0] ) # Duplicate first rgb = Colz.hslToRgb( *pal[0] ) ctx.set_source_rgb( *rgb ) for i in range( 2, len(points_list), 2 ): pal_pos = i * ( len(pal) - 1 ) / len(points_list) col_current = math.floor( pal_pos ) col_next = math.ceil( pal_pos ) frac, whole = math.modf( pal_pos ) if col_current == col_next: col_next = min( col_current + 1, len(pal) - 1 ) c_mix = Colz.interpolate( pal[col_current], pal[col_next], frac ) ctx.set_source_rgb( *c_mix.rgb ) ctx.move_to( points_list[i-2], points_list[i-1] ) ctx.line_to( points_list[i], points_list[i+1] ) ctx.stroke() # Pass caito ctx, list of points, list of colors ( colz )
def _fromtimestamp(cls, t, utc, tz): """Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well. """ frac, t = _math.modf(t) us = round(frac * 1e6) if us >= 1000000: t += 1 us -= 1000000 elif us < 0: t -= 1 us += 1000000 converter = _time.gmtime if utc else _time.localtime y, m, d, hh, mm, ss, weekday, jday, dst = converter(t) ss = min(ss, 59) # clamp out leap seconds if the platform has them return cls(y, m, d, hh, mm, ss, us, tz)
def save_clip_img(): img=cv.LoadImage('static/InterceptedIMG/clip.jpg') vertical_distance_decimal,vertical_distance_integer = math.modf(float(640)/19) parallel_distance_decimal,parallel_distance_integer = math.modf(float(480)/19) #print vertical_distance_decimal,vertical_distance_integer,parallel_distance_decimal,parallel_distance_integer draw_img = cv2.imread('static/InterceptedIMG/clip.jpg') for i in range(19): for j in range(19): cv2.rectangle(draw_img,(0+int(33.68*i),int(25.26*j)),(int(33.68*(i+1)),int(25.26*(j+1))),(0,255,0),1) cv2.imshow('image',draw_img) k = cv2.waitKey(0) & 0xFF if k == 27: cv2.destroyAllWindows() for i in range(19): for j in range(19): wn_position =(int(vertical_distance_integer*i)+int(vertical_distance_decimal*i),int(parallel_distance_integer*j)+int(parallel_distance_decimal*j)) es_position =(int(vertical_distance_integer*(i+1)+int(vertical_distance_decimal*i)),int(parallel_distance_integer*(j+1))+int(parallel_distance_decimal*j)) img_backup=cv.CloneImage(img) cv.SetImageROI(img_backup,(wn_position[0],wn_position[1],33,25)) cv.SaveImage('static/ClippedImg/%d_%d.jpg'%(j,i),img_backup)
def update_index_t_info (starttime, samples, sps) : global DAS_INFO #tdoy = timedoy.TimeDOY () ph5file = EXREC.filename ph5path = '/Experiment_g/Receivers_g/' + EXREC.ph5_g_receivers.current_g_das._v_name das = ph5path[32:] stoptime = starttime + (float (samples) / float (sps)) di = Index_t_Info (das, ph5file, ph5path, starttime, stoptime) if not DAS_INFO.has_key (das) : DAS_INFO[das] = [] DAS_INFO[das].append (di) logging.info ("DAS: {0} File: {1} First Sample: {2} Last Sample: {3}".format (das, ph5file, time.ctime (starttime), time.ctime (stoptime))) #startms, startsecs = math.modf (starttime) #startms = int (startms * 1000.); startsecs = int (startsecs) #stopms, stopsecs = math.modf (stoptime) #stopms = int (stopms * 1000.); stopsecs = int (stopsecs) #ptimestart = tdoy.epoch2PasscalTime (startsecs, startms) #ptimestop = tdoy.epoch2PasscalTime (stopsecs, stopms) #print ph5file, ph5path, ptimestart, ptimestop
def update_index_t_info (starttime, samples, sps) : global DAS_INFO ph5file = EXREC.filename ph5path = '/Experiment_g/Receivers_g/' + EXREC.ph5_g_receivers.current_g_das._v_name das = ph5path[32:] stoptime = starttime + (float (samples) / float (sps)) di = Index_t_Info (das, ph5file, ph5path, starttime, stoptime) if not DAS_INFO.has_key (das) : DAS_INFO[das] = [] DAS_INFO[das].append (di) logging.info ("DAS: {0} File: {1} First Sample: {2} Last Sample: {3}".format (das, ph5file, time.ctime (starttime), time.ctime (stoptime))) #startms, startsecs = math.modf (starttime) #startms = int (startms * 1000.); startsecs = int (startsecs) #stopms, stopsecs = math.modf (stoptime) #stopms = int (stopms * 1000.); stopsecs = int (stopsecs) #ptimestart = tdoy.epoch2PasscalTime (startsecs, startms) #ptimestop = tdoy.epoch2PasscalTime (stopsecs, stopms) #print ph5file, ph5path, ptimestart, ptimestop # YYY YYY
def json2generator(data, arrayKey=None): """ ??????? ???????????? ?????????? json ? ?????????. ??? ????????? ???????? ?????? ?????? ?? ???????? ??????? ??????. ????? ?????? ????????? ?????? ??? ??????? (??????? ????? ??????????? ? ?????????). arrayKey ?????? ????????? ?? ??????, ????? ???? ???????? (key1.key2) """ from ijson import common # from io import BytesIO from cStringIO import StringIO #! yajl2 ??????? ???????? ??????????? ???????, ?? ?? ?????? ?????? ??? ? ?? ??????? ??? ??????????, ????? "Yajl shared object cannot be found" try: import ijson.backends.yajl2_cffi as ijson except: try: from ijson.backends import yajl2 as ijson except: try: from ijson.backends import yajl as ijson except: from ijson.backends import python as ijson try: f=StringIO(data) except: f=StringIO(data.encode('utf-8')) def _fixJSON(event): # ??????? ?????????? "????" ?????????, ??????? ???????? ??? ???????? ???? ???????? ? decimal() if event[1]=='number': return (event[0], event[1], float(event[2]) if math.modf(event[2])[0] else int(event[2])) else: return event events=imap(_fixJSON, ijson.parse(f)) g=common.items(events, (arrayKey+'.item' if arrayKey else 'item')) # g=ijson.items(f, (arrayKey+'.item' if arrayKey else 'item')) return g
def getTimeTagStr(self): """Return the TimeTag as a human-readable string """ fract, secs = math.modf(self.timetag) out = time.ctime(secs)[11:19] out += ("%.3f" % fract)[1:] return out
def iadd(t1, offset): if not isinstance(t1, Time): return t1 tmp=_copy.copy(t1) # make into tics pfrac,pwhole = math.modf(offset*Time.TicFreq) tfrac = long(tmp.pf250_) + int(pfrac * Time.Two32) tmp.ps250_ += long(pwhole) + (tfrac>>32) tmp.pf250_ = int(tfrac) return tmp
def setFromTime(self, time_sec=time.time() ): """ Create a sdds time object from the input parameter. If the time_sec is from the epoch then we need to convert to the current year as per spec. """ if time_sec: if time_sec >= self.startofyear: # UTC.. need to convert to SDDS EPOCH time_sec = time_sec - self.startofyear pfrac, pwhole = math.modf(time_sec*Time.TicFreq) self.ps250_ = long(pwhole) self.pf250_ = int( pfrac*Time.Two32) #print "td: %12Lu %12u %16.2Lf " % ( self.ps250_, self.pf250_, pfrac )
def setFromPartial( self, integral, fractional ): pfrac, pwhole= math.modf(fractional*Time.TicFreq) self.ps250_ = long(integral*Time.TicFreqLong) + long(pwhole) self.pf250_ = int( pfrac * Time.Two32) #print "td: %12Lu %12u %16.2Lf " % ( self.ps250_, self.pf250_, pfrac )
def normalize(tstamp): # Get fractional adjustment from whole seconds fadj, tstamp.twsec = math.modf(tstamp.twsec) # Adjust fractional seconds and get whole seconds adjustment tstamp.tfsec, wadj = math.modf(tstamp.tfsec + fadj) # If fractional seconds are negative, borrow a second from the whole # seconds to make it positive, normalizing to [0,1) if (tstamp.tfsec < 0.0): tstamp.tfsec += 1.0; wadj -= 1.0; tstamp.twsec += wadj;
def iadd(t1, offset): fractional, whole = math.modf(offset) t1.twsec += whole t1.tfsec += fractional normalize(t1) return t1
def microtime(get_as_float = False) : if get_as_float: return time.time() else: return '%.8f %d' % math.modf(time.time())
def day_time(connection, value=None): if value is not None: if not connection.admin: return S_NO_RIGHTS value = float(value) if value < 0.0: raise ValueError() connection.protocol.current_time = value connection.protocol.update_day_color() f, i = modf(connection.protocol.current_time) return S_TIME_OF_DAY.format(hours=int(i), minutes=int(f * 60))
def suspend (timeout): a, b = math.modf (timeout) for i in range (int (b)): socketpool.noop () time.sleep (1) time.sleep (a)
def get_sampled_frames(start, end, sampling): return [math.modf(start + x * sampling) for x in range(int((end - start) / sampling) + 1)]
def float2text(number_float): cent, euro = modf(number_float) cent = round(cent * 100) zahlwort = num2text(int(euro)) + ' Euro' if (cent > 0): zahlwort += ' und ' + num2text(int(cent)) + ' Cent' zahlwort = zahlwort[0].upper() + zahlwort[1:] return zahlwort
def fractionalDayToTime(frac): ofrac = frac (frac, h) = math.modf(frac*24) (frac, m) = math.modf(frac*60) (frac, s) = math.modf(frac*60) return datetime.time(h, m, s, int(frac*1.0e6)) ## Convert time in seconds-since-start-of-day into datetime.time
def setHue ( self, newhue ): """ Modifies hue value of Colz object """ if isinstance( newhue, int ): newhue /= 360.0 if newhue > 1.0: newhue, whole = math.modf(newhue) # Keep decimal part self.h = newhue self.hsl[0] = newhue self.hsla[0] = newhue self.updateFromHsl()
def hueLerp ( h1, h2, amt ): """ Generic linear interpolation """ if isinstance( h1, int ): h1 = h1 / 360.0 if isinstance( h2, int ): h2 = h2 / 360.0 hue = h1 + Colz.shortHueDist( h1, h2) * amt if hue > 1.0: hue, whole = math.modf(hue) # Keep decimal part if hue < 0.0: hue, whole = math.modf(hue) # Keep decimal part hue = 1.0 + hue return hue
def next_generation(self): next_population = [] wheel = [] for permutation in self.population: value = self.evaluation[id(permutation)] fitness = value / self.avg_value fitness_fraction, copies = math.modf(fitness) if fitness_fraction: wheel.append(permutation) wheel.append(permutation) if copies == 1: next_population.append(permutation) elif copies > 1: next_population += [permutation] * int(copies) # XXX: fractional copies should be placed with a proportinal probability (FMD2) next_population += random.sample(wheel, len(self.population) - len(next_population)) next_population_size = len(next_population) # crossover crossover_count = int(0.5 * self.crossover_p * next_population_size) crossover_indices = random.sample(range(next_population_size), 2 * crossover_count) for i in range(crossover_count): index_a, index_b = crossover_indices[2*i], crossover_indices[2*i+1] next_population[index_a], next_population[index_b] = self.crossover(next_population[index_a], next_population[index_b]) # mutation for mutation, p in self.mutations: for index in random.sample(range(next_population_size), int(p * next_population_size)): next_population[index] = mutation(next_population[index]) self.population = next_population self.generation_count += 1 self.evaluate()
def addBubbleToTop(bubbleArray, bubble): posx = bubble.rect.centerx leftSidex = posx - BUBBLERADIUS columnDivision = math.modf(float(leftSidex) / float(BUBBLEWIDTH)) column = int(columnDivision[1]) if columnDivision[0] < 0.5: bubbleArray[0][column] = copy.copy(bubble) else: column += 1 bubbleArray[0][column] = copy.copy(bubble) row = 0 return row, column
def TimeDelta_or_None(s): try: h, m, s = s.split(':') h, m, s = int(h), int(m), float(s) td = timedelta(hours=abs(h), minutes=m, seconds=int(s), microseconds=int(math.modf(s)[0] * 1000000)) if h < 0: return -td else: return td except ValueError: # unpacking or int/float conversion failed return None
def Time_or_None(s): try: h, m, s = s.split(':') h, m, s = int(h), int(m), float(s) return time(hour=h, minute=m, second=int(s), microsecond=int(math.modf(s)[0] * 1000000)) except ValueError: return None
def latlng2dm(latlng): """ Degrees Minutes representation of LatLng :param latlng: LatLng :return: unicode >>> latlng2dm(LatLng(45.5, 30.5)) u'N4530.0E03030.0' """ def dm(v, pattern): f, degrees = math.modf(abs(v)) cents, minutes = math.modf(f * 60) cents = round(cents * 10) if cents >= 10: cents = 0 minutes += 1 return pattern.format( int(degrees), int(minutes), int(cents) ) return '{0}{1}{2}{3}'.format( 'N' if latlng.latitude >= 0 else 'S', dm(latlng.latitude, '{0:0>2d}{1:0>2d}.{2}'), 'E' if latlng.longitude > 0 else 'W', dm(latlng.longitude, '{0:0>3d}{1:0>2d}.{2}'), )
def microtime(get_as_float=False): if get_as_float: return time.time() else: return '%.8f %d' % math.modf(time.time())
def minutes_to_str(m): frac,m = math.modf(m) hours = m//60 minutes = m % 60 seconds = frac * 60 return "%02d:%02d.%02.f" % (hours,minutes,seconds) # Read the stock history file as a list of lists