Calculate the fraction of the year since moon swap.
163493
def get_year_since_resonance(ringcube):
    ""
    t0 = dt(2006, 1, 21)
    td = ringcube.imagetime - t0
    return td.days / 365.25
1075128
def yearfrac_365q(d1, d2):
    """"""

    # import modules
    from datetime import date
    from oxyba import date_to_datetime

    # define yearfrac formula
    # toyf = lambda a,b: (a - b).days / 365.2425
    def toyf(a, b):
        a = date_to_datetime(a) if isinstance(a, date) else a
        b = date_to_datetime(b) if isinstance(b, date) else b
        return (a - b).days / 365.2425

    # deal with scalars and vectors
    n1 = len(d1) if hasattr(d1, "__iter__") else 1
    n2 = len(d2) if hasattr(d2, "__iter__") else 1

    # compute yearfrac
    if n1 == 1 and n2 == 1:
        return toyf(d1, d2)
    elif n1 > 1 and n2 == 1:
        return [toyf(elem, d2) for elem in d1]
    elif n1 == 1 and n2 > 1:
        return [toyf(d1, elem) for elem in d2]
    elif n1 > 1 and n1 == n2:
        return [toyf(e1, e2) for e1, e2 in zip(d1, d2)]
    else:
        raise Exception("d1 and d2 have the wrong dimensions.")
909847
private int newYear(int gyear) {

        long cacheValue = newYearCache.get(gyear);

        if (cacheValue == CalendarCache.EMPTY) {

            int solsticeBefore= winterSolstice(gyear - 1);
            int solsticeAfter = winterSolstice(gyear);
            int newMoon1 = newMoonNear(solsticeBefore + 1, true);
            int newMoon2 = newMoonNear(newMoon1 + SYNODIC_GAP, true);
            int newMoon11 = newMoonNear(solsticeAfter + 1, false);
            
            if (synodicMonthsBetween(newMoon1, newMoon11) == 12 &&
                (hasNoMajorSolarTerm(newMoon1) || hasNoMajorSolarTerm(newMoon2))) {
                cacheValue = newMoonNear(newMoon2 + SYNODIC_GAP, true);
            } else {
                cacheValue = newMoon2;
            }

            newYearCache.put(gyear, cacheValue);
        }
        return (int) cacheValue;
    }
964796
function jdnToGregorian(jdn, JD_OFFSET = JD_EPOCH_OFFSET_GREGORIAN, leapYear = isGregorianLeap) {
  const nMonths = 12;
  const monthDays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  const r2000 = mod((jdn - JD_OFFSET), 730485);
  const r400 = mod((jdn - JD_OFFSET), 146097);
  const r100 = mod(r400, 36524);
  const r4 = mod(r100, 1461);

  let n = mod(r4, 365) + 365 * Math.floor(r4 / 1460);
  const s = Math.floor(r4 / 1095);

  const aprime = 400 * Math.floor((jdn - JD_OFFSET) / 146097)
               + 100 * Math.floor(r400 / 36524)
               + 4 * Math.floor(r100 / 1461)
               + Math.floor(r4 / 365)
               - Math.floor(r4 / 1460)
               - Math.floor(r2000 / 730484);
  const year = aprime + 1;
  const t = Math.floor((364 + s - n) / 306);
  let month = t * (Math.floor(n / 31) + 1) + (1 - t) * (Math.floor((5 * (n - s) + 13) / 153) + 1);
  n += 1 - Math.floor(r2000 / 730484);
  let day = n;

  if ((r100 === 0) && (n === 0) && (r400 !== 0)) {
    month = 12;
    day = 31;
  } else {
    monthDays[2] = (leapYear(year)) ? 29 : 28;
    for (let i = 1; i <= nMonths; i += 1) {
      if (n <= monthDays[i]) {
        day = n;
        break;
      }

      n -= monthDays[i];
    }
  }

  return { year, month, day };
}
301788
def swap(self):
        """"""
        self.xmin, self.ymin = self.ymin, self.xmin
        self.xmax, self.ymax = self.ymax, self.xmax
