def from_fixed(cls, date): """Return Old Hindu solar date equivalent to fixed date date.""" sun = cls.hindu_day_count(date) + Clock.days_from_hours(6) year = quotient(sun, cls.ARYA_SOLAR_YEAR) month = mod(quotient(sun, cls.ARYA_SOLAR_MONTH), 12) + 1 day = ifloor(mod(sun, cls.ARYA_SOLAR_MONTH)) + 1 return OldHinduSolarDate(year, month, day)
def do_date(datenode) : (day,month,year) = extractdate(datenode) if le(month,0) or gt(month,12) : daysinmonth = 0 elif eq(month,9) or eq(month,4) or eq(month,6) or eq(month,11) : daysinmonth = 30 elif eq(month,2) : if eq(mod(year,4),0) and (julian or (ne(mod(year,100),0) or eq(mod(year,400),0))) : daysinmonth = 29 else : daysinmonth = 28 else : daysinmonth=31 future = 0 if gt(year,toyear) : future = 1 elif eq(year,toyear) : if gt(month,tomonth) : future=1 elif eq(month,tomonth) and gt(day,today) : future=1 if gt(day,daysinmonth) or future : out("*") if lt(year,0) : cols(d(year),6) else : if lt(year,10) : out("0") if lt(year,100) : out("0") if lt(year,1000) : out("0") out(d(year)) if lt(month,10) : out("0") out(d(month)) if lt(day,10) : out ("0") out(d(day)+" ")
def make_table(L, style1_even, style1_odd, style2_even, style2_odd): '''Generate HTML table from input data stored in list L. style1_even and style1_odd is the style class for the even and odd entries of the first column (player names). style2_even and style2_odd are the equivalent the other entries.''' lines = [] for i in xrange(len(L)): if (mod(i, 2) == 0): str1 = '<TR>\n' str1 = str1 + '<TD><DIV class="%s">' % style1_even + str( L[i][0]) + '</SPAN>\n' str1 = str1 + '</DIV></TD>' str2 = '' else: str1 = '<TR>\n' str1 = str1 + '<TD><DIV class="%s">' % style1_odd + str( L[i][0]) + '</SPAN>\n' str1 = str1 + '</DIV></TD>' str2 = '' for j in xrange(1, len(L[0])): if (mod(i, 2) == 0): str2 = str2 + '<TD><DIV class="%s">' % style2_even + str( L[i][j]) + '\n' str2 = str2 + '</DIV></TD>\n' else: str2 = str2 + '<TD><DIV class="%s">' % style2_odd + str( L[i][j]) + '\n' str2 = str2 + '</DIV></TD>\n' str2 = str2 + '</TR>\n' lines.append(str1) lines.append(str2) lines.append('</TABLE>') return lines
def __init__(self, ptxt, pyfhel, pSize=0): if not isinstance(ptxt, list): raise TypeError("pyPtxt init error: ptxt must be of type list") if not isinstance(pyfhel, Pyfhel): raise TypeError("pyPtxt init error: pyfhel must be of type Pyfhel") self.__numSlots = pyfhel.numSlots() self.__pyfhel = pyfhel if (pSize > 0): nPart = len(ptxt) / pSize + int(mod(len(ptxt), pSize) > 0) if (pSize > self.__numSlots): raise ValueError("pSize cannot be bigger than numSlots: " + self.__numSlots) for i in range(0, nPart): # Fill the List of lists self.__ptxtList.append(ptxt[(i * pSize):((i + 1) * pSize)]) self.__ptxtList = [[mod(elt, pyfhel.getModulus()) for elt in lst] for lst in self.__ptxtList] elif (isinstance(ptxt[0], list)): for elt in ptxt: l = len(elt) if ((l) > self.__numSlots): raise ValueError( "No list can have bigger size than numSlots: " + self.__numSlots) self.__ptxtList = [[mod(elt, pyfhel.getModulus()) for elt in lst] for lst in ptxt] else: self.__ptxt = [mod(elt, pyfhel.getModulus()) for elt in ptxt] n = max(1, self.__numSlots) self.__ptxtList = [ptxt[i:i + n] for i in range(0, len(ptxt), n)] self.__length = ([len(elt) for elt in self.__ptxtList]) return
def feast_of_ridvan(cls, gregorian_year): """Return Fixed date of Feast of Ridvan in Gregorian year year, 'gregorian_year'.""" years = gregorian_year - GregorianDate.to_year(cls.EPOCH) major = 1 + quotient(years, 361) cycle = 1 + quotient(mod(years, 361), 19) year = 1 + mod(years, 19) return FutureBahaiDate(major, cycle, year, 2, 13).to_fixed()
def tropical_longitude(cls, fixed_date): """Return the Hindu tropical longitude on fixed date, 'fixed_date'. Assumes precession with maximum of 27 degrees and period of 7200 sidereal years (= 1577917828/600 days).""" days = ifloor(fixed_date - OldHindu.EPOCH) precession = 27 - abs(54 - mod(27 + (108 * 600/1577917828 * days), 108)) return mod(cls.solar_longitude(fixed_date) - precession, 360)
def cenPoly(c, q): u = float(q) / float(2) l = -u c = modPoly(c, q) c = list(map(lambda x: mod(x, -q) if x > u else x, c)) c = list(map(lambda x: mod(x, q) if x <= l else x, c)) return c
def test_float_modulus_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = operator.mod(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = operator.mod(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = operator.mod(fone, fzer) assert_(np.isnan(rem), 'dt: %s' % dt) # MSVC 2008 returns NaN here, so disable the check. #rem = operator.mod(fone, finf) #assert_(rem == fone, 'dt: %s' % dt) rem = operator.mod(fone, fnan) assert_(np.isnan(rem), 'dt: %s' % dt) rem = operator.mod(finf, fone) assert_(np.isnan(rem), 'dt: %s' % dt)
def is_swap(player_score, opponent_score): """ Return whether the two scores should be swapped """ # BEGIN PROBLEM 4 "*** YOUR CODE HERE ***" from operator import mod, floordiv i = -1 p_digits = [0] * 10 o_digits = [0] * 10 while player_score >= 1: i += 1 p_digits[i] = mod(player_score, 10) player_score = floordiv(player_score, 10) p_mul = p_digits[0] * p_digits[i] n = -1 while opponent_score >= 1: n += 1 o_digits[n] = mod(opponent_score, 10) opponent_score = floordiv(opponent_score, 10) o_mul = o_digits[0] * o_digits[n] if o_mul == p_mul: return True else: return False
def estimate_prior_solar_longitude(cls, lam, tee): """Return approximate moment at or before tee when solar longitude just exceeded lam degrees.""" rate = cls.MEAN_TROPICAL_YEAR / 360.0 tau = tee - (rate * mod(cls.solar_longitude(tee) - lam, 360)) cap_Delta = mod(cls.solar_longitude(tau) - lam + 180, 360) - 180 return min(tee, tau - (rate * cap_Delta))
def cenPoly(c,q): u=float(q)/float(2) l=-u c=modPoly(c,q) c=map(lambda x: mod(x,-q) if x>u else x,c) c=map(lambda x: mod(x,q) if x<=l else x,c) return c
def from_moment(cls, tee): """Return clock time hour:minute:second from moment 'tee'.""" time = cls.time_from_moment(tee) hour = ifloor(time * 24) minute = ifloor(mod(time * 24 * 60, 60)) second = mod(time * 24 * 60 * 60, 60) return Clock(hour, minute, second)
def easter(cls, year): """Return fixed date of Easter in Gregorian year 'year'.""" century = quotient(year, 100) + 1 shifted_epact = mod(14 + 11 * mod(year, 19) - quotient(3 * century, 4) + quotient(5 + (8 * century), 25), 30) adjusted_epact = shifted_epact + 1 if shifted_epact == 0 or (shifted_epact == 1 and 10 < mod(year, 19)) else shifted_epact apr19 = GregorianDate(year, MonthOfYear.April, 19) paschal_moon = apr19.to_fixed() - adjusted_epact return DayOfWeek.Sunday.after(paschal_moon)
def is_leap_year(year): """Verify if a year is a leap year. :year: an int object :returns: True or False """ return not mod(year, 4) and not (not mod(year, 100) and mod(year, 400))
def test_mod(backend, alltypes, df): expr = operator.mod(alltypes.smallint_col, alltypes.smallint_col + 1) result = expr.execute() expected = operator.mod(df.smallint_col, df.smallint_col + 1) expected = backend.default_series_rename(expected) backend.assert_series_equal(result, expected, check_dtype=False)
def test_apply_lambda(): v = Matrix.from_lists([0, 1, 2], [0, 1, 2], [22, 33, 44]) w = v.apply(lambda x: mod(x, 10)) assert w.iseq(Matrix.from_lists([0, 1, 2], [0, 1, 2], [2, 3, 4])) w = v.apply(lambda x: mod(x, 7)) assert w.iseq(Matrix.from_lists([0, 1, 2], [0, 1, 2], [1, 5, 2]))
def is_leap_year(year): """TODO: Docstring for is_leap_year. :year: TODO :returns: TODO """ return not mod(year, 4) and not (not mod(year, 100) and mod(year, 400))
def verifyGcd(gcd, numbers) : ''' What are the properties one should verify? I propose two properties which must be satisfied. One that gcd divides all given numbers and there is no number between gcd and the minimum among the given numbers which also divides the given numbers. Former assertion is ovious : it is the property of gcd that it divides all numbers. For second property we can argue that if there is a number (less than or equal to the minimum among the given numbers) which is larger than gcd and divides all given numbers then gcd is not really the GCD. ''' propertyOneIsTrue = True propertyTwoIsTrue = True msg = " + Verifying that gcd divides all numbers" print(msg) for i in numbers : if operator.mod(i, gcd) != 0 : propertyOneIsTrue = False if propertyOneIsTrue : msg = " : Passed " else : msg = " : Failed " print(msg) minNumbers = min(numbers) msg = " + verifying that there is no number between {0} and {1}".format( gcd+1, minNumbers) + " which divides all numbers. This might take a while..." print(msg) # It is enough to iterate from gcd+1 to min(numbers) and check that there is # at least one number which can't be divided. for i in xrange(gcd+1, minNumbers) : iIsGCD = True for num in numbers : if operator.mod(num, i) != 0 : # There is a number i does not divide iIsGCD = False break if iIsGCD : # There is a number i which divides all numbers print("[I] {0} also divides.".format(i)) propertyTwoIsTrue = False break if propertyTwoIsTrue : msg = " : Passed " else : msg = " : Failed " print(msg) if propertyOneIsTrue and propertyTwoIsTrue : print("\nRESULT : Men and gentle ladies, {0} is the GCD.".format(gcd)) print("--- This has been verified!") return 0 else : print("\nThe claim that {0} is the GCD is wrong.".format(gcd)) print("--- What an incompetent implementation.") return -1
def __init__(self, field, elts=0): self.field = field if self.isIntType(elts): # Allow coercion from integer self.coeffs = [mod(elts, self.field.char) ] + [0 for i in range(self.field.degree - 1)] else: self.coeffs = [mod(theelt, self.field.char) for theelt in elts] + [ 0 for i in range(self.field.degree - len(elts)) ]
def on_or_before(self, date): """Return last fixed date on or before date with Pawukon date b_date.""" a5 = self.pancawara - 1 a6 = self.sadwara - 1 b7 = self.saptawara - 1 b35 = mod(a5 + 14 + (15 * (b7 - a5)), 35) days = a6 + (36 * (b35 - a6)) cap_Delta = self.day_from_fixed(0) return date - mod(date + cap_Delta - days, 210)
def from_fixed(cls, fixed_date): """Return Old Hindu lunar date equivalent to fixed date 'fixed_date'.""" sun = cls.hindu_day_count(fixed_date) + Clock.days_from_hours(6) new_moon = sun - mod(sun, cls.ARYA_LUNAR_MONTH) leap = cls.ARYA_SOLAR_MONTH - cls.ARYA_LUNAR_MONTH >= mod(new_moon, cls.ARYA_SOLAR_MONTH) and mod(new_moon, cls.ARYA_SOLAR_MONTH) > 0 month = mod(iceiling(new_moon / cls.ARYA_SOLAR_MONTH), 12) + 1 day = mod(quotient(sun, cls.ARYA_LUNAR_DAY), 30) + 1 year = iceiling((new_moon + cls.ARYA_SOLAR_MONTH) / cls.ARYA_SOLAR_YEAR) - 1 return OldHinduLunarDate(year, month, leap, day)
def func(a, b, c, d): if mod(c, a) == 0 and mod(d, b) == 0: print(c + d, c / a, d / b) return 0 elif (d - a) < 0: print("*", c + d, c / a, d / b) return -1 else: func(a, b, c + a, d - a)
def columnProcess(i): if operator.mod(i, 5) == 1: return stocks[:, i] * 0 if operator.mod(i, 5) == 2: return stocks[:, i] * 0 if operator.mod(i, 5) == 4: return stocks[:, i] * 0 else: return stocks[:, i] / stocks[:, 0]
def RealmDecrypt(vector_key, tag_key, cipher_key, buffer): count = 0 # Sanity check the input values. if len(cipher_key) != 32: raise ValueError("The encryption key must be 32 octets in length.") elif len(tag_key) != 16: raise ValueError("The tag key must be 16 octets in length.") elif len(vector_key) != 16: raise ValueError("The vector key must be 16 octets in length.") elif len(buffer) < 54: raise ValueError( "The minimum length of a correctly formatted cipher text is 54 octets." ) elif operator.mod(len(buffer) - 34, 16) != 0: raise ValueError( "The cipher text was not aligned to a 16 octet boundary or some of the data is missing." ) # Parse the envelope. vector_shard = buffer[2:18] tag_shard = buffer[18:34] ciphertext = buffer[34:] # Combine the shard values with the key to device the iv and tag. iv = str().join(chr(operator.xor(ord(a), ord(b))) \ for a,b in zip(vector_key, vector_shard)) tag = str().join(chr(operator.xor(ord(a), ord(b))) \ for a,b in zip(tag_key, tag_shard)) # Decrypt the payload. decryptor = Cipher(algorithms.AES(cipher_key), modes.GCM(iv, tag), backend=default_backend()).decryptor() plaintext = decryptor.update(ciphertext) + decryptor.finalize() # Parse the prefix. size = struct.unpack(">I", '\x00' + plaintext[0:3])[0] pad = struct.unpack(">I", '\x00' + '\x00' + '\x00' + plaintext[3:4])[0] # Validate the prefix values. if operator.mod(size + pad + 4, 16) != 0 or len(plaintext) != size + pad + 4: raise ValueError("The encrypted buffer is invalid.") # Confirm the suffix values. for offset in xrange(size + 4, size + pad + 4, 1): if struct.unpack( ">I", '\x00' + '\x00' + '\x00' + plaintext[offset:offset + 1])[0] != pad: raise ValueError( "The encrypted buffer contained an invalid padding value.") # Return just the plain text value. return plaintext[4:size + 4]
def sid2vals(s, nOnionLoc=4, nEEFLoc=4, nPredict=3, nlistIDStatus=3): sid = s onionloc = int(mod(sid, nOnionLoc)) sid = (sid - onionloc) / nOnionLoc eefloc = int(mod(sid, nEEFLoc)) sid = (sid - eefloc) / nEEFLoc predic = int(mod(sid, nPredict)) sid = (sid - predic) / nPredict listidstatus = int(mod(sid, nlistIDStatus)) return [onionloc, eefloc, predic, listidstatus]
def muXY(md,x,y): MUX=[];MUY=[];NAMES=[] for j in range(len(y.NAME)): nm1=cbpm(y.NAME[j]);nm2=cbpm(y.NAME2[j]) MUY.append(mod(md[nm2][1]-md[nm1][1],1)) for j in range(len(x.NAME)): nm1=cbpm(x.NAME[j]);nm2=cbpm(x.NAME2[j]) MUX.append(mod(md[nm2][0]-md[nm1][0],1)) print len(MUX), len(MUY), md['Q1'], md['Q2'] return MUX,MUY
def double_add(a, b, pr, P): x = P.x y = P.y lamda = int(mod((3 * (x * x) + a) / (2 * y), pr)) m = int(mod(lamda * lamda - 2 * x, pr)) n = int(mod(y + lamda * (m - x), pr)) R = Point(m, n) if P.y == 0: R.isInfinite = True return R
def process_column(i): if operator.mod(i, 5) == 1: return stocks[:, i] * 0 if operator.mod(i, 5) == 2: return stocks[:, i] * 0 if operator.mod(i, 5) == 4: return stocks[:, i] * 0 #return np.log(stocks[:,i] + 1) else: return stocks[:, i] / stocks[:, 0]
def accel(self, v): if self.helirect.left > 0 or self.helirect.right < width: self.speed[0] = v * cos(mod(self.rots, 36) /18 * pi) else: self.speed[0] = 0.0 if self.helirect.top > 0 or self.helirect.bottom < height: self.speed[1] = -v * sin(mod(self.rots, 36) /18 * pi) else: self.speed[1] = 0.0
def process_column(i): if operator.mod(i, 5) == 1: return stocks[:,i] * 0 if operator.mod(i, 5) == 2: return stocks[:,i] * 0 if operator.mod(i, 5) == 4: return stocks[:,i] * 0 #return np.log(stocks[:,i] + 1) else: return stocks[:,i] / stocks[:,0]
def test_floating_mod(backend, alltypes, df): if not backend.supports_floating_modulus: pytest.skip(f'{backend} does not support floating modulus operation') expr = operator.mod(alltypes.double_col, alltypes.smallint_col + 1) result = expr.execute() expected = operator.mod(df.double_col, df.smallint_col + 1) expected = backend.default_series_rename(expected) backend.assert_series_equal(result, expected, check_exact=False)
def lres2dec(ires): lim=len(ires) tot=ires[0] ind=1 while ind<lim: lrad=lrads[ind] cry=mod(tot, lrad) dig=mod((ires[ind]-cry)*linvs[ind], lrad) tot+=dig*lcms[ind] ind+=1 return tot
def DisplayItem(self, SelectLeftChar): Period = int(self.Repeat.total_seconds()) Seconds = operator.mod(Period, 60) Period = operator.div(Period, 60) Minutes = operator.mod(Period, 60) Period = operator.div(Period, 60) Hours = operator.mod(Period, 24) Period = operator.div(Period, 24) Days = Period print("{}{:^19}".format(SelectLeftChar, self.ScheduleDate.strftime("%Y-%m-%d %H:%M:%S")) + "\r") print("{}{:>2}={:<2} {:>3} {:0>2}:{:0>2}:{:0>2}".format(SelectLeftChar, self.RelayNumber, self.RelayState, str(Days), str(Hours), str(Minutes), str(Seconds)) + "\r")
def mod_pow(a, x, N): """Computes mod(a^x, N) using repeated squaring mod N. x must be a positive integer. """ X = numstr_to_array(bin(x)[2:]) # exponent in big-endian binary res = 1 for b in reversed(X): # little-endian if b: res = mod(res * a, N) a = mod(a * a, N) # square a return res
def check(x=9): a = eq(0,mod(x,3)) b = eq(0,mod(x,5)) if a & b: return "Fizz Buzz" elif a: return "Fizz" elif b: return "Buzz" else: return x
def func(a,b,c): d=c c=0 for n in(1,c%a,1): if mod(c,a)==0 and mod(d,b)==0: print( c+d,c/a,d/b) return 0 elif(d-a)<0: print( "*",c+d,c/a,d/b) return -1 else: c=c+a; d=d-a
def getTableNames(self, startTime, endTime): tables = list() tmpTables = self.getTables() for tab in tmpTables: tabletime = calendar.timegm([string.atoi(tab[0][2:6]), string.atoi(tab[0][6:8]), string.atoi(tab[0][8:10]), string.atoi(tab[0][11:13]), string.atoi(tab[0][14])*30, 0, 0, 0, 0]) # one table is 30 minutes == 30*60 tableLength = 30*60 alignedStart = startTime - mod(startTime, tableLength) alignedEnd = endTime + tableLength - mod(endTime + tableLength, tableLength) if tabletime >= alignedStart and tabletime < alignedEnd: tables.append(tab[0]) return tables
def add(pr, P, Q): if P.isInfinite: return Q if Q.isInfinite: return P lamda = int(mod((P.y - Q.y) / (P.x - Q.x), pr)) x = int(mod((lamda * lamda - P.x - Q.x), pr)) y = int(mod((P.y + lamda * (x - P.x)), pr)) R = Point(x, y) if (-P.y) % pr == Q.y: R.isInfinite = True return R
def to_year(cls, fixed_date): """Return the year corresponding to the fixed date 'fixed_date'.""" d0 = fixed_date - cls.EPOCH n400 = quotient(d0, 146097) d1 = mod(d0, 146097) n100 = quotient(d1, 36524) d2 = mod(d1, 36524) n4 = quotient(d2, 1461) d3 = mod(d2, 1461) n1 = quotient(d3, 365) year = (400 * n400) + (100 * n100) + (4 * n4) + n1 return year if n100 == 4 or n1 == 4 else year + 1
def precession(cls, tee): """Return the precession at moment tee using 0,0 as J2000 coordinates. Adapted from "Astronomical Algorithms" by Jean Meeus, Willmann-Bell, Inc., 1991.""" c = cls.julian_centuries(tee) eta = mod(poly(c, [0, secs(mpf(47.0029)), secs(mpf(-0.03302)), secs(mpf(0.000060))]), 360) cap_P = mod(poly(c, [mpf(174.876384), secs(mpf(-869.8089)), secs(mpf(0.03536))]), 360) p = mod(poly(c, [0, secs(mpf(5029.0966)), secs(mpf(1.11113)), secs(mpf(0.000006))]), 360) cap_A = cos_degrees(eta) * sin_degrees(cap_P) cap_B = cos_degrees(cap_P) arg = arctan_degrees(cap_A, cap_B) return mod(p + cap_P - arg, 360)
def lunar_phase(cls, tee): """Return the lunar phase, as an angle in degrees, at moment tee. An angle of 0 means a new moon, 90 degrees means the first quarter, 180 means a full moon, and 270 degrees means the last quarter.""" phi = mod(cls.lunar_longitude(tee) - Solar.solar_longitude(tee), 360) t0 = cls.nth_new_moon(0) n = iround((tee - t0) / cls.MEAN_SYNODIC_MONTH) phi_prime = (360 * mod((tee - cls.nth_new_moon(n)) / cls.MEAN_SYNODIC_MONTH, 1)) if abs(phi - phi_prime) > 180: return phi_prime else: return phi
def largest_factor(n): i = 2 if n == 1: return n while mod(n, i) != 0: i = i + 1 if i == n: return i n = n / i while mod(n, 2) == 0: if n == 2: return n n = n / 2 return n
def sum_digits(n): """Sum all the digits of n. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 """ fldiv, sum_digits = floordiv(n, 10), mod(n, 10) while fldiv > 0: sum_digits += mod(fldiv, 10) fldiv = floordiv(fldiv, 10) return sum_digits
def lunar_altitude(self, tee): """Return the geocentric altitude of moon at moment, tee, at location, location, as a small positive/negative angle in degrees, ignoring parallax and refraction. Adapted from 'Astronomical Algorithms' by Jean Meeus, Willmann_Bell, Inc., 1998.""" lamb = lunar_longitude(tee) beta = lunar_latitude(tee) alpha =right_ascension(tee, beta, lamb) delta = declination(tee, beta, lamb) theta0 = sidereal_from_moment(tee) cap_H = mod(theta0 + self.longitude - alpha, 360) altitude = arcsin_degrees( (sin_degrees(self.latitude) * sin_degrees(delta)) + (cos_degrees(self.latitude) * cos_degrees(delta) * cos_degrees(cap_H))) return mod(altitude + 180, 360) - 180
def lunar_altitude(self, tee): """Return the geocentric altitude of moon at moment, tee, at location, location, as a small positive/negative angle in degrees, ignoring parallax and refraction. Adapted from 'Astronomical Algorithms' by Jean Meeus, Willmann_Bell, Inc., 1998.""" lamb = Lunar.lunar_longitude(tee) beta = Lunar.lunar_latitude(tee) alpha = Astro.right_ascension(tee, beta, lamb) delta = Astro.declination(tee, beta, lamb) theta0 = Astro.sidereal_from_moment(tee) cap_H = mod(theta0 + self.longitude - alpha, 360) altitude = arcsin_degrees( (sin_degrees(self.latitude) * sin_degrees(delta)) + (cos_degrees(self.latitude) * cos_degrees(delta) * cos_degrees(cap_H))) return mod(altitude + 180, 360) - 180
def binarize(in_col, out, width): """Convert any positive integer to a binary array. """ i = cuda.grid(1) if i < in_col.size: n = in_col[i] idx = width - 1 out[i, idx] = operator.mod(n, 2) idx -= 1 while n > 1: n = operator.rshift(n, 1) out[i, idx] = operator.mod(n, 2) idx -= 1
def DisplayItem(self, SelectLeftChar): Period = int(self.Repeat.total_seconds()) Seconds = operator.mod(Period, 60) Period = operator.div(Period, 60) Minutes = operator.mod(Period, 60) Period = operator.div(Period, 60) Hours = operator.mod(Period, 24) Period = operator.div(Period, 24) Days = Period print("{}{:^19}".format( SelectLeftChar, self.ScheduleDate.strftime("%Y-%m-%d %H:%M:%S")) + "\r") print("{}{:>2}={:<2} {:>3} {:0>2}:{:0>2}:{:0>2}".format( SelectLeftChar, self.RelayNumber, self.RelayState, str(Days), str(Hours), str(Minutes), str(Seconds)) + "\r")
def test_floating_mod(backend, alltypes, df): if not backend.supports_floating_modulus: pytest.skip( '{} backend does not support floating modulus operation'.format( backend.name ) ) expr = operator.mod(alltypes.double_col, alltypes.smallint_col + 1) result = expr.execute() expected = operator.mod(df.double_col, df.smallint_col + 1) expected = backend.default_series_rename(expected) backend.assert_series_equal( result, expected, check_exact=False, check_less_precise=True )
def operator_mod(size): a = Array(size, 'int32') b = Array(size, 'int32') for i in range(size): a[i] = nb_types.int32(i * 123) b[i] = nb_types.int32(7) return operator.mod(a, b)
def getNewFrameWidth(self, NewFrameHeight): newwidth = int(self.VideoFrameWidth * int(NewFrameHeight) / self.VideoFrameHeight) if operator.mod(newwidth, 2) == 0: return newwidth else: return newwidth + 1
def outputMatrix(startVertices, endVertices, estMatrix, daytimeindex): filename = 'estimatedMatri-' + daytimeindex + '.fma' foutmtx = open(filename, 'w') foutmtx.write( '$VMR;D2;estimated with the generalized least squares model\n') foutmtx.write('* Verkehrsmittelkennung\n') foutmtx.write(' 1\n') foutmtx.write('* Von Bis\n\n') foutmtx.write('* Faktor\n') foutmtx.write('1.00\n') foutmtx.write('*\n') foutmtx.write('* Deutsches Zentrum fuer Luft- und Raumfahrt e.V.\n') foutmtx.write('* %s\n' % datetime.datetime.now()) foutmtx.write('* Anzahl Bezirke\n') foutmtx.write('%s\n' % len(startVertices)) foutmtx.write('*\n') for startVertex in startVertices: foutmtx.write('%s ' % startVertex.label) foutmtx.write('\n*') for start, startVertex in enumerate(startVertices): count = -1 foutmtx.write('\n* from: %s\n' % startVertex.label) for end, endVertex in enumerate(endVertices): count += 1 if operator.mod(count, 12) != 0: foutmtx.write('%s ' % estMatrix[start][end]) elif count > 12: foutmtx.write('\n%s ' % estMatrix[start][end]) foutmtx.close()
def KeysAddSchedule(self, KeyCode): Result = KeyCode self.InputBuffer = self.KeyMaskedInput("####-##-## ##:##:## ### ##:##:## ## #", self.InputBuffer, KeyCode) # If enter key is pressed, change to display main menu. if KeyCode == 10: # If full user input has been gathered, add a schedule item. if len(self.InputBuffer) == 26: # Parse user input. UserInput = self.GetMaskedInput("####-##-## ##:##:## ### ##:##:## ## #", self.InputBuffer) RelayState = { "0":ScheduleItem.RELAY_OFF, "1":ScheduleItem.RELAY_ON, "2":ScheduleItem.RELAY_TOGGLE, }.get(UserInput[36:37], ScheduleItem.RELAY_TOGGLE) PeriodSeconds = string.atoi(UserInput[30:32]) + 60 * string.atoi(UserInput[27:29]) + 60 * 60 * string.atoi(UserInput[24:26]) + 24 * 60 * 60 * string.atoi(UserInput[20:23]) PeriodDays = operator.div(PeriodSeconds, 24 * 60 * 60) PeriodSeconds = operator.mod(PeriodSeconds, 24 * 60 * 60) # Add schedule item, ignore errors from invalid data entered. try: self.ThisSchedule.AddSchedule(string.atoi(UserInput[33:35]), datetime.datetime(string.atoi(UserInput[0:4]), string.atoi(UserInput[5:7]), string.atoi(UserInput[8:10]), string.atoi(UserInput[11:13]), string.atoi(UserInput[14:16]), string.atoi(UserInput[17:19])), RelayState, datetime.timedelta(PeriodDays, PeriodSeconds)) except: print("") self.ThisWindow.refresh() self.SetInterfaceState(STATE_MAIN_MENU) return Result
def outputMatrix(startVertices, endVertices, estMatrix, daytimeindex): filename = "estimatedMatri-" + daytimeindex + ".fma" foutmtx = file(filename, "w") foutmtx.write("$VMR;D2;estimated with the generalized least squares model\n") foutmtx.write("* Verkehrsmittelkennung\n") foutmtx.write(" 1\n") foutmtx.write("* Von Bis\n\n") foutmtx.write("* Faktor\n") foutmtx.write("1.00\n") foutmtx.write("*\n") foutmtx.write("* Deutsches Zentrum fuer Luft- und Raumfahrt e.V.\n") foutmtx.write("* %s\n" % datetime.datetime.now()) foutmtx.write("* Anzahl Bezirke\n") foutmtx.write("%s\n" % len(startVertices)) foutmtx.write("*\n") for startVertex in startVertices: foutmtx.write("%s " % startVertex.label) foutmtx.write("\n*") for start, startVertex in enumerate(startVertices): count = -1 foutmtx.write("\n* from: %s\n" % startVertex.label) for end, endVertex in enumerate(endVertices): count += 1 if operator.mod(count, 12) != 0: foutmtx.write("%s " % estMatrix[start][end]) elif count > 12: foutmtx.write("\n%s " % estMatrix[start][end]) foutmtx.close()
def approx_moment_of_depression(self, tee, alpha, early): """Return the moment in local time near tee when depression angle of sun is alpha (negative if above horizon) at location; early is true when MORNING event is sought and false for EVENING. Raise VlueError if depression angle is not reached.""" ttry = self.sine_offset(tee, alpha) date = Clock.fixed_from_moment(tee) if alpha >= 0: if early: alt = date else: alt = date + 1 else: alt = date + Clock.days_from_hours(12) if abs(ttry) > 1: value = self.sine_offset(alt, alpha) else: value = ttry if abs(value) <= 1: temp = -1 if early else 1 temp *= mod(Clock.days_from_hours(12) + arcsin_degrees(value) / 360, 1) - Clock.days_from_hours(6) temp += date + Clock.days_from_hours(12) return self.local_from_apparent(temp) else: raise ValueError("Depression angle not reached")
def isReady(self, job, jobType): """ Actual function that does the work """ #This should come from configuration, pause_count pauseCount = self.config.RetryManager.pauseCount pauseMap = { 'createcooloff' : 'createpaused', 'submitcooloff' : 'submitpaused', 'jobcooloff' : 'jobpaused' } # Here introduces the SquaredAlgo logic : baseTimeout = self.config.RetryManager.coolOffTime.get(jobType.lower(), 10) cooloffTime = baseTimeout * pow(job['retry_count'], 2) currentTime = self.timestamp() if currentTime - job['state_time'] > cooloffTime: retryByTimeOut = True else: retryByTimeOut = False if retryByTimeOut : # If reached the pauseCount, we want the job to pause instead of retrying if mod(job['retry_count'], pauseCount): self.changer.propagate(job, pauseMap[job['state']], job['state']) return False else: return True else: return False
def get_language_list_for_templates(default_language): # type: (Text) -> List[Dict[str, Dict[str, str]]] language_list = [l for l in get_language_list() if 'percent_translated' not in l or l['percent_translated'] >= 5.] formatted_list = [] lang_len = len(language_list) firsts_end = (lang_len // 2) + operator.mod(lang_len, 2) firsts = list(range(0, firsts_end)) seconds = list(range(firsts_end, lang_len)) assert len(firsts) + len(seconds) == lang_len for row in zip_longest(firsts, seconds): item = {} for position, ind in zip(['first', 'second'], row): if ind is None: continue lang = language_list[ind] percent = name = lang['name'] if 'percent_translated' in lang: percent = u"{} ({}%)".format(name, lang['percent_translated']) item[position] = { 'name': name, 'code': lang['code'], 'percent': percent, 'selected': True if default_language == lang['code'] else False } formatted_list.append(item) return formatted_list