Beispiel #1
0
    def test_period_inequality(self):
        period_1 = Period((2007, 1, 1), (2008, 1, 1))
        period_2 = Period((2007, 3, 4), (2007, 5, 17))
        self.assertTrue(period_1 != period_2)

        period_3 = Period((2007, 1, 1), (2008, 1, 1))
        self.assertFalse(period_1 != period_3)
Beispiel #2
0
    def test_period_equality(self):
        period_1 = Period((2007, 1, 1), (2008, 1, 1))
        period_2 = Period((2007, 1, 1), (2008, 1, 1))
        self.assertTrue(period_1 == period_2)

        period_3 = Period((2009, 1, 1), (2010, 1, 1))
        self.assertFalse(period_1 == period_3)
Beispiel #3
0
 def test_period_greater_than_equal(self):
     period_1 = Period((2007, 1, 1), (2008, 1, 1))
     period_2 = Period((2007, 2, 4), (2007, 5, 17))
     period_3 = Period((2007, 1, 1), (2008, 1, 1))
     self.assertTrue(period_2 >= period_1)
     self.assertTrue(period_3 >= period_1)
     self.assertFalse(period_1 >= period_2)
Beispiel #4
0
def plotAccounts(ledger,
                 accountLists,
                 timeframe,
                 xlabel,
                 ylabel,
                 labels,
                 smooth=False,
                 invert=None,
                 totals=False):
    print(accountLists)
    if invert is None:
        invert = [False for _ in accountLists]
    dates = [
        d.start for d in util.subdivideTime(timeframe, Period(config.month))
    ]
    data = [
        getQuery(ledger,
                 accountList,
                 timeframe,
                 Period(config.month),
                 invert=invert,
                 totals=totals)
        for (accountList, invert) in zip(accountLists, invert)
    ]
    if smooth:
        dates = smoothDates(dates, N=smooth)
        data = [smoothData(d, N=smooth) for d in data]
    datePlot(dates, data, xlabel=xlabel, ylabel=ylabel, labels=labels)
Beispiel #5
0
 def test_period_less_than_equal(self):
     period_1 = Period((2007, 1, 1), (2008, 1, 1))
     period_2 = Period((2007, 3, 4), (2007, 5, 17))
     period_3 = Period((2007, 1, 1), (2008, 1, 1))
     self.assertTrue(period_1 <= period_2)
     self.assertTrue(period_1 <= period_3)
     self.assertFalse(period_2 <= period_1)
Beispiel #6
0
    def test_sensor_pair_get_secondary(self):
        sensor_1 = Sensor('avhrr-m01', Period((2007, 1, 1), (2008, 1, 1)))
        sensor_2 = Sensor('avhrr-m02', Period((2007, 7, 1), (2008, 7, 1)))

        sensor_pair = SensorPair(sensor_1, sensor_2)
        secondary = sensor_pair.get_secondary()
        self.assertEqual('avhrr-m02', secondary.get_name())
Beispiel #7
0
    def test_sensor_pair_equality(self):
        sensor_1 = Sensor('atsr-en', Period((2007, 1, 1), (2008, 1, 1)))
        sensor_2 = Sensor('atsr-e2', Period((2007, 7, 1), (2008, 7, 1)))

        sensor_pair_1 = SensorPair(sensor_1, sensor_2)
        sensor_pair_2 = SensorPair(sensor_2, sensor_1)
        self.assertTrue(sensor_pair_1 == sensor_pair_2)
Beispiel #8
0
    def test_get_effective_production_period_one_sensor_with_workflow_period(
            self):
        w = Workflow('test', 2, 'config', Period((1994, 1, 1), (1994, 12, 31)))
        w.add_primary_sensor('avhrr.n11', (1988, 11, 8), (1994, 12, 31))

        period = w._get_effective_production_period()
        self.assertEqual(Period((1994, 1, 1), (1994, 12, 31)), period)