465654
function phase (phase_date) {
  if (!phase_date) {
    phase_date = new Date()
  }
  phase_date = julian.fromDate(phase_date)

  const day = phase_date - EPOCH

  // calculate sun position
  const sun_mean_anomaly =
    (360.0 / 365.2422) * day +
    (ECLIPTIC_LONGITUDE_EPOCH - ECLIPTIC_LONGITUDE_PERIGEE)
  const sun_true_anomaly =
    2 * todeg(Math.atan(
      Math.sqrt((1.0 + ECCENTRICITY) / (1.0 - ECCENTRICITY)) *
      Math.tan(0.5 * kepler(sun_mean_anomaly, ECCENTRICITY))
    ))
  const sun_ecliptic_longitude =
    ECLIPTIC_LONGITUDE_PERIGEE + sun_true_anomaly
  const sun_orbital_distance_factor =
    (1 + ECCENTRICITY * dcos(sun_true_anomaly)) /
    (1 - ECCENTRICITY * ECCENTRICITY)

  // calculate moon position
  const moon_mean_longitude =
    MOON_MEAN_LONGITUDE_EPOCH + 13.1763966 * day
  const moon_mean_anomaly =
    moon_mean_longitude - 0.1114041 * day - MOON_MEAN_PERIGEE_EPOCH
  const moon_evection =
    1.2739 * dsin(
      2 * (moon_mean_longitude - sun_ecliptic_longitude) - moon_mean_anomaly
    )
  const moon_annual_equation =
    0.1858 * dsin(sun_mean_anomaly)
  // XXX: what is the proper name for this value?
  const moon_mp =
    moon_mean_anomaly +
    moon_evection -
    moon_annual_equation -
    0.37 * dsin(sun_mean_anomaly)
  const moon_equation_center_correction =
    6.2886 * dsin(moon_mp)
  const moon_corrected_longitude =
    moon_mean_longitude +
    moon_evection +
    moon_equation_center_correction -
    moon_annual_equation +
    0.214 * dsin(2.0 * moon_mp)
  const moon_age =
    fixangle(
      moon_corrected_longitude -
      sun_ecliptic_longitude +
      0.6583 * dsin(
        2 * (moon_corrected_longitude - sun_ecliptic_longitude)
      )
    )
  const moon_distance =
    (MOON_SMAXIS * (1.0 - MOON_ECCENTRICITY * MOON_ECCENTRICITY)) /
    (1.0 + MOON_ECCENTRICITY * dcos(moon_mp + moon_equation_center_correction))

  return {
    phase: (1.0 / 360.0) * moon_age,
    illuminated: 0.5 * (1.0 - dcos(moon_age)),
    age: (SYNODIC_MONTH / 360.0) * moon_age,
    distance: moon_distance,
    angular_diameter: MOON_ANGULAR_SIZE_SMAXIS / moon_distance,
    sun_distance: SUN_SMAXIS / sun_orbital_distance_factor,
    sun_angular_diameter: SUN_ANGULAR_SIZE_SMAXIS * sun_orbital_distance_factor
  }
}
287891
private long getYearOffsetInMillis() {
        long t = (internalGet(DAY_OF_YEAR) - 1) * 24;
        t += internalGet(HOUR_OF_DAY);
        t *= 60;
        t += internalGet(MINUTE);
        t *= 60;
        t += internalGet(SECOND);
        t *= 1000;
        return t + internalGet(MILLISECOND) -
            (internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET));
    }
1218578
def last_quarter():
        
        since, until = Date.this_quarter()
        since = since.date - delta(months=3)
        until = until.date - delta(months=3)
        return Date(since), Date(until)
424177
private static int firstIslamicStartYearFromGrego(int year) {
        // ad hoc conversion, improve under #10752
        // rough est for now, ok for grego 1846-2138,
        // otherwise occasionally wrong (for 3% of years)
        int cycle, offset, shift = 0;
        if (year >= 1977) {
            cycle = (year - 1977) / 65;
            offset = (year - 1977) % 65;
            shift = 2*cycle + ((offset >= 32)? 1: 0);
        } else {
            cycle = (year - 1976) / 65 - 1;
            offset = -(year - 1976) % 65;
            shift = 2*cycle + ((offset <= 32)? 1: 0);
        }
        return year - 579 + shift;
    }
467015
def dePeriod(arr):
    """"""
    diff= arr-nu.roll(arr,1,axis=1)
    w= diff < -6.
    addto= nu.cumsum(w.astype(int),axis=1)
    return arr+_TWOPI*addto
1056890
def _end_of_century(self):
        
        year = self.year - 1 - (self.year - 1) % YEARS_PER_CENTURY + YEARS_PER_CENTURY

        return self.set(year, 12, 31, 23, 59, 59, 999999)
71056
def _is_leap_year(year):
    
    isleap = ((np.mod(year, 4) == 0) &
              ((np.mod(year, 100) != 0) | (np.mod(year, 400) == 0)))
    return isleap
16669
def compute_moon
      # === 月が光を発した時刻 t1(jd) の計算
      t_1_jd = calc_t1(:moon, @tdb)
      # === 時刻 t1(= TDB) におけるの位置・速度（ICRS 座標）の計算 (地球, 月, 太陽)
      Const::BODIES.each { |k, v| @icrs_1[k] = get_icrs(v, t_1_jd) }
      # === 時刻 t2 における地球重心から時刻 t1 における月への方向ベクトルの計算
      v_12 = calc_unit_vector(@icrs_2[:earth][0,3], @icrs_1[:moon][0,3])
      # === GCRS 座標系: 光行差の補正（方向ベクトルの Lorentz 変換）
      dd = conv_lorentz(v_12)
      pos_moon = calc_pos(dd, @r_e[:moon])
      # === 瞬時の真座標系: GCRS への bias & precession（歳差） & nutation（章動）の適用
      bpn = EphBpn.new(@tdb.strftime("%Y%m%d%H%M%S"))
      pos_moon_bpn = bpn.apply_bpn(pos_moon)
      # === 座標変換
      eq_pol_m  = MkCoord.rect2pol(pos_moon_bpn)
      ec_rect_m = MkCoord.rect_eq2ec(pos_moon_bpn, bpn.eps)
      ec_pol_m  = MkCoord.rect2pol(ec_rect_m)
      # === 視半径／（地平）視差計算
      radius = Math.asin(@am / (eq_pol_m[2] * Const::AU / 1000))
      radius *= 180 / Math::PI * 3600
      parallax = Math.asin(@re / (eq_pol_m[2] * Const::AU / 1000))
      parallax *= 180 / Math::PI * 3600
      return [eq_pol_m, ec_pol_m, [radius, parallax]]
    rescue => e
      raise
    end
363941
def S2L(dd, mm, yy, timeZone=7):
    ''''''
    dayNumber = jdFromDate(dd, mm, yy)
    k = int((dayNumber - 2415021.076998695) / 29.530588853)
    monthStart = getNewMoonDay(k + 1, timeZone)
    if (monthStart > dayNumber):
        monthStart = getNewMoonDay(k, timeZone)
    # alert(dayNumber + " -> " + monthStart)
    a11 = getLunarMonth11(yy, timeZone)
    b11 = a11
    if (a11 >= monthStart):
        lunarYear = yy
        a11 = getLunarMonth11(yy - 1, timeZone)
    else:
        lunarYear = yy + 1
        b11 = getLunarMonth11(yy + 1, timeZone)
    lunarDay = dayNumber - monthStart + 1
    diff = int((monthStart - a11) / 29.)

    lunarLeap = 0
    lunarMonth = diff + 11

    if (b11 - a11 > 365):
        leapMonthDiff = \
            getLeapMonthOffset(a11, timeZone)
        if (diff >= leapMonthDiff):
            lunarMonth = diff + 10
            if (diff == leapMonthDiff):
                lunarLeap = 1
    if (lunarMonth > 12):
        lunarMonth = lunarMonth - 12
    if (lunarMonth >= 11 and diff < 4):
        lunarYear -= 1
    # print [lunarDay, lunarMonth, lunarYear, lunarLeap]
    return \
        [lunarDay, lunarMonth, lunarYear, lunarLeap]
857300
public static Years<CalendarUnit> between(CalendarMonth m1, CalendarMonth m2) {

        int delta = m1.getYear() - m2.getYear();

        if (delta > 0) {
            if (m2.getMonth().compareTo(m1.getMonth()) < 0) {
                delta--;
            }
        } else if (delta < 0) {
            if (m2.getMonth().compareTo(m1.getMonth()) > 0) {
                delta++;
            }
        }

        return Years.ofGregorian(delta);

    }
466374
def getMoonPhase(self):
        
        sun = self.getObject(const.SUN)
        moon = self.getObject(const.MOON)
        dist = angle.distance(sun.lon, moon.lon)
        if dist < 90:
            return const.MOON_FIRST_QUARTER
        elif dist < 180:
            return const.MOON_SECOND_QUARTER
        elif dist < 270:
            return const.MOON_THIRD_QUARTER
        else:
            return const.MOON_LAST_QUARTER
43004
def rollforward(self, date):
        """"""
        if self.onOffset(date):
            return date
        else:
            return date + YearEnd(month=self.month)