Beispiel #9
0
    def test_sensor_pair_construction_with_production_period(self):
        sensor_1 = Sensor('avhrr-n12', Period((2007, 1, 1), (2008, 1, 1)))
        sensor_2 = Sensor('avhrr-n13', Period((2007, 7, 1), (2008, 7, 1)))

        sensor_pair = SensorPair(sensor_1, sensor_2,
                                 Period((2007, 8, 1), (2007, 9, 1)))
        self.assertEqual(Period((2007, 8, 1), (2007, 9, 1)),
                         sensor_pair.get_period())
Beispiel #10
0
    def test_period_grow_inside(self):
        period_1 = Period((1980, 1, 1), (1980, 5, 31))
        period_2 = Period((1980, 2, 1), (1980, 3, 1))

        grown = period_1.grow(period_2)

        self.assertFalse(grown)
        self.assertEqual(Period((1980, 1, 1), (1980, 5, 31)), period_1)
Beispiel #11
0
    def test_period_grow_not_intersecting(self):
        period_1 = Period((1980, 1, 1), (1980, 5, 31))
        period_2 = Period((1980, 6, 1), (1980, 11, 1))

        grown = period_1.grow(period_2)

        self.assertFalse(grown)
        self.assertEqual(Period((1980, 1, 1), (1980, 5, 31)), period_1)
Beispiel #12
0
    def test_period_grow_not_intersecting(self):
        period_1 = Period((1980, 1, 1), (1980, 5, 31))
        period_2 = Period((1980, 6, 1), (1980, 11, 1))

        grown = period_1.grow(period_2)

        self.assertFalse(grown)
        self.assertEqual(Period((1980, 1, 1), (1980, 5, 31)), period_1)
Beispiel #13
0
    def test_period_grow_inside(self):
        period_1 = Period((1980, 1, 1), (1980, 5, 31))
        period_2 = Period((1980, 2, 1), (1980, 3, 1))

        grown = period_1.grow(period_2)

        self.assertFalse(grown)
        self.assertEqual(Period((1980, 1, 1), (1980, 5, 31)), period_1)
Beispiel #14
0
    def test_sensor_ge(self):
        sensor_1 = Sensor('atsr-en', Period((2007, 1, 1), (2008, 1, 1)))
        sensor_2 = Sensor('atsr-e2', Period((2008, 1, 1), (2009, 1, 1)))
        self.assertTrue(sensor_1 >= sensor_2)

        sensor_3 = Sensor('atsr-e2', Period((2009, 1, 1), (2010, 1, 1)))
        self.assertTrue(sensor_2 >= sensor_3)
        self.assertTrue(sensor_3 >= sensor_2)
Beispiel #15
0
    def test_sensor_pair_construction_with_production_period_invalid(self):
        sensor_1 = Sensor('avhrr-n12', Period((2007, 1, 1), (2008, 1, 1)))
        sensor_2 = Sensor('avhrr-n13', Period((2007, 7, 1), (2008, 7, 1)))

        try:
            SensorPair(sensor_1, sensor_2, Period((2000, 8, 1), (2000, 9, 1)))
            self.fail("ValueError exoected")
        except ValueError:
            pass
Beispiel #16
0
    def test_get_next_period_cut_at_month_end(self):
        w = Workflow('test', 10)

        date = datetime.date(2001, 9, 22)
        next_period = w._get_next_period(date)
        self.assertEqual(Period((2001, 9, 23), (2001, 9, 30)), next_period)

        next_period = w._get_next_period(next_period.get_end_date())
        self.assertEqual(Period((2001, 10, 1), (2001, 10, 10)), next_period)
Beispiel #17
0
    def test_get_next_period_overlap_year(self):
        w = Workflow('test', 7)

        date = datetime.date(2001, 12, 26)
        next_period = w._get_next_period(date)
        self.assertEqual(Period((2001, 12, 27), (2001, 12, 31)), next_period)

        next_period = w._get_next_period(next_period.get_end_date())
        self.assertEqual(Period((2002, 1, 1), (2002, 1, 7)), next_period)
Beispiel #18
0
    def test_sensor_pair_ge(self):
        sensor_1 = Sensor('atsr-en', Period((2007, 1, 1), (2008, 1, 1)))
        sensor_2 = Sensor('atsr-e2', Period((2007, 7, 1), (2008, 7, 1)))
        sensor_3 = Sensor('atsr-e1', Period((2007, 10, 1), (2008, 10, 1)))

        sensor_pair_1 = SensorPair(sensor_1, sensor_2)
        sensor_pair_2 = SensorPair(sensor_2, sensor_3)
        sensor_pair_3 = SensorPair(sensor_1, sensor_3)
        self.assertTrue(sensor_pair_1 >= sensor_pair_2)
        self.assertTrue(sensor_pair_1 >= sensor_pair_3)
Beispiel #19
0
    def test_add_get_primary_sensors_multiple(self):
        w = Workflow('test', 5)
        w.add_primary_sensor('atsr-e2', '1995-06-01', '1996-01-01')
        w.add_primary_sensor('atsr-e1', '1991-06-01', '1995-01-01')
        w.add_primary_sensor('atsr-en', '1996-01-01', '1998-01-01')

        sensors = w._get_primary_sensors()
        self.assertEqual([
            Sensor('atsr-en', Period((1996, 1, 1), (1998, 1, 1))),
            Sensor('atsr-e2', Period((1995, 6, 1), (1996, 1, 1))),
            Sensor('atsr-e1', Period((1991, 6, 1), (1995, 1, 1)))
        ], sensors)
Beispiel #20
0
    def test_add_get_secondary_sensors_multiple(self):
        w = Workflow('test', 9)
        w.add_secondary_sensor('atsr-e2', '1996-06-01', '1997-01-01')
        w.add_secondary_sensor('atsr-e1', '1992-06-01', '1996-01-01')
        w.add_secondary_sensor('atsr-en', '1997-01-01', '1999-01-01')

        sensors = w._get_secondary_sensors()
        self.assertEqual([
            Sensor('atsr-en', Period((1997, 1, 1), (1999, 1, 1))),
            Sensor('atsr-e2', Period((1996, 6, 1), (1997, 1, 1))),
            Sensor('atsr-e1', Period((1992, 6, 1), (1996, 1, 1)))
        ], sensors)
Beispiel #21
0
    def test_sensor_pair_construction_invalid(self):
        sensor_1 = Sensor('avhrr-n14', Period((2007, 1, 1), (2008, 1, 1)))
        sensor_2 = Sensor('avhrr-n15', Period((2008, 1, 1), (2009, 1, 1)))

        try:
            SensorPair(sensor_1, sensor_2)
            self.fail()
        except exceptions.ValueError:
            pass

        try:
            SensorPair(sensor_2, sensor_1)
        except exceptions.ValueError:
            pass
Beispiel #22
0
    def test_period_ctor(self):
        a = Period()
        self.assertEqual(a.start, 1)
        self.assertEqual(a.end, 1)
        self.assertEqual(a.rate, 0)

        b = Period(start=5, end=10, rate=10)
        self.assertEqual(b.start, 5)
        self.assertEqual(b.end, 10)
        self.assertEqual(b.rate, 10)

        with self.assertRaises(AssertionError):
            c = Period(start=0, end=10, rate=10)

        with self.assertRaises(AssertionError):
            c = Period(start=13, end=10, rate=10)

        with self.assertRaises(AssertionError):
            c = Period(start="time", end=10, rate=10)

        with self.assertRaises(AssertionError):
            c = Period(start=1, end=0, rate=10)

        with self.assertRaises(AssertionError):
            c = Period(start=1, end=13, rate=10)

        with self.assertRaises(AssertionError):
            c = Period(start=1, end="time", rate=10)
Beispiel #23
0
    def test_sensor_pair_construction(self):
        sensor_1 = Sensor('avhrr-n12', Period((2007, 1, 1), (2008, 1, 1)))
        sensor_2 = Sensor('avhrr-n13', Period((2007, 7, 1), (2008, 7, 1)))
        sensor_3 = Sensor('avhrr-n14', Period((2008, 1, 1), (2009, 1, 1)))

        sensor_pair = SensorPair(sensor_1, sensor_2)
        self.assertEqual('avhrr-n12', sensor_pair.get_primary_name())
        self.assertEqual('avhrr-n13', sensor_pair.get_secondary_name())
        self.assertEqual(Period((2007, 7, 1), (2008, 1, 1)),
                         sensor_pair.get_period())

        sensor_pair = SensorPair(sensor_3, sensor_2)
        self.assertEqual('avhrr-n14', sensor_pair.get_primary_name())
        self.assertEqual('avhrr-n13', sensor_pair.get_secondary_name())
        self.assertEqual(Period((2008, 1, 1), (2008, 7, 1)),
                         sensor_pair.get_period())
Beispiel #24
0
 def test_add_get_primary_sensors_version(self):
     w = Workflow('test', 5)
     w.add_primary_sensor('atsr-e2', '1995-06-01', '1996-01-01',
                          'version_5')
     self.assertEqual([
         Sensor('atsr-e2', Period((1995, 6, 1), (1996, 1, 1)), 'version_5')
     ], w._get_primary_sensors())
Beispiel #25
0
def parse(dataset='data/exam_comp_set1.exam'):
    with open(dataset) as f:
        indices = {}
        lines = []
        for i, line in enumerate(f):
            if line.startswith('['):
                indices[determine_header(line)] = i
            lines.append(line.strip())
        exams = parse_data(lines, indices[EXAMS_HEADER],
                           indices[PERIOD_HEADER],
                           lambda x: Exam(int(x[0]), [int(i) for i in x[1:]]))
        periods = parse_data(
            lines, indices[PERIOD_HEADER], indices[ROOM_HEADER],
            lambda x: Period(x[0], x[1], int(x[2]), int(x[3])))
        rooms = parse_data(lines, indices[ROOM_HEADER],
                           indices[PERIOD_CONSTRAINTS_HEADER],
                           lambda x: Room(int(x[0]), int(x[1])))
        period_constraints = parse_constraint(
            lines, indices[PERIOD_CONSTRAINTS_HEADER],
            indices[ROOM_CONSTRAINTS_HEADER], lambda x: PeriodHardConstraint(
                PeriodHardEnum.fromstring(x[1]), int(x[0]), int(x[2])),
            PeriodHardEnum)
        room_constraints = parse_constraint(
            lines, indices[ROOM_CONSTRAINTS_HEADER],
            indices[INSTITUTIONAL_CONSTRAINTS_HEADER],
            lambda x: RoomHardConstraint(RoomHardEnum.fromstring(x[1]),
                                         int(x[0])), RoomHardEnum)
        institutional_constraints = parse_constraint(
            lines, indices[INSTITUTIONAL_CONSTRAINTS_HEADER], len(lines),
            lambda x: InstitutionalConstraint(
                InstitutionalEnum.fromstring(x[0]), [int(i) for i in x[1:]]),
            InstitutionalEnum)
        return exams, periods, rooms, period_constraints, room_constraints, institutional_constraints
Beispiel #26
0
def parse_html_period_row(tr, crn):
    '''
    Creates a Period from a table row.
    '''

    ptype = get_td_text(tr, 3)
    if len(ptype) < 3:
        ptype = "???"

    # If days are empty, then we do not care about this period.
    days = list(
        map(lambda s: DAY_NUMS[s],
            filter(lambda s: len(s) > 0 and s != " ", get_td_text(tr, 6))))
    if len(days) == 0:
        raise PeriodError("Period days are empty.")

    course_summary = ''.join(get_td_text(tr, 1).split()[1:]).strip()
    if len(course_summary) > 0:
        course_summaries[crn] = course_summary
    else:
        course_summary = course_summaries[crn]

    # 9:00 or 10:00
    # Convert from H:MM to HH:MM
    start_time, end_time = determine_times(get_td_text(tr, 7),
                                           get_td_text(tr, 8))

    location = tr.xpath('td[10]')[0].text_content().strip()

    return Period(crn, course_summary, ptype, days, start_time, end_time,
                  location)
def parse_periods(f):
    nr_periods = parse_int_from_header(f.readline())
    periods = {}
    for i in range(nr_periods):
        vals = f.readline().split((','))
        periods[i] = Period(vals[0], vals[1], int(vals[2]), int(vals[3]))
    return periods
Beispiel #28
0
    def test_get_effective_production_period_many_sensors(self):
        w = Workflow('test', 2)
        w.add_primary_sensor('avhrr.n11', (1988, 11, 8), (1994, 12, 31))
        w.add_primary_sensor('avhrr.n12', (1991, 9, 16), (1998, 12, 14))
        w.add_secondary_sensor('avhrr.n10', (1986, 11, 17), (1991, 9, 16))

        period = w._get_effective_production_period()
        self.assertEqual(Period((1988, 11, 8), (1991, 9, 16)), period)
Beispiel #29
0
    def test_period_is_intersecting(self):
        period_1 = Period((1999, 7, 14), (2000, 2, 21))
        period_2 = Period((1998, 3, 4), (1999, 10, 2))
        self.assertTrue(period_1.is_intersecting(period_2))
        self.assertTrue(period_2.is_intersecting(period_1))

        period_3 = Period((1999, 7, 14), (2000, 2, 21))
        period_4 = Period((2000, 2, 23), (2001, 1, 12))
        self.assertFalse(period_3.is_intersecting(period_4))
        self.assertFalse(period_4.is_intersecting(period_3))
Beispiel #30
0
def getBudgetDict(budgetFilename: Path) -> Dict:
    with budgetFilename.open("r") as f:
        budgetDict = yaml.load(f, Loader=yaml.SafeLoader)
        assert config.periodIdentifier in budgetDict
        budgetDict[config.periodIdentifier] = Period(budgetDict[config.periodIdentifier])
        assert config.accountsIdentifier in budgetDict
    for (k, v) in budgetDict[config.accountsIdentifier].items():
        budgetDict[config.accountsIdentifier][k] = Amount(v.replace(config.currency, ""))
    return budgetDict
Beispiel #31
0
    def add_primary_sensor(self, name, start_date, end_date, version=''):
        """

        :type name: str
        """
        period = Period(start_date, end_date)
        for sensor in self._get_primary_sensors():
            if sensor.get_name() == name and sensor.get_period().is_intersecting(period):
                raise ValueError("Periods of sensor '" + name + "' must not intersect.")
        if version == '':
            self.primary_sensors.add(Sensor(name, period))
        else:
            self.primary_sensors.add(Sensor(name, period, version))
Beispiel #32
0
 def test_loadAndSaveStudyPlan2(self):
     plannerIO = PlannerIO()
     studyPlan = plannerIO.loadStudyPlan('outputFile.csv')
     year1, period1 = studyPlan.getCourse('matematiikka 2')
     self.assertEqual(0, year1, 'wrong year')
     self.assertEqual(Period(Period.III, Period.IV), period1,
                      'wrong period')
     year2, period2 = studyPlan.getCourse('puhekurssi')
     self.assertEqual(-1, year2, 'wrong year')
     self.assertEqual(None, period2, 'wrong period')
     year3, period3 = studyPlan.getCourse('kirjoituskurssi')
     self.assertEqual(-2, year3, 'wrong year')
     self.assertEqual(None, period3, 'wrong period')
Beispiel #33
0
    def test_get_period_intersection(self):
        period_1 = Period('2007-01-01', '2008-01-01')
        period_2 = Period('2007-07-01', '2008-07-01')
        period_3 = Period('2007-10-01', '2007-11-01')
        period_4 = Period('2001-07-01', '2002-07-01')

        self.assertEqual(period_1, period_1.get_intersection(period_1))
        self.assertEqual(period_2, period_2.get_intersection(period_2))

        self.assertEqual(Period('2007-07-01', '2008-01-01'), period_1.get_intersection(period_2))
        self.assertEqual(Period('2007-07-01', '2008-01-01'), period_2.get_intersection(period_1))

        self.assertEqual(period_3, period_1.get_intersection(period_3))

        self.assertTrue(period_1.get_intersection(period_4) is None)
Beispiel #34
0
def yearly_selection(args):
    current_year = args.current_month[0]
    current_month = args.current_month[1]
    if args.yearly_selection_type != YearlySelectionType.ABSOLUTE:
        current_end = datetime(
            current_year, current_month,
            last_day_of_month(date(current_year, current_month, 1)).day)
    else:
        current_end = datetime(current_year, 12, 31)

    if args.yearly_selection_type != YearlySelectionType.TODATE:
        previous_end = datetime(
            current_end.year - 1, current_end.month,
            last_day_of_month(date(current_end.year - 1, current_month,
                                   1)).day)
    else:
        previous_end = datetime(current_end.year - 1, 12, 31)
    current_start = previous_end + timedelta(days=1)
    previous_start = datetime(current_start.year - 1, current_start.month,
                              current_start.day)
    return YearlySelection(args.yearly_selection_type,
                           Period(current_start, current_end),
                           Period(previous_start, previous_end))
Beispiel #35
0
 def __init__(self, debug = False):
     self.debug = debug
     self.range = Period()
     self.instructions = {
         'test' : self.test,
         'debug' : self.changeDebug,
         'interactive' : self.interactive,
         'exit' : self.exit,
         'quit' : self.exit,
         'help' : self.help,
         'import' : self.importData,
         'dump' : self.dumpData,
         'weekly' : self.weekly,
         'export' : self.exportData,
         'publish' : self.publishHTML,
         'range' : self.makeRange,
         'filter' : self.filter,
         'rangekilometres' : self.rangeKilometres,
         'run' : self.run,
         '' : self.noOp,
         'races' : self.races,
         'bestfit' : self.bestFit,
         'effectiveness' : self.effectiveness,
         }
Beispiel #36
0
class UI:

    def __init__(self, debug = False):
        self.debug = debug
        self.range = Period()
        self.instructions = {
            'test' : self.test,
            'debug' : self.changeDebug,
            'interactive' : self.interactive,
            'exit' : self.exit,
            'quit' : self.exit,
            'help' : self.help,
            'import' : self.importData,
            'dump' : self.dumpData,
            'weekly' : self.weekly,
            'export' : self.exportData,
            'publish' : self.publishHTML,
            'range' : self.makeRange,
            'filter' : self.filter,
            'rangekilometres' : self.rangeKilometres,
            'run' : self.run,
            '' : self.noOp,
            'races' : self.races,
            'bestfit' : self.bestFit,
            'effectiveness' : self.effectiveness,
            }

    def std_dev(self, nums, mean):
        sum_sq = 0
        for num in nums:
            sum_sq += (num - mean)*(num - mean)
        sum_sq /= float(len(nums))
        std_dev = math.sqrt(sum_sq)
        return std_dev

    def correlation(self, x, y, mean_x, mean_y):
        ab_sum = 0
        aa_sum = 0
        bb_sum = 0
        for xx, yy in zip(x, y):
            a = xx - mean_x
            b = yy - mean_y
            ab_sum += a*b
            aa_sum += a*a
            bb_sum += b*b
        corr = ab_sum / math.sqrt(aa_sum * bb_sum)
        return corr

    def effectiveness(self, data, arguments):
        filtered = data
        if len(arguments) >= 1:
            weeks = int(arguments.split(' ')[0])
        if len(arguments) >= 2:
            filtered = data.filter(arguments.split(' ')[1])
        x = []
        y = []
        for activity in filtered.training:
            newRange = data.range(activity.date - timedelta(days = weeks * 7), activity.date - timedelta(days = 1))
            training = 0
            for trainingRun in newRange.training:
                training += trainingRun.distance
            fitness = activity.fitness()
            if (activity.isRace()):
                fitness = activity.raceFitness()
            if (fitness > 0):
                y.append(fitness)
                x.append(training)

        mean_x = sum(x) / float(len(x))
        mean_y = sum(y) / float(len(y))

        std_dev_x = self.std_dev(x, mean_x)
        std_dev_y = self.std_dev(y, mean_y) 

        corr = self.correlation(x, y, mean_x, mean_y)
       
        slope = corr * (std_dev_y / std_dev_x)
 
        intercept = mean_y - slope * mean_x

        print "slope = %f\nintercept = %f\ncorrelation = %f"%(slope, intercept, corr)

       #     print "%f %f %f %f"%(slope, intercept, r, p)


    def bestFit(self, data, arguments):
        if not self.range:
            print "Define range first"
        else:
            x = []
            y = []
            for activity in self.range.training:
                x.append(activity.date.days)
                y.append(activity.fitness())
            
            #slope, intercept, r, p, stderr = stats.lineregress(x, y)
            
            #print "%.2f Fit/month"%(slope*28)
            
    def races(self, data, arguments):
        for race in data.getRaces():
            print
            print race.summaryString()
            endDate = race.date - timedelta(days = 1)
            sixWeeksPrior = endDate - timedelta(days = 1 + (6 * 7))
            twelveWeeksPrior = endDate - timedelta(days = 1 + (12 * 7))
            sixWeeks = data.range(sixWeeksPrior, endDate)
            twelveWeeks = data.range(twelveWeeksPrior, endDate)
            print "6 week lead-up: %.0fkm"%sixWeeks.kilometres()
            print "12 week lead-up: %.0fkm"%twelveWeeks.kilometres()
            print "Race fitness: %.1f"%race.raceFitness()

    def noOp(self, data, arguments):
        return

    def filter(self, data, arguments):
        tag = arguments
        
        self.range = data.filter(tag)
        
    def run(self, data, arguments):
        filename = arguments
        fileStream = open(filename)

        for line in fileStream:
            self.execute(data, line.strip())

    def makeRange(self, data, arguments):
        (startDate, endDate) = arguments.split(' ', 1)

        self.range = data.range(datetime.strptime(startDate, "%Y-%m-%d").date(), datetime.strptime(endDate, "%Y-%m-%d").date())

    def rangeKilometres(self, data, arguments):
        print "%.2fkm"%self.range.kilometres()

    def publishHTML(self, data, arguments):
        usage = "\
Usage: publish <sourceDir> <intermediateDir> <targetDir> <domain> <password>"

        if not " " in arguments:
            self.error(usage)
            return

        (sourceDir, intermediateDir, targetDir, domain, password) = arguments.split(' ', 4)

        webPublish = WebPublish(sourceDir, intermediateDir, targetDir, domain, password)

        webPublish.publish()

    def exportData(self, data, arguments):
        usage = "\
Usage: export HTMLCharts <filename>\n\
       export HTMLTemplate <outputDirectory> <templateDirectory>\n\
       export HTMLNews <filename>\n"
        if " " in arguments:
            (type, arguments) = arguments.split(' ', 1)
        else:
            self.error(usage)
            return

        if type == "HTMLCharts":
            filename = arguments
            exporter = WebExporter(filename = filename)
        elif type == "HTMLTemplate":
            if " " in arguments:
                (outputDir, templateDir) = arguments.split(' ', 1)
            else:
                self.error(usage)
                return
            exporter = WebExporter(outputDir = outputDir, templateDir = templateDir)
        elif type == "HTMLNews":
            filename = arguments            
            exporter = NewsExporter(filename = filename)
        else:
            self.error("Type '%s' not recognized"%type)
            self.error(usage)
            return

        exporter.publish(data)

    def weekly(self, data, arguments):
        for week in data.getWeeks():
            print "%s %.2f"%(week.startDate.strftime("%Y-%b-%d"), week.kilometres())

    def dumpData(self, data, arguments):
        print "Data:"
        data.dump()
        print "Range:"
        self.range.dump()

    def continuePrompt(self, text):
        print text
        print "Enter 'yes' to continue or any other input to cancel."
        answer = raw_input()
        return(answer == "yes")

    def importData(self, data, arguments):
        usage = "Usage: import Google/Garmin/GoogleForm/GoogleWeb/Races <filename>"
        if " " in arguments:
            (type, filename) = arguments.split(' ', 1)
        else:
            self.error(usage)
            return

        if type == "Google":
            importer = GoogleImporter(filename)
        elif type == "Garmin":
            importer = GarminImporter(filename)
        elif type == "GoogleForm":
            importer = Importer(filename)
        elif type == "GoogleWeb":
            importer = GoogleWebImporter(filename)
        elif type == "Races":
            importer = RacesImporter(filename)
        else:
            self.error("Type '%s' not recognized"%type)
            self.error(usage)
            return

        if not importer.fileExists():
            self.error("File '%s' not found"%filename)
            self.error(usage)
            return

        #if importer.clashingData(data) and \
        #        not self.continuePrompt("Data clash processing %s.  Overwrite existing data with newly imported data?"%filename):
        #    return;

        importer.loadData(data)

    def help(self, data, arguments):
        for instruction in self.instructions:
            print instruction

    def log(self, text):
        if self.debug:
            print text

    def test(self, data, arguments):
        print data
        print arguments

    def error(self, text):
        print text

    def changeDebug(self, data, arguments):
        yes = [ "True",
                "true",
                "TRUE",
                "Yes",
                "yes",
                "YES",
                "On",
                "on",
                "ON",
                "",
                ];
        no = [ "False",
               "false",
               "FALSE",
               "No",
               "no",
               "NO",
               "Off",
               "off",
               "OFF",
               ];
        if arguments in yes:
            self.debug = True;
        elif arguments in no:
            self.debug = False;
        else:
            self.error("Unrecognized Debug parameter: %s"%arguments)

    def interactive(self, data, arguments):
        while True:
            print(">"),
            line = raw_input()
            self.execute(data, line)

    def exit(self, data, arguments):
        sys.exit()

    def execute(self, data, instruction):
        if " " in instruction:
            (command, arguments) = instruction.split(' ', 1)
        else:
            command = instruction
            arguments = ""

        self.log("instruction = '%s'"%instruction)
        self.log("command = '%s'"%command)
        self.log("arguments = '%s'"%arguments)

        if command.lower() in self.instructions:
            self.instructions[command.lower()](data, arguments)
        else:
            self.error("Command %s not recognized"%command)
Beispiel #37
0
 def test_period_is_including(self):
     period_1 = Period((2007, 1, 1), (2008, 1, 1))
     period_2 = Period((2007, 3, 4), (2007, 5, 17))
     self.assertTrue(period_1.is_including(period_2))
     self.assertFalse(period_2.is_including(period_1))
Beispiel #38
0
    def test_period_construction(self):
        period_1 = Period((2007, 1, 1), '2008-01-01')
        self.assertEqual(datetime.date(2007, 1, 1).isoformat(), period_1.get_start_date().isoformat())
        self.assertEqual(datetime.date(2008, 1, 1).isoformat(), period_1.get_end_date().isoformat())

        period_2 = Period('2007-02-01', (2008, 1, 2))
        self.assertEqual(datetime.date(2007, 2, 1).isoformat(), period_2.get_start_date().isoformat())
        self.assertEqual(datetime.date(2008, 1, 2).isoformat(), period_2.get_end_date().isoformat())

        period_3 = Period((2007, 3, 3), datetime.date(2007, 3, 5))
        self.assertEqual(datetime.date(2007, 3, 3).isoformat(), period_3.get_start_date().isoformat())
        self.assertEqual(datetime.date(2007, 3, 5).isoformat(), period_3.get_end_date().isoformat())

        period_4 = Period(datetime.date(1979, 12, 31), (1980, 2, 14))
        self.assertEqual(datetime.date(1979, 12, 31).isoformat(), period_4.get_start_date().isoformat())
        self.assertEqual(datetime.date(1980, 2, 14).isoformat(), period_4.get_end_date().isoformat